Using Var and Let in JavaScript


I’ve read this topic multiple times and feel like people explaining it make it too verbose. Here is a link to a jsfiddle example for the code below:

function cat(){
    var cat = 'VAR';
    if(true){
        let cat = 'LET';
        // here the value of cat is "LET"
    }i
    // here the value of cat is "VAR"
}

In the inner if block which executes automatically with if(true) the value of cat will be LET, but outside of this block it will always be VAR. The let declaration is limited in scope to only the block of code it is in, including any nested blocks within it. In the above case this means only inside the if statement.

function cat(){
    let cat;    
    if(true){
        let cat = 'LET';
        // here the value of cat is "LET"
    }
    // here the value of cat is "undefined"
}

If var and let are switched as shown in example code directly below, this will create an error since let cat = 'LET' declares the value to the whole block for the function cat() and it cannot be redeclared. An error message of: “Cannot redeclare block-scoped variable ‘cat’.” will appear using the following code:

function cat(){
    let cat = 'LET';
    if (true){
        var cat = 'VAR';     
    }    
}

The function in the code example directly above causes the same error as the example directly below. “SyntaxError: Identifier ‘cat’ has already been declared”

let cat = 'LET';
var cat = 'VAR';

Here an error will appear saying the same variable cannot be declared twice!

Summary:

In JavaScript the first choice for variables should always be const. If something must change decide whether to use let or var. If possible, it's generally best to use let instead of var since let does a better job with separation of concerns.