Javascript let or variable

Differences Between var and let

Summary: in this tutorial, you will learn about the differences between the var and let keywords.

#1: Variable scopes

The var variables belong to the global scope when you define them outside a function. For example:

var counter;Code language: JavaScript (javascript)

In this example, the counter is a global variable. It means that the counter variable is accessible by any functions.

When you declare a variable inside a function using the var keyword, the scope of the variable is local. For example:

function increase( ) < var counter = 10; > // cannot access the counter variable hereCode language: JavaScript (javascript)

In this example, the counter variable is local to the increase() function. It cannot be accessible outside of the function.

The following example displays four numbers from 0 to 4 inside the loop and the number 5 outside the loop.

for (var i = 0; i < 5; i++) < console.log("Inside the loop:", i); > console.log("Outside the loop:", i);Code language: JavaScript (javascript)
Inside the loop: 0 Inside the loop: 1 Inside the loop: 2 Inside the loop: 3 Inside the loop: 4 Outside the loop: 5Code language: Shell Session (shell)

In this example, the i variable is a global variable. Therefore, it can be accessed from both inside and after the for loop.

Читайте также:  Изменить значение строки python

The following example uses the let keyword instead of the var keyword:

for (let i = 0; i < 5; i++) < console.log("Inside the loop:", i); > console.log("Outside the loop:", i);Code language: JavaScript (javascript)

In this case, the code shows four numbers from 0 to 4 inside a loop and a reference error:

Inside the loop: 0 Inside the loop: 1 Inside the loop: 2 Inside the loop: 3 Inside the loop: 4
Uncaught ReferenceError: i is not definedCode language: JavaScript (javascript)

Since this example uses the let keyword, the variable i is blocked scope. It means that the variable i only exists and can be accessible inside the for loop block.

In JavaScript, a block is delimited by a pair of curly braces <> like in the if. else and for statements:

if(condition) < // inside a block > for(. ) < // inside a block >Code language: JavaScript (javascript)

#2: Creating global properties

The global var variables are added to the global object as properties. The global object is window on the web browser and global on Node.js:

var counter = 0; console.log(window.counter); // 0Code language: JavaScript (javascript)

However, the let variables are not added to the global object:

let counter = 0; console.log(window.counter); // undefinedCode language: JavaScript (javascript)

#3: Redeclaration

The var keyword allows you to redeclare a variable without any issue:

var counter = 10; var counter; console.log(counter); // 10Code language: JavaScript (javascript)

However, if you redeclare a variable with the let keyword, you will get an error:

let counter = 10; let counter; // errorCode language: JavaScript (javascript)

#4: The Temporal dead zone

The let variables have temporal dead zones while the var variables don’t. To understand the temporal dead zone, let’s examine the life cycles of both var and let variables, which have two steps: creation and execution.

The var variables

  • In the creation phase, the JavaScript engine assigns storage spaces to var variables and immediately initializes them to undefined .
  • In the execution phase, the JavaScript engine assigns the var variables the values specified by the assignments if there are ones. Otherwise, the var variables remain undefined.

See the execution context for more information.

The let variables

  • In the creation phase, the JavaScript engine assigns storage spaces to the let variables but does not initialize the variables. Referencing uninitialized variables will cause a ReferenceError .
  • The let variables have the same execution phase as the var variables.

The temporal dead zone starts from the block until the let variable declaration is processed. In other words, it is the location where you cannot access the let variables before they are defined.

In this tutorial, you have learned about the differences between var and let keywords.

Источник

Variable Declaration in JavaScript: var, let or const?

Visit my Blog for the original post: Variable Declaration in JavaScript: var, let or const? There are 4 ways of variable declaration in JavaScript. Beginner web developers are usuallly confused about the effects of different ways. Hence, this article is for beginners to understand the differences among the 4 ways of declaring variables in JavaScript and when to use them.

Let’s go through them

