WebMasterCampus
WEB DEVELOPER Resources

JS ES6 Basics

Learn JS ES6 Basics


JS ES6 Basics

Let keyword

The let keyword allows you to declare a variable with block scope.

Let keyword Example


var x = 20;
console.log("x outer scope value: "+x);

{
  let x = 10; 
  console.log("x inner Scope with let : "+x);
}

console.log("x outer scope value: "+x);

Const Keyword

The const keyword allows you to declare a constant(an unchangeable value). const is similar to let, except that it’s value cannot be changed.

Const Keyword Example


var x = 20;
console.log("x outer scope value: "+x);

{
  const x = 10;  // Const x means value cannot be changed
  console.log("x inner Scope with let : "+x);
  
  //x =15; // if you try to update with new value it will raise error.
}

console.log("x outer scope value: "+x);

Function Rest Parameter

The rest parameter allows a function to treat an indefinte number of arguments as array.

Function Rest Parameter Example


function sum(...args){

  let result = 0;

  for(let arg of args)
    result +=  arg;

  return result;
}


console.log(sum(5,6));

Arrow Functions

Arrow functions allows a short syntax for writing function expressions. You don’t need the function keyword the return keyword and the curly brackets.

Arrow Functions Example


var x = function (x,y) { return x*y; }

console.log(x(4,3));

const a = (b,c) => b * c;

console.log ( a(4, 3));

Javascript classes

Javascript classes are template for Javasript objects. We can use class keyword to create class. In addition always use a method name constructor() inside the class.

Javascript classes Example


class Rectangle {
  constructor(height, width) {
    this.height = height;
    this.width = width;
  }
  
  get area() {
    return this.calcArea();
  }
  
  calcArea() {
    return this.height * this.width;
  }
  
  
}


var r = new Rectangle(6,6);

console.log( r.calcArea() );

Template Literals

In ES6, you create a template lieteral by wrapping your text in backticks (`) as follows. Template literals are string literals allowing embedded expressions. You can use multi-line strings and string interpolation features with them.

Template Literals Example


let expression = "embeded here";

console.log(`string message`);

console.log(`string message line 1
 string message line 2`);

console.log(`string message ${expression} as string text`);
Created with love and passion.