Advertisement
Guest User

Untitled

a guest
Sep 11th, 2019
157
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.24 KB | None | 0 0
  1. ## Question 3
  2. Please explain what is the bug in the following Javascript function, and how to correct it.
  3.  
  4. ```javascript
  5. function createArrayOfFunctions(y) {
  6. var arr = [];
  7. for(var i = 0; i<y; i++) {
  8. arr[i] = function(x) { return x + i; }
  9. }
  10. return arr;
  11. }
  12. ```
  13. ## Answer 3
  14. There is a semantic issue in given Javascript snippet.
  15.  
  16. The variable 'i' is type of 'var', then all createArrayOfFunctions function will share the same value of 'i'.
  17.  
  18. For example
  19.  
  20. ```javascript
  21. let result = createArrayOfFunctions(100);
  22. console.log(result[10](10)); //the output should be 20, but the output is 110
  23. console.log(result[20](10)); //the output should be 30, but the output is 110
  24. console.log(result[30](10)); //the output should be 40, but the output is 110
  25. ```
  26. In above program all the functions share same value of 'i' i.e. 100.
  27.  
  28. Then if we want to get the correct output, we can modify the type of 'i' to let as below:
  29.  
  30. ```javascript
  31. function createArrayOfFunctions(y) {
  32. var arr = [];
  33. for(let i = 0; i<y; i++) {
  34. arr[i] = function(x) { return x + i; }
  35. }
  36. return arr;
  37. }
  38.  
  39. let result = createArrayOfFunctions(100);
  40. console.log(result[10](10)); //the output is 20
  41. console.log(result[20](10)); //the output is 30
  42. console.log(result[30](10)); //the output is 40
  43. ```
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement