> For the complete documentation index, see [llms.txt](https://yyaozhibo.gitbook.io/qian-duan-xue-xi/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://yyaozhibo.gitbook.io/qian-duan-xue-xi/js/es6-gang-xu/han-shu-de-kuo-zhan/han-shu-can-shu-mo-ren-zhi-de-xiang-guan-sao-cao-zuo.md).

# 函数参数默认值的相关骚操作

## 场景：利用参数默认值指定一个参数不可省略

```javascript
function throwIfMissing() {
  throw new Error('Missing parameter')
}

function foo(mustBeProvided = throwIfMissing()) {
  return mustBeProvided
}

foo()
```

上面代码的 foo 用函数，如果调用的时候没有参数，就会调用默认值 `throwIfMissing` 函数，从而抛出一个错误

从上面代码还可以看到，参数 `mustBeProvided` 的默认值等于 `throwIfMissing` 函数的运行结果（注意函数名 `throwIfMissing` 之后有一对圆括号），这表明参数的默认值不是在定义时执行，而是在运行时执行。如果参数已经赋值，默认值中的函数就不会运行

另外，可以将参数默认值设置为 `undefined` ，表明这个参数是可以省略的

```javascript
function foo(optional = undefined) { ... }
```
