Introduction to JS ES6
JS’s ECMAScript 6 revision has additional features over earlier revisions of JS to bring it in line with other programming languages.
- var Keyword in JS
- let Keyword
- const Keyword
- Declaring Functions
- Spread Function and Destructuring
var Keyword in JS
The standard keyword for declaring variables in JS var has three quirks: it has global scope, is hoisted on runtime, and can be re-declared (“duplicated”) outside of it’s local block.
A JS variable declared with keyword var can be declared again:
var x=1;
var x = 100;
console.log(x);
Output:
100
All variables declared with var have global scope:
var x = 1;
console.log(x);
if (true) {
var x = 10;
console.log(x);
}
console.log(x);
Output:
1 10 10
The same behavior persists with different types of code blocks (for(){}, blank curly brackets {}, etc.)
Lastly, any variables declared with the var keyword are hoisted and initialized, other declarations are only hoisted until initialized.
console.log(x);
x = 1;
var x = 1;
Output:
1
let Keyword
ES6 introduces the let keyword, of which variables declared with let behave like variables in other C-family languages.
Unlike var:
- *let* cannot be re-declared
- *let* has local scope, within its own block
- *let* is hoisted but not initialized until it is directly done so in code
Syntax:
let bar = 123;
const Keyword
ES6 introduces the const keyword, which has the same behavior as let, but declares constants. This is similar to the behavior of the final keyword in Java.
Syntax:
const foo = 1;
Constants may not be declared empty in JS.
Declaring Functions
As observed previously, functions can be saved to variables, which can then be used in constructors or as methods:
var foo = function(){
return 1;
}
//constructor
new foo(); // => foo {}
//method
var obj = {ddd:foo};
obj.ddd();
console.log(obj);
Another feature of JS are arrow functions, which act as shorthand for the function keyword.
They are written in the syntax:
VARIABLE = (INPUTS) => [FUNCTION;]
E.x. 1:
const plus = (x,y) => {return x+y};
*is shorthand for*
const plus = function (x,y) {return x+y;}
E.x. 2: Note the function receives null.
const hello = () => {return "hello";}
*is shorthand for*
var hello = function(){return "hello";}
Spread and Destructure
The spread function […] is useful in unpacking lists(arrays) in JS into a string.
let numList = [1, 2, 3];
console.log(numList);
console.log(...numList);
Output:
1, 2, 3 1 2 3
Destructuring expressions are an extension of this concept, allowing lists to be individually assigned to variables.
const arr2 = [4, 5, 6];
const [four, five, six] = arr2;
console.log(four, five, six);
Output:
4, 5, 6
The variables four, five, and six are the variables in which the deconstructed elements of the array of stored in.
-gonkgonk