DEV Community

Ryuto Nishida
Ryuto Nishida

Posted on • Originally published at qiita.com

JavaScript Declaring variables with var/let/const

var (variables)

Redeclared Reassignment Run on old browser(like IE)
is possible true true true

var is function scope.

function foo(){
    var x = 0;
    console.log(x); //output: 0
    var x = 1;
    console.log(x); //output: 1
    x = 2;
    console.log(x); //output: 2
    if (true){
        console.log(x); //output: 2
        x = 3;
        var y = "a";
        console.log(y); //output: a
    }
    console.log(x); //output: 3
    console.log(y); //output: a
}

Variables defined with 'var' can be called within that function because of function scope.

let (variables)

Redeclared Reassignment Run on old browser(like IE)
is possible false true need transpiler(ex Babel)

let is block scope.

function foo(){
    let x = 0;
    console.log(x); //0
    let x = 1; //error  x has already been declared
    console.log(x); //0
    x = 2;
    console.log(x) //2
    if (true){
        console.log(x); //2
        x = 3;
        let y = "a";
        console.log(y); //output: a
    }
    console.log(x); //3
    console.log(y); //error y is not defined
}

The variable y defined in the if statement has scope only within the block of the if statement, so it cannot be used outside of it.

const (constant)

Redeclared Reassignment Run on old browser(like IE)
is possible false false need transpiler(ex Babel)

const is block scope.

function foo(){
    const x = 0;
    console.log(x); //0
    const x = 1; //error x has already been declared
    console.log(x); //0
    x = 2; //error Assignment to constant variable.
    console.log(x); //0
    if (true){
        console.log(x); //0
        const y = "a";
        console.log(y); //a
    }
    console.log(y); //error y is not defined
}

Declaring in const allows you to define immutable values.

But objects are not immutable. For example, see the code below.

function foo(){
    const like = {fruit: "apple", movie:"GODZILLA", food:"sushi"};
    console.log(like); //output: {fruit: "apple", movie: "GODZILLA", food: "sushi"}
    like.food = "rice";
    console.log(like); //output: {fruit: "apple", movie: "GODZILLA", food: "rice"}

    like = {fruit: "grape", movie: "GODZILLA", food: "rice"}; //However, this is not possible.
}

hoisting

Variables declared using the var are hoisted.
But declared using the let and const are not hoisted.

var x = 0;
function foo(){
    console.log(x);//output: undefined
    var x = 1;
    console.log(x);//output: 1
}

Why is undefined output on the first log!

JavaScript sets all variables declared by var in the function to 'undefined' when the function is declared

function foo() { //x and y become undefined in this line
    var x = 0;
    var y = 1;
    let z = 2; //z is initialized at this line.
}

Use properly

Don't use var!
Only allowed when trying on REPL...

Top comments (0)