Top 10 tips for easily consume ES6 core concept
1.Error handling, “try..catch”
Usually, a script “dies” (immediately stops) in case of an error, printing it to console.
But there’s a syntax construct try..catch
that allows us to “catch” errors so the script can, instead of dying, do something more reasonable.
The “try…catch” syntax
The try..catch
construct has two main blocks: try
, and then catch
:
try {// code...} catch (err) {// error handling}
2.comments
As we know from the chapter Code structure, comments can be single-line: starting with //
and multiline: /* ... */
.
We normally use them to describe how and why the code works.
At first, sight, commenting might be obvious, but novices in programming often use them wrongly.
Ideal comments
/**
* Returns x raised to the n-th power.
*
* @param {number} x The number to raise.
* @param {number} n The power, must be a natural number.
* @return {number} x raised to the n-th power.
*/
function pow(x, n) {
...
}
3.Coding Style
Our code must be as clean and easy to read as possible.
That is actually the art of programming — to take a complex task and code it in a way that is both correct and human-readable. A good code style greatly assists in that.
Syntax
Here is a cheat sheet with some suggested rules (see below for more details):
4.Block Bindings
Traditionally, the way variable declarations work has been one tricky part of programming in JavaScript. In most C-based languages, variables (or bindings) are created at the spot where the declaration occurs. In JavaScript, however, this is not the case. Where your variables are actually created depends on how you declare them, and ECMAScript 6 offers options to make controlling scope easier. This chapter demonstrates why classic var
declarations can be confusing, introduces block-level bindings in ECMAScript 6, and then offers some best practices for using them.
5.Var Declarations and Hoisting
Variable declarations using var
are treated as if they are at the top of the function (or global scope, if declared outside of a function) regardless of where the actual declaration occurs; this is called hoisting. For a demonstration of what hoisting does, consider the following function definition:
function getValue(condition) {if (condition) {
var value = "blue";// other codereturn value;
} else {// value exists here with a value of undefinedreturn null;
}// value exists here with a value of undefined
}
6.Block-Level Declarations
Block-level declarations are those that declare variables that are inaccessible outside of given block scope. Block scopes are created:
- Inside of a function
- Inside of a block (indicated by the
{
and}
characters)
Block scoping is how many C-based languages work, and the introduction of block-level declarations in ECMAScript 6 is intended to bring that same flexibility (and uniformity) to JavaScript.
7.Let Declarations
The let
declaration syntax is the same as the syntax for var
. You can basically replace var
with let
to declare a variable, but limit the variable's scope to only the current code block (there are a few other subtle differences discussed a bit later, as well). Since let
declarations are not hoisted to the top of the enclosing block, you may want to always place let
declarations first in the block, so that they are available to the entire block. Here's an example:
function getValue(condition) {if (condition) {
let value = "blue";// other codereturn value;
} else {// value doesn't exist herereturn null;
}// value doesn't exist here
}
8.Constant Declarations
You can also define variables in ECMAScript 6 with the const
declaration syntax. Variables declared using const
are considered constants, meaning their values cannot be changed once set. For this reason, every const
variable must be initialized on the declaration, as shown in this example:
// Valid constant
const maxItems = 30;// Syntax error: missing initialization
const name;
The maxItems
the variable is initialized, so its const
declaration should work without a problem. The name
variable, however, would cause a syntax error if you tried to run the program containing this code because name
is not initialized.
Declaring Objects with Const
A const
declaration prevents modification of the binding and not of the value itself. That means const
declarations for objects do not prevent the modification of those objects. For example:
const person = {
name: "Nicholas"
};// works
person.name = "Greg";// throws an error
person = {
name: "Greg"
}
9.Block Binding in Loops
Perhaps one area where developers most want block-level scoping of variables is within for
loops, where the throwaway counter variable is meant to be used only inside the loop. For instance, it's not uncommon to see code like this in JavaScript:
for (var i=0; i < 10; i++) {
process(items[i]);
}// i is still accessible here
console.log(i); // 10
In other languages, where block-level scoping is the default, this example should work as intended, and only the for
loop should have access to the i
variable. In JavaScript, however, the variable i
is still accessible after the loop is completed because the var
declaration gets hoisted. Using let
instead, as in the following code, should give the intended behavior:
for (let i=0; i < 10; i++) {
process(items[i]);
}// i is not accessible here - throws an error
console.log(i);
In this example, the variable i
only exists within the for
loop. Once the loop is complete, the variable is destroyed and is no longer accessible elsewhere.
10.Global Block Bindings
Another way in which let
and const
are different from var
is in their global scope behavior. When var
is used in the global scope, it creates a new global variable, which is a property on the global object (window
in browsers). That means you can accidentally overwrite an existing global using, such as:
// in a browser
var RegExp = "Hello!";
console.log(window.RegExp); // "Hello!"var ncz = "Hi!";
console.log(window.ncz); // "Hi!"
Emerging Best Practices for Block Bindings
While ECMAScript 6 was in development, there was widespread belief you should use let
by default instead of var
for variable declarations. Many JavaScript developers, let
behave exactly the way they thought var
should have behaved, and so the direct replacement makes logical sense. In this case, you would use const
for variables that needed modification protection.
However, as more developers migrated to ECMAScript 6, an alternate approach gained popularity: use const
by default and only use let
when you know a variable's value needs to change. The rationale is that most variables should not change their value after initialization because unexpected value changes are a source of bugs. This idea has a significant amount of traction and is worth exploring in your code as you adopt ECMAScript 6.