Everything You Need to Know About Let in Javascript

The let keyword in Javascript was introduced in 2015 with ES6. Just like var in Javascript, let keyword is also used for variable declaration. But the only difference is the variable declared with the “let” keyword is block-scoped and local variable. A variable declared with let will be out of scope outside the block within which it has been declared.

Let us see the syntax for this,

let name1 [= val1] [, name2 [= val2]] [, ..., namen [= valn];

Parameters:

The names of those variables which are to be declared like name1, name2, namen etc, each of them must be a legal Javascript identifier. Even for those declared variables, you can also specify their values initially though it’s optional.

let { bar } = foo; // where foo = { bar:10, baz:12 };

/* This creates a variable with the name 'bar', which has a value of 10 */

You can also use destructuring assignments:

This is generally used for unpacking the values from arrays, or you can also say the properties from the variables into distinct variables.

Here's How to Land a Top Software Developer Job

Full Stack Developer - MERN StackExplore Program
Here's How to Land a Top Software Developer Job

Now let’s see its code implementation:

let x, y, remain;

[x, y] = [10, 20];

console.log(x);

// expected output: 10

console.log(y);

// expected output: 20

[x, y, ...remain] = [10, 20, 30, 40, 50];

console.log(remain);

// expected output array : [30,40,50]

Global Scope

The variables which have been declared globally, those variables become “Global”.

That means they can be used anywhere, and all scripts and functions can access them on a web page.

let languageName = "Java";

// code here can use languageName

function myFunction() {

// code here can also use languageName

}

Now you will look at, what is Function scope:

The variables which have been declared within a function in Javascript are generally known as Local variables and their scope is local.

// code here can NOT use languageName

function myFunction() {

    let languageName = "Java";

    // code here CAN use languageName

  }

  // code here can NOT use languageName

All the local variables can only be accessed from within your function.

In Javascript each function has its own scope (function scope), the variables which are declared inside the function or the function scope, those variables cannot be accessed outside the function. The variables which are declared with let, var, and const behave the same when they are declared inside a function.

function myFunction() {

    var languageName = "Java";   // Function Scope

  }

Now you will look at what Block scope is:

Before the evolution of Javascript ES6, Javascript had only two scopes and those two scopes are Global and Function scope.

But with the evolution of ES6  in 2015, Javascript had introduced another scope called “Block Scope” and with which it had also introduced two different keywords for variable declaration, called “let” and “const” and these two keywords support the Block scope phenomena.

Here's How to Land a Top Software Developer Job

Full Stack Developer - MERN StackExplore Program
Here's How to Land a Top Software Developer Job

The concept of Block scope basically says a variable that has been declared inside the “{ }” block can not be accessed outside the block.

{

    let a = 100;

}

  // a CAN be used here

Now, you will see emulating private members in Javascript:

Basically, constructors make the private variables.

function Container(param) {

    this.member = param;

    var secret = 3;

    var that = this;

}

In the above code, you can see three private instances of variables have been made by the constructor, these are only accessible to the private methods. The inner functions of the constructor are generally known as the private methods.

function Container(param) {

    function dec() {

        if (secret > 0) {

            secret -= 1;

            return true;

        } else {

            return false;

        }

    }

    this.member = param;

    var secret = 3;

    var that = this;

}

In the above code dec is a private method and it is used to examine the secret instance variable. If it comes to be secret, then it decrements the secret and will return true. If not then it returns false.

Redeclaration

If you talk about the redeclaration of variables in Javascript, then you can say that in Javascript redeclaring of variables that have been declared with “var” is allowed anywhere within your program or code.

The following is the code implementation:

var a = 1;

// Now a is 1

var a = 2;

// Now a is 2

In javascript redeclaration of variables that have been declared with the “let” keyword within the same block is not allowed.

Look at the code implementation for this:

var a = 2;    // Allowed

let a = 3;    // Not allowed

{

let a = 2;    // Allowed

let a = 3     // Not allowed

}

{

let a = 2;    // Allowed

var a = 3     // Not allowed

}

Whereas, redeclaration of variables with “let” keywords within another variable is allowed in Javascript:

let a = 1;    // Allowed

{

let a = 2;    // Allowed

}

{

let a = 3;    // Allowed

}

Here's How to Land a Top Software Developer Job

Full Stack Developer - MERN StackExplore Program
Here's How to Land a Top Software Developer Job

Temporal Dead Zone

The term “Temporal Dead Zone” is used for describing the state where the variables are not reachable, such as they are in scope but are not declared.

The variables which have been declared with “let” and “const”, those variables exist in the Temporal Dead Zone from the start of their enclosing scope until they are declared.

You can say that the variables which exist in the Temporal Dead Zone, from the place they get bound until it is declared. That means, when a variable gets bound to the scope it’s inside and for the variable when the name is reserved in the memory.

{

      // This is the temporal dead zone for the year variable!

   let year = 2021; // we got there! No more TDZ

   console.log(year);

}

In the above, the Temporal Dead Zone has been declared.

TDZ and Typeof

// results in a 'ReferenceError'

console.log(typeof a);

let a = 10;

If we use a typeof operator for a variable that has been declared with the “let” keyword and which is in the Temporal Dead Zone will throw a ReferenceError (when a non-existence variable is referred).

Now, this article will look at TDZ combined with lexical scoping:

function test(){

    var foo = 33;

    if(foo) {

       let foo = (foo + 55); // ReferenceError

    }

 }

 test();

The code given above will give a ReferenceError as shown above. Only because if the outer foo has a value, the if block is evaluated. However, due to lexical scoping, this value is not available inside the block. As the initialization of the foo is not completed, that is why foo+55 throws a reference error. 

function go(n) {

    // n here is defined!

    console.log(n); // Object {a: [1,2,3]}

    for (let n of n.a) { // ReferenceError

      console.log(n);

    }

  }

  go({a: [1, 2, 3]});

Now you will see a situation in the following where the phenomenon can be confusing. The instruction let n of n.a already exists inside the private scope for the for a loop.

So, to the property, a of the n, n.a is resolved, which is located in the first part of the instruction object “let n”.

In the below code as the declaration statement has not been reached and terminated, it is still in the Temporal Dead zone.

function go(n) {

    // n here is defined!

    console.log(n); // Object {a: [1,2,3]}

    for (let n of n.a) { // ReferenceError

      console.log(n);

    }

  }

  go({a: [1, 2, 3]}); 

Become a Certified UI UX Expert in Just 5 Months!

With The Best-in-class UI UX ProgramExplore Program
Become a Certified UI UX Expert in Just 5 Months!

Now you will look at the difference between let and var keywords:

In Javascript, let and var both of the keywords are used to declare the data variables, var keyword was the way of declaring the variables on earlier days, but with the evolution of Javascript ES6, let keywords were introduced for the variable declaration.

The main difference between these two keywords is, var is function scoped whereas let is block scoped.

A variable that has been declared with var, throughout the program is defined as compared to a variable that has been declared with let.

You will see the code implementation with var keyword :

//Input:

console.log(a);

var a=1;

console.log(a);

// Output:

// undefined

// 1

Now look at the code implementation of the let keyword :

// Input:

console.log(a);

let a=1;

console.log(a);

// Output:

// Error

Advance your career as a MEAN stack developer with the Full Stack Web Developer - MEAN Stack Master's Program. Enroll now!

Conclusion

As you know, these days along with data structure and algorithms, your development skill is also very important to crack the tech giants. Ultimately they are going to see how your development skill is and how’s your knowledge about this tech industry. A techie should always be closely conversant with all the technologies which are being used in this tech industry. There are some awesome full-stack development courses for you that you can check out. Surely this will really help you to enhance your skills and will brighten up your future. Enroll in Simplileran's Post Graduate Program in Full Stack Web Development to start your software devlopment career. Join Simplilearn for free courses on SkillUp to explore dozens of other courses.

Have any questions for us regarding this article? Leave them in the comments section and our experts will get back to you as soon as possible.

About the Author

SimplilearnSimplilearn

Simplilearn is one of the world’s leading providers of online training for Digital Marketing, Cloud Computing, Project Management, Data Science, IT, Software Development, and many other emerging technologies.

View More
  • Acknowledgement
  • PMP, PMI, PMBOK, CAPM, PgMP, PfMP, ACP, PBA, RMP, SP, OPM3 and the PMI ATP seal are the registered marks of the Project Management Institute, Inc.