Variable scope in JavaScript has been a source of surprises and bugs over the years.
The surprise is because JavaScript only offers function scope and global scope to control the lifetime of a variable. There is no block scope . var doWork = function(flag){ if(flag) { var x = 3; } return x; // x is still available }; var result = doWork(true); expect(result).toBe(3); // PASS!!!!! The ne w le t keyword of 2015will replac e va r for variable declarations and provide true block scoping. let doWork = function(flag) { if(flag){ let x = 3; } return x; // Will give a ReferenceError: x is not defined }; let result = doWork(true); expect(result).toBe(3); Iteration statements also benefit fro m le t . var doWork = function(){ for( let x = 0; x < 3; x++) { // ... le t is the ne w va r ! Wil l le t make JavaScript code better? I doubt i f le t will prevent a significant number of bugs, but I do think JavaScript code will improve. le t is the ne w va r ! Wil l le t make JavaScript code better? I doubt i f le t will prevent a significant number of bugs, but I do think JavaScript code will improve.
We can declare variables close to where we use the variables instead of declaring all local variables at the top of a function, which is a defensive practice followed today to avoi d va r related bugs. We also dont need to introduce a second nested function or immediately invoked function expression (IIFE) only to control the scope of a variable (another defensive practice youll see in JS libraries). The result is that programsusin g le t should be easier to read, and perhaps just a tiny bit safer, too.
const
Th e cons t keyword will give you a read-only variable. Lik e le t , a variable declared wit h cons t will have block scope, and you cannot re-declare a cons t .
Using const
In a perfect world, all the JavaScript environmentswould have a perfect implementation o f cons t .
Using const
In a perfect world, all the JavaScript environmentswould have a perfect implementation o f cons t .
Unfortunately , cons t is one of those keywords that has been around in some runtimes even before the keyword appeared in an official ECMAScript specification. While most runtimes can agree that a cons t should be constant, existing implementations disagree on how to behave when code attempts to assign a new value to a constant. Should the assignment cause a runtime error? Should the assignment fail silently? The official specification say s cons t should fail with a runtime error if a program tries to assign a new value to a constant, and constant declarations without an initializer should be a syntax error. const MAX_SIZE = 10; // MAX_SIZE = 12; // If executed, will result in a SyntaxError I hope it will not take long for all the latest runtimes and browsers to straighten up and behave correctly. The current situation should notstop you from usin g cons t whenever possible because the keyword does have a few benefits.
- cons t tells other programmers about the intended behavior of a variable, and this makes a script easier to maintain.
- cons t tells the runtime about the intended behavior of a variable, which can allow for optimizations across time and space.
Default Parameters
If a JavaScript function takes two parameters, we have always had the ability to invoke the function and pass two parameters, or one parameter, or no parameters, or three parameters if we wanted.
In cases where we do not pass enough parameters, the author of a function might want to specify a default value instead of working wit h undefine d . Before 2015, developers applied default values to incoming parameters usin g | | expressions inside the function. In the following function, if the caller does not pass a value for th e nam e parameter, the code will assign a default of Scott. let doWork = function(name) { name = name || "Scott"; return name; }; In 2015, default values are explicit and appear in the parameter list for a function. let doWork = function(name = "Scott") { return name; }; expect(doWork()).toBe("Scott"); A function can even calculate a default using something more than just a literal expression. let doWork = function(x = Math.random()) { return x; } The default parameter syntax is a good example of how ES2015 provides a clean syntax for a common requirement.
No longer will we have to scan through a functions source code or documentation to discover the defaults. Of course, not all parameters are simple values. A common programming technique for operations involving complex configurations, like an HTTP call, is to accept a single object argument with properties to set the URI, HTTP method, timeout settings, and more. Default parameters are useful in this scenario, too, but well have to wait for later and learn about object destructuring first.
Rest Parameters
A rest parameter allows a function to work with a variable number of arguments. let doWork = function(name, ...numbers){ let result = 0; numbers.forEach(function(n){ result += n; }); return result; }; A caller invokin g doWor k can pass zero or more parameters at the rest parameter position. let doWork = function(name, ...numbers){ let result = 0; numbers.forEach(function(n){ result += n; }); return result; }; A caller invokin g doWor k can pass zero or more parameters at the rest parameter position.
You can say th e number s argument will take the rest of the parameters a caller passest o doWor k , and number s will hold the parameters in an array. In the following example , number s will reference an array with the values 1, 2, 3. let result = doWork("Scott", 1, 2, 3); expect(result).toBe(6); In the case where a caller passes no parameters in the rest parameter position, the rest parameter will be an empty array. let doWork = function(...numbers){ return numbers; }; let result = doWork(); expect(result.length).toBe(0); Before 2015, we could allow callers to pass a variable number of arguments to a function by using the implicit arguments variable inside of the function. The arguments variable contains all the parameters to a function in an array-like object, but arguments isnot an array, which creates confusion. It is also difficult to spot if a function is usin g argument s without reading through the code or documentation for the function.
Rest parameters will avoid confusion by always giving us a true array, and by using a dedicated syntax that makes rest parameters easy to spot when reading the function signature.