Important Hacks About ES6

Block Bindings

Variable Declaration and Hosting

  • var : var declarations are globally scoped or function scoped. var variables can be re-declared and updated within its scope. var is now the weakest signal when you define a variable in JavaScript.
  • Hosting : variables are hoisted to the top of their scope and initialized with a value of undifined.
  • let : let declarations are blocked scoped. let variables can be updated but not re-declared.
  • Hosting : let declarations are hoisted to the top.
  • const : const declarations are blocked scoped. const variables can neither be updated nor re-declared.
  • Hosting : const declarations are hoisted to the top but are not initialized.

Block Binding in Loops

for (var i=0; i < 10; i++) {
process(items[i]);
}

// i is still accessible here
console.log(i); // 10
for (let i=0; i < 10; i++) {
process(items[i]);
}

// i is not accessible here - throws an error
console.log(i);

Global Block Bindings

  • Another way in which let and const are different from var is in their global scope behaviour. When var is used in the global scope, a new property is added to the global object (window in browsers). That means you can overwrite an existing global using var.
// in a browser
var greeting = ‘Say Hello’;
console.log(window.greeting); // Say Hello
var person = ‘Hi there’;
console.log(window.person); // Hi there
  • If you instead use let or const in the global scope, a new binding is created in the global scope but no property is added to the global object. So, here also you can not overwrite a global variable using let or const.
// in a browser
var greeting = ‘Say Hello’;
console.log(window.greeting === greeting); // false
var person = ‘Hi there’;
console.log(window.person); // Hi there
console.log(person in window); // false

Function With Default Parameters

  1. function add(num1, num2 = 20) {
    return num1 + num2
    }
  • num2 = 20; where 20 is a default parameter value.

Unnamed Parameters

Spread Operator

  1. let num = [10, 20, 30]
    console.log(Math.max(...num)) // Output is 30

Block-Level Functions

if (true) {
console.log(typeof doCode); // “function”
function doCode() {
// writting some code
}
doCode();
}
console.log(typeof doCode); // function

Arrow Functions

//have no parameter
const give5 = () => 5;//have single parameter
const doubleIt = num => num * 2;// have multiple parameter
const add = (a, b) => a+ b;
console.log(add(20, 10)); // 30

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store