What's the difference between using "let" and "var"?

Asked
Active3 hr before
Viewed126 times

9 Answers

differenceusing
90%

var and let are both used for variable declaration in javascript but the difference between them is that var is function scoped and let is block scoped.It can be said that a variable declared with var is defined throughout the program as compared to let.An example will clarify the difference even betterExample of var:,Code #2:In the following code, clicking start will call a function that changes the color of the two headings every 0.5sec. The color of first heading is stored in a var and the second one is declared by using let.Both of them are then accessed outside the function block. Var will work but the variable declared using let will show an error because let is block scoped.,Difference between var and let in JavaScript,JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples.

var and let are both used for variable declaration in javascript but the difference between them is that var is function scoped and let is block scoped.
It can be said that a variable declared with var is defined throughout the program as compared to let.
An example will clarify the difference even better
Example of var:

Input:
   console.log(x);
var x = 5;
console.log(x);
Output:
   undefined
5


Example of let:

Input:
   console.log(x);
let x = 5;
console.log(x);
Output:
   Error
load more v
88%

The main difference is scoping rules. Variables declared by var keyword are scoped to the immediate function body (hence the function scope) while let variables are scoped to the immediate enclosing block denoted by { } (hence the block scope).,The main difference between var and let is that variables declared with var are function scoped. Whereas functions declared with let are block scoped. For example:,When used inside a block, let limits the variable's scope to that block. Note the difference between var whose scope is inside the function where it is declared.,When the first function testVar gets called the variable foo, declared with var, is still accessible outside the if statement. This variable foo would be available everywhere within the scope of the testVar function.

function run() {
   var foo = "Foo";
   let bar = "Bar";

   console.log(foo, bar); // Foo Bar

   {
      var moo = "Mooo"
      let baz = "Bazz";
      console.log(moo, baz); // Mooo Bazz
   }

   console.log(moo); // Mooo
   console.log(baz); // ReferenceError
}

run();
load more v
72%

The let variables have the same execution phase as the var variables.,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 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.,The var variables belong to the global scope when you define them outside a function. For example:

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

.wp - block - code {
      border: 0;
      padding: 0;
   }

   .wp - block - code > div {
      overflow: auto;
   }

   .shcb - language {
      border: 0;
      clip: rect(1 px, 1 px, 1 px, 1 px); -
      webkit - clip - path: inset(50 % );
      clip - path: inset(50 % );
      height: 1 px;
      margin: -1 px;
      overflow: hidden;
      padding: 0;
      position: absolute;
      width: 1 px;
      word - wrap: normal;
      word - break: normal;
   }

   .hljs {
      box - sizing: border - box;
   }

   .hljs.shcb - code - table {
      display: table;
      width: 100 % ;
   }

   .hljs.shcb - code - table > .shcb - loc {
      color: inherit;
      display: table - row;
      width: 100 % ;
   }

   .hljs.shcb - code - table.shcb - loc > span {
      display: table - cell;
   }

   .wp - block - code code.hljs: not(.shcb - wrap - lines) {
      white - space: pre;
   }

   .wp - block - code code.hljs.shcb - wrap - lines {
      white - space: pre - wrap;
   }

   .hljs.shcb - line - numbers {
      border - spacing: 0;
      counter - reset: line;
   }

   .hljs.shcb - line - numbers > .shcb - loc {
      counter - increment: line;
   }

   .hljs.shcb - line - numbers.shcb - loc > span {
      padding - left: 0.75 em;
   }

   .hljs.shcb - line - numbers.shcb - loc::before {
      border - right: 1 px solid #ddd;
      content: counter(line);
      display: table - cell;
      padding: 0 0.75 em;
      text - align: right; -
      webkit - user - select: none; -
      moz - user - select: none; -
      ms - user - select: none;
      user - select: none;
      white - space: nowrap;
      width: 1 % ;
   }
var counter;
Code language: JavaScript(javascript)
load more v
65%

