comparison on var, let and const variable declaration

Introduction
let, const and var are keywords used for variable declarations in JavaScript programming language,

const and let were newly introduced to the programming language in Escmascript es6 or es2016.

Declaration keywords
the syntax of declaring a variable using let keyword is done as;

let {variable name} = value

for const it's done as;

const {variable name} = value

similarly with var;

var {variable name} = value

Scope for 'let' and 'const' variables
let and const declared variables are block scoped that means values assigned remain within the block of assignment;
take for instance;

if(true) {
   const declaration = "declared"
}

console.log(typeof declaration)
// undefined

values remain accessible only within the if block

Scope for 'var' variables
var declared variables are function scoped so variables declared within a function are only accessible within the function it's self for example;

function assign(param){
    var assignment = param;
}

assign('assigned')

console.log(typeof assignment)
// undefined

Outside the scope of the function type of assignment is 'undefined', within the scope of the function it's a String with the value "assigned"

mutability for 'var' and 'let' variables
variables declared using 'var' and 'let' keyword are mutable therefore can be reassigned with a new value;

var typeofvar = []
      typeofvar = {} // true

let me = 'myself'
      me = 'i' // true

Immutability for 'const' variables
const variables are immutable, they can only be assigned once, for example;

const variable = []
      variable.push(10) // true
      variable = 'string' // "TypeError: Assignment to constant variable"

Redeclarations of 'let' and 'const' variables
const and let declared variables cannot be redeclared within their scope once they are declared any attempt to redeclare them will cause the JavaScript runtime to throw an error;

const name = "John" // true
const name = "duke" //
"SyntaxError: Identifier 'name' has already been declared"

Redeclarations of 'var' variables
variables declared using var can be redeclared at anytime in or outside their scope

var name = "duke" // true
var name = "max" // true
var name = "khloe" // true

Comments

Popular posts from this blog

How to make a static http server in nodejs using express

What is 'this.' keyword in JavaScript

Ways of iterating Object properties in JavaScript

Array concat method in JavaScript

How to create promises in JavaScript