Fanis Prodromou
  • Blog
  • About
  • Blog
  • About
Search by typing & pressing enter

YOUR CART

6/10/2018 Comments

let VS var VS const

In the release of ES6 (ECMAScript 2015) a new way of declaring variables in JavaScript has been introduced. Actually 2 new ways. let and const. With these two, we now have 3 different ways to declare variables. var, let, const

What are the differences? The main difference is the scoping 
  • let
    Block scope

  • const
    Block scope

  • var
    Function scope
In nutshell, block scope is the code that is enclosed in curly braces

let

In the code above we are defining the variable num two times. Lines 1 and 3. What we will see in the console.log of lines 4 and 7?

Well, in line 4 we will see 10 and in line 7 we will see 50. Why is that?
​
Although we have the same variable name, the scope is different. The scope of the variable in line 1 is the global while the other's scope is between lines 2 and 5. 

const

The variables that are declared with const have the same behavior like we declare them with let. They are Blocked Scope too.
​
So, what's the difference then? The difference is that the variables are constant and their value won't change during the application execution. 
If we try to change the value of a constant variable, a run-time error will be thrown (const_scope_2.js)
const variables are not immutable
It's a common misconception that since we can not change the value of a variable, then we have an immutability. Well, no! We are not allowed to change the value of a variable by assigning a new object (line 10), but we are allowed to change the value of a property of this object (line 6)

var

Declaring variables with var is error prone as it is easier the value to be changed on any internal scope
Comments
comments powered by Disqus

    Author

    I am an Angular GDE, content creator who loves sharing knowledge

    Follow @prodromouf
    View my profile on LinkedIn

    Tags

    All Angular Angularjs General Graphql Ionic Javascript .net Nodejs Typescript

Proudly powered by Weebly