Aspects of `const` & `let` in ES6+

ES6 resolves various issue we already have encountered in past and introduced new concepts or we can say concepts which are present in other object oriented languages. Now introduced in javascript as well such as class, let, const, arrow function etc. Scoping with var is bit off a confusing area in javascript which affects people specially coming from strongly typed languages.

Let’s see some challenges will using `var` & how it has been handle by let & const.

function varFunc() {
var count = 1;
if (true) {
var x = 2; // same variable!
console.log(x); // 2
}
console.log(x); // 2
}

let statement declares a block scope local variable, optionally initializing it to a value. let might mean a value, or a variable that can be assigned, but not changed.

function letTest() {
let x = 1;
if (true) {
let x = 2; // different variable
console.log(x); // 2
}
console.log(x); // 1
}

Few points to note down in the above example, I am able to define “let x =2” inside my if statement & having different variable, but with let you can’t define again the same variable within scope.

If I tried to define variable x again within same scope with let it won’t allow us and throw syntax error.

> var x = 0;
undefined
> let x = 0;
SyntaxError: Identifier 'x' has already been declared

Another scenario, if I have define variable x with let, it won’t allow even with var to re-define it.

> let x = 0;
undefined
> var x = 0;
SyntaxError: Identifier ‘x’ has already been declared

And the obvious part. But, we can define in different scope & also we can re-assign values at any time.

> let x = 0
undefined
> let x= 1
SyntaxError: Identifier ‘x’ has already been declared
> x = 5
5

Now let’s talk about constant in javascript

const are block-scoped, much like variables defined using the let statement. The value of a constant cannot change through re-assignment, and it can't be re-declared.

Here cannot be reassigned does not mean immutable.

let’s discuss const over examples:

> const pi = 3.14;
> typeof(pi)
'number'

Now let’s try to assign value:

> pi = 4;
> TypeError: Assignment to constant variable.

In case of an array or objects, itself can still be altered.

> const fruits = [“apple”,”mango”];
> fruits.push("orange")
> fruits
[ 'apple', 'mango', 'orange' ]

But as you can see if I am try to push element in array it worked. let’s try to reassign a new array.

> fruits = [“banana”]
TypeError: Assignment to constant variable.

Anonymous functions:

const car = function(){ this.model; this.type;}
> car.model="model s"
'model s'
> car.type="sports"
'sports'
> car.year = "2017"
>car
{ [Function: car] model: 'model s', type: 'sports', year: '2017' }
>car = function(){ this.model}
TypeError: Assignment to constant variable.

Last thing, I would like to point is worth reading is about Why `typeof` is no longer “safe”

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.