Javascript var, let and const with examples.

Var, let and const keywords are used to declare variables in Javascript. Var is the oldest keyword for declaring variables. And let and const are introduced in ES6.

Scope:
Var: function scope
let: Block scope
const: block scope like let but immutable

Assignment:
let and var can be reassigned to a new value while const cannot be reassigned.

Hoisting:
var keyword is hoisted to the top of their scope.
let and const is also hoisted but will throw an error if the variable is used before declaration.

Output questions:

1) What will be the output of the following ?

var name = 'abc'

{
  var name = 'xyz'
  console.log(name) // ??
}

console.log(name) // ??

Answer:

var name = 'abc'
{
  var name = 'xyz'
  console.log(name) // xyz
}

console.log(name) // xyz

2) What is output of the following?

var name = 'abc'

function printName() {
  var name = 'xyz'
  console.log(name) // ??
}

console.log(name) // ??
printName()

Answer:

var name = 'abc'

function printName() {
  var name = 'xyz'
  console.log(name) // xyz
}

console.log(name) // abc
printName()

var outside the function has global namespace while inside the function has function scope.

3) What would be output in the following?

let name = 'abc'
let name = 'xyz'
console.log(name)

Answer

let name = 'abc'
let name = 'xyz' // SyntaxError: Identifier 'fruit' has already been declared
console.log(name)

4) What is the output of the following?

a = 20
var a
console.log(a) // ??

Answer

a = 25
var a
console.log(a) // 20

Why?

Due to the hoisting concept, the above is equivalent to

var a = undefined // placed at the top of the scope
a = 20 // variable assignment
console.log(a) // 20

5) What is the output of the following?

console.log(a) // ??
var a = 222
console.log(a) // ??

Answer

console.log(a) // undefined
var a = 222
console.log(a) // 111

6) What is the output of the following?

var a
console.log(a) // ??
a = 10
console.log(a) // ??

Answer

var a
console.log(a) // undefined
a = 10
console.log(a) // 10

7) What is output of the following?

// let
{ let a = 5 } 
console.log(variable) // ReferenceError: variable is not defined
Explanation: Variable a in local scope (the current block scope)

// var
{ var a = 10 } 
console.log(variable) // 10
Explanation:  Variable a in global scope (the current function scope)

// const
const obj = {name: "abc"} 
obj.name = "xyz" // Object properties are mutable, even the obj is a const
console.log(obj) // obj { name: "xyz" }
obj = {name1: "test"} // TypeError: invalid assignment to const `object', because the variable which assign using const can't be reassign while variable property can be mutate.
Sunil Yadav

About Sunil Yadav

Hi, This is Sunil Yadav, I am full stack dev. I have a passion for learning and sharing my knowledge with others as publicly as possible.

View all posts by Sunil Yadav →

Leave a Reply

Your email address will not be published. Required fields are marked *