1. «Freestyle» Way (Yes, it works, but is strongly NOT recommanded!)

myVariable = ‘abc’; It’s possible that you declare a variable in JavaScript without using any keyword var , let , const . It simply means that you have created a global variable. In node environment, let’s run the following code snippet

a = "test"; console.log(a); // output: test 

The result shows test , which means it works! However, if we add ‘use strict’ to enter strict mode, such declaration method is prohibited

"use strict"; a = "test"; console.log(a); // ReferenceError: a is not defined 

An error is thrown. ReferenceError: a is not defined This method is highly NOT recommanded because it is prohibited under strict mode and it will pollute your global environment. If your global environment contains too many useless temporary variables, your program will likely go into unpredicted errors and it will be a horrible experience to debug on such problem. So, DO NOT use this way at all.

2. var

var is the most common way of declaring a variable in JavaScript. Before ES6 was released, you should always use var to declare your variables. However, var also has its limitations because the variables declared with var is at function level. What does it mean? See the following example.

"use strict"; function test()  for (var i = 0; i  10; i++)  var count = i; > console.log(count); > test(); // Output: 9 

Before running this piece of code, what do you expect the output of the function to be? Throwing an error? You might probably think that count is declared within the for loop, it should not be accessible outside of the loop. But sorry, if you use var to declare a variable, the variable belongs to the function scope, which means that even though count is declared within the for loop, count still belongs to test() function. Hence, as long as it’s within test() function, count is accessbile! Another evidence is that, no error is thrown at all even if you console.log(count) before declaring it within a function! Since no error is thrown, it would be hard to trace when unexpected bug occurs.

"use strict"; function test()  console.log(count); // runs before declaration for (var i = 0; i  10; i++)  var count = i; > > test(); // Output: undefined 

The output shows undefined instead of throwing errors! Instead, errors will be thrown if the count is not declared at all!

"use strict"; function test()  console.log(count); // error is thrown > test(); 

3. let

let is introduced in ES6. It is scoped at block level, which resolves the difficulty you might encounter when using var . By using let , the following code snippet correctly throws errors ReferenceError: count is not defined

"use strict"; function test()  for (let i = 0; i  10; i++)  let count = i; > console.log(count); // ReferenceError: count is not defined > test(); 

That is because let makes count variable become block-scoped. count only exists in this for loop. It is a better way to use when declaring variables. However, it also has its disadvantage. let is not compatible with old browsers such as IE 11. If you are writing JavaScript codes directly for browser display (not compiled by Babel) and need to take care of users with old browsers, you should consider to use var because incompatible let will likely cause problems in old browsers and stop webpage rendering once error occurs.

4. const

const is also introduced in ES6. Same as let , it is also scoped at block level. The only difference is that const variable is a constant, whose values cannot be changed.

"use strict"; const a = 1; a = 2; 

The above code snippet will throw error TypeError: Assignment to constant variable. In addition, if you are working with arrays or objects, it’s totally fine with constant declarations but modify it’s attributes or members later. Consider the following code snippet:

"use strict"; const a = []; const b = <>; a.push(1); b.key = 2; console.log("a", a); console.log("b", b); // output: // a [ 1 ] // b 

No error is occured. That is because the constant values of a and b are their addresses in the memory, instead of their members or attributes. If we assign the address of a to b as below, errors will then take place.

"use strict"; const a = []; const b = <>; a = b; // TypeError: Assignment to constant variable. 

Therefore, as long as you do not point a or b to another locations, no error would occur. It is recommanded to do so to ensure that you are operating on the correct instance of object / array.

A little summary

You should never ever declare a variable without var , let or const ! Also, var should be avoided too unless you really have to consider browser compatibility issues. The good practice is that you should always consider declaring a variable using const .
Using const by default helps you avoid unnecessary mistakes such as carelessly re-assign values to an important variable. unless you are sure that you would change its values later. Then the second option should always be let .

Источник

Оцените статью