Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- ## Question 3
- Please explain what is the bug in the following Javascript function, and how to correct it.
- ```javascript
- function createArrayOfFunctions(y) {
- var arr = [];
- for(var i = 0; i<y; i++) {
- arr[i] = function(x) { return x + i; }
- }
- return arr;
- }
- ```
- ## Answer 3
- There is a semantic issue in given Javascript snippet.
- The variable 'i' is type of 'var', then all createArrayOfFunctions function will share the same value of 'i'.
- For example
- ```javascript
- let result = createArrayOfFunctions(100);
- console.log(result[10](10)); //the output should be 20, but the output is 110
- console.log(result[20](10)); //the output should be 30, but the output is 110
- console.log(result[30](10)); //the output should be 40, but the output is 110
- ```
- In above program all the functions share same value of 'i' i.e. 100.
- Then if we want to get the correct output, we can modify the type of 'i' to let as below:
- ```javascript
- function createArrayOfFunctions(y) {
- var arr = [];
- for(let i = 0; i<y; i++) {
- arr[i] = function(x) { return x + i; }
- }
- return arr;
- }
- let result = createArrayOfFunctions(100);
- console.log(result[10](10)); //the output is 20
- console.log(result[20](10)); //the output is 30
- console.log(result[30](10)); //the output is 40
- ```
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement