JS ES6 Basics

import

import React from 'react';
import {Route, DefaultRoute, NotFoundRoute} from 'react-router';

import {tobecalled} from ‘{packagename}’ import {x, y, z} from ‘{packagename}’ will import only the packages package.x, package.y, and package.z from the package

es6 imports are hoisted, meaning all dependent modules will be loaded before any of the module code is executed

export

function Add(x) {
  return x + x;
}

export default Add;

where export default Add is eqivelent to module.exports = Add;

classes

es6 classes are syntactical sugar over the js prototype-based inheritence is js.

class Box {
  constructor(length, width) {
    this.length = length;
    this.width = width;
  }
  calculateArea() {
    return this.length * this.width;
  }
}

let box = new Box(2, 2);

box.calculateArea(); // 4

you can also use extends to extend an already existing class:

class MyComponent extends React.Component {
  // Now MyComponent contains all React component methods
  // such as componentDidMount(), render() and etc.
}

var vs let

var is scoped to the nearest function block, and let is scope to the nearest enclosing block, which could be a function, for-loop, or an if-statement.

Basically, let is block scoped, var is function scoped.

var a = 5;
var b = 10;

if (a === 5) {
  let a = 4; // The scope is inside the if-block
  var b = 1; // The scope is inside the function

  console.log(a);  // 4
  console.log(b);  // 1
}

console.log(a); // 5
console.log(b); // 1

Arrow Functions (Fat Arrow)

An arrow function expression has a shorter syntax compared to function expressions and lexically binds the this value.

so basically inside an array function the this keyword will point to the parent this of its enclosing block.

// ES6
[1, 2, 3].map(n => n * 2); // [2, 4, 6]

// ES5
[1, 2, 3].map(function(n) { return n * 2; }); // [2, 4, 6]