The main difference between let and var is that scope of a variable defined with let is limited to the block in which it is declared while variable declared with var has the global scope. So we can say that var is rather a keyword which defines a variable globally regardless of block scope.,Also, one difference between var and let is variable with var can be redeclared to some other value while variable could not be redeclared if it is defined with let.,The scope of let not only limited to the block in which it is defined but variable with let also do not get added with global window object even if it get declared outside of any block. But we can access variable with var from window object if it is defined globally.,As we know in order to declare a variable in javascript we have two options either declare with var or declare with let. Now the question is when to use var and when to use let i.e what are the major difference between both.

Example representing difference between var and let

let a = 'hello'; // globally scoped
var b = 'world'; // globally scoped
console.log(window.a); // undefined
console.log(window.b); // 'world'
var a = 'hello';
var a = 'world'; // No problem, 'hello' is replaced.
let b = 'hello';
let b = 'world'; // SyntaxError: Identifier 'b' has already been declared
75%

var variables can be updated and re-declared within its scope; let variables can be updated but not re-declared; const variables can neither be updated nor re-declared.,Just like var,  a variable declared with let can be updated within its scope. Unlike var, a let variable cannot be re-declared within its scope. So while this will work:,This means that the value of a variable declared with const remains the same within its scope. It cannot be updated or re-declared. So if we declare a variable with const, we can neither do this:,They are all hoisted to the top of their scope. But while var variables are initialized with undefined, let and const variables are not initialized.

To understand further, look at the example below.

    var greeter = "hey hi";

    function newFunction() {
       var hello = "hello";
    }
load more v
40%

The var statement is used to declare a variable in JavaScript. A variable declared with the var keyword is defined throughout the program.,The let statement is used to declare a local variable in TypeScript. It is similar to the var keyword, but it has some restriction in scoping in comparison of the var keyword. The let keyword can enhance our code readability and decreases the chance of programming error. A variable declared with the let keyword is limited to the block-scoped only.,The above code snippet throws an error because the variable "hello" is not defined globally.,JavaTpoint offers too many high quality services. Mail us on [email protected], to get more information about given services.

Example:
function varGreeter() {
   var a = 10;
   var a = 20; //a is replaced
   console.log(a);
}
varGreeter();
load more v
22%

Generally, if you need to create a variable, use const. However, if you know or think that you’ll need to reassign it (for-loops, switch statements, algorithm swapping) use let.,The keyword const is an abbreviation for constant. Similar to let, it’s block-scoped, however, you can’t reassigned it.,Using var you can reassign it with a new value.,Before we can understand how var and let/const differ we need to understand a computer science-y concept called scope.

function myFn() {
   var foo = 'peekaboo!';

   console.log(foo); // 'peekaboo!'
}

console.log(foo); // ReferenceError: foo is not defined
load more v
60%

let allows you to declare variables that are limited to the scope of a block statement, or expression on which it is used, unlike the var keyword, which declares a variable globally, or locally to an entire function regardless of block scope. The other difference between var and let is that the latter is initialized to a value only when a parser evaluates it (see below). , However, it's important to point out that a block nested inside a case clause will create a new block scoped lexical environment, which will not produce the redeclaration errors shown above. , When used inside a block, let limits the variable's scope to that block. Note the difference between var, whose scope is inside the function where it is declared. , The let statement declares a block-scoped local variable, optionally initializing it to a value.

let name1[ = value1][, name2[ = value2]][, ..., nameN[ = valueN];
load more v
48%

This has practical implications. For example, a variable is declared inside an if or used as the for loop iterator. Using let makes it local to those 2 blocks. Using var, however, allows the variable to be available outside of that block, which might lead to bugs.,But when I do need to redeclare a variable later on, I always use let.,var instead is a bit more weird, as it has function scoping, which means that variables declared using var are scoped to the nearest function.,var variables instead are hoisted to the top of the function, and as such they are available even in the lines before their declaration. Weird, right?

load more v

Other "difference-using" queries related to "What's the difference between using "let" and "var"?"