June 2018
Beginner
288 pages
6h 31m
English
var does not have block scope and, in the past, that led developers to use a JavaScript design pattern known as Immediately Invoked Function Expression (IIFE) or the Self-Executing Anonymous Function. This pattern was also used to hide variables and functions from outside visibility. In this pattern, lines of code are wrapped inside an anonymous function that is immediately executed.
For example, in the following code, the variable sqrt defined within the block is hoisted to the top of the file and becomes unintentionally available outside of the intended scope.
| | //BROKEN CODE |
| | 'use strict'; |
| | |
| | var result = 0; |
| | for(var i = 0; i < 5; i++) { |
| | var sqrt = Math.sqrt(i); |
| | result += sqrt; |
| | } |
| | |
| | console.log(result); ... |
Read now
Unlock full access