JavaScript: ES6 Features

Sheetal Jain
2 min readNov 28, 2020

What is JavaScript?

JavaScript is a cross-platform, object-oriented scripting language used to make webpages interactive (e.g., having complex animations, clickable buttons, popup menus, etc.). It is also one of the core technologies of the web, along with HTML and CSS.

Getting started with JavaScript is easy: all you need is a modern Web browser. Here I will include one of the ES6 JavaScript features i.e let and const:

1. let and const :

one of the biggest problems with declaring variables with the var keyword is that you can overwrite variable declarations without an error.

    var camper = "James";
var camper = "David";
console.log(camper);//logs David

A new keyword let was introduced in ES6 to solve this issue.

when you declare a variable with the var keyword it is declared globally or locally if declared inside a function,let keyword behaves similarly but its scope is limited to the block, statement or expression.

var printNumTwo;
for(var i=0; i<3; i++){
if(i===2){
printNumTwo = function()
{
return i;
};
}
}
console.log(printNumTwo()); //returns 3

As you can see, printNumTwo()prints 3 and not 2 because the value assigned to i was updated and the printNumTwo()returns the global i and not the value i had when the function was created in the loop.

let printNumTwo;
for(let i=0; i<3; i++){
if(i===2){
printNumTwo = function()
{
return i;
};
}
}
console.log(printNumTwo()); //returns 2
console.log(i); /returns "i" is not defined

i is not defined because it was not declared in the global scope. It is only declared within the for loop statement. printNumTwo() returned the correct value because three different i variables with unique values (0, 1, and 2) were created by the let keyword within the loop statement.

In ES6, you can also declare variables using the const keyword. Once the variable is assigned with const , it cannot be reassigned.

  const Fav_Pet = "cats";
Fav_Pet = "Dogs"; // returns error

Mutate an Array declared with const:

   const S = [5,6,7];
S = [1,2,3]; // throws error ,trying to assign a const
S[2] = 45; // works just as it would with an array declared
console.log(S); // returns [5,6,45]

To ensure that data doesn’t change JavaScript provides a function object.freeze to prevent data mutation.

     let obj = {
name: "JavaScript ES6 Features",
review : "Awesome"
};
object.freeze(obj);
obj.review = "bad" ; // will be ignored,mutation not allowed
console.log(obj);

This was all about let and const. In the next blog, I’ll share about Arrow functions.

--

--