--- id: 587d7b8e367417b2b2512b5e title: Avoid Mutations and Side Effects Using Functional Programming challengeType: 1 videoUrl: '' localeTitle: 使用功能编程避免突变和副作用 --- ## Description
如果您还没有弄明白,上一次挑战中的问题是使用tabClose()函数中的splice调用。不幸的是, splice更改了它所调用的原始数组,因此对它的第二次调用使用了一个修改过的数组,并给出了意想不到的结果。这是一个更大模式的一个小例子 - 你在一个变量,数组或一个对象上调用一个函数,该函数改变了对象中的变量或其他东西。函数式编程的核心原则之一是不改变事物。变化导致错误。知道你的函数不会改变任何东西,包括函数参数或任何全局变量,更容易防止错误。前面的例子没有任何复杂的操作,但是splice方法改变了原始数组,并导致了一个bug。回想一下,在函数式编程中,改变或改变事物称为mutation ,结果称为side effect 。理想情况下,函数应该是pure function ,这意味着它不会产生任何副作用。让我们尝试掌握这门学科,不要改变代码中的任何变量或对象。
## Instructions
填写函数incrementer的代码,使其返回全局变量fixedValue的值增加1。
## Tests
```yml tests: - text: 您的函数incrementer不应更改fixedValue的值。 testString: 'assert(fixedValue === 4, "Your function incrementer should not change the value of fixedValue.");' - text: 您的incrementer函数应返回一个大于fixedValue值的值。 testString: 'assert(newValue === 5, "Your incrementer function should return a value that is one larger than the fixedValue value.");' ```
## Challenge Seed
```js // the global variable var fixedValue = 4; function incrementer () { // Add your code below this line // Add your code above this line } var newValue = incrementer(); // Should equal 5 console.log(fixedValue); // Should print 4 ```
## Solution
```js // solution required ```