Pagepro Blog

JavaScript

Let and var – differences

Posted on .

Let and var – differences

Introduction

Introduction

With the introduction of a new standard of JavaScript code writing – ECMAScript 6 (ES6) – new structures responsible for variable declaration appeared. I am talking about the let and const instructions. Even before the introduction of ES6, we had to choose only the var instruction. Beginners often find it difficult to understand the difference between var and let. It is often heard that let it be a new var. There is some truth in it, but not quite. Scoping makes a difference

  • var’s scope is a function
  • let’s scope is enclosing block – `if () {}, for () {}, function () {}`

Declared outside any block – both are global.

About var

The introduction of the LET variable greatly simplifies the work of developers, because the VAR operation through the function scope sometimes caused problems. Below two examples.
I will use Visual Studio Code and dev tools in the chrome browser.

1. First example

Code:


// 1. var example

if (true) {
  var a = 1
}
  
console.log(a)

Now let’s check console:

var 1 example console log

The console will display the number 1 to us, even though the variable has been declared in the block.

2. Second example

Code:


// 2. var example

for (var i = 0; i < 5; i++) {
  console.log(`Inside for loop - ${i}`)
}

console.log(`Outside loop - ${i}`)

And console log:

var 2 example console log

The first console log will write to us number s 0 1 2 3 4. The second one outside the block will write to us the number 5. As in the first case it is an unwanted event

About let

Now let's look what happens when we use the let variable with the same examples …

1. First example

Code:


// 1. let example

if (true) {
  let a = 1
}
  
console.log(a)

Console log:

let example 1 console log

As you can see. Variable was declared in a block and we can not refer to it outside the loop.

2. Second example

Code:


// 2. let example

for (let i = 0; i < 5; i++) {
  console.log(`Inside for loop - ${i}`)
}

console.log(`Outside loop - ${i}`)

Console log:

let example 2 console log

As you can see, assigning a value to let variable within a block caused that it loses its scope outside the block.

Summation

So you see that the variable let is much more convenient, more practical and in addition can make us avoid unpleasant surprises in the future, related to the unwanted action of variable var. I would suggest an almost complete departure from the application of VAR to LET and CONST about which it will be in the next post.

Michał Moroz

Michał Moroz

There are no comments.

View Comments (0) ...
Navigation