The difference between let and var in js

javascript strict mode

The first time you contact let keyword, there is a very important concept to pay attention to: "javascript strict mode". For example, the following code will report an error when running:

let hello = 'hello world.';
console.log(hello);
  • 1
  • 2

The error message is as follows:

let hello = 'hello world.';
^^^

SyntaxError: Block-scoped declarations (let, const, function, class) not yet supported outside strict mode
    ...
  • 1
  • 2
  • 3
  • 4
  • 5

The solution is to add the declaration of "javascript strict mode" in the file header:

'use strict';

let hello = 'hello world.';
console.log(hello);
  • 1
  • 2
  • 3
  • 4

For more details on "javascript strict mode", please refer to Ruan Yifeng's blog
Detailed explanation of Javascript strict mode

Similarities and differences between let and var keywords

No assignment after declaration, same performance

'use strict';

(function() {
  var varTest;
  let letTest;
  console.log(varTest); //Output undefined
  console.log(letTest); //Output undefined
}());
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

Use undeclared variables, which behave differently:

(function() {
  console.log(varTest); //Output undefined (note to comment out the following line to run)
  console.log(letTest); //Direct error: ReferenceError: letTest is not defined

  var varTest = 'test var OK.';
  let letTest = 'test let OK.';
}());
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

When the same variable is declared repeatedly, it behaves differently:

'use strict';

(function() {
  var varTest = 'test var OK.';
  let letTest = 'test let OK.';

  var varTest = 'varTest changed.';
  let letTest = 'letTest changed.'; //Direct error: syntax error: identifier 'lettest' has already been declared

  console.log(varTest); //Output varTest changed
  console.log(letTest);
}());
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

Variable action range, different performance

'use strict';

(function() {
  var varTest = 'test var OK.';
  let letTest = 'test let OK.';

  {
    var varTest = 'varTest changed.';
    let letTest = 'letTest changed.';
  }

  console.log(varTest); //Output "varTest changed.", varTest variable declared in internal "{}" overrides external letTest declaration
  console.log(letTest); //Output "test let OK.", the letTest declared in the internal "{}" and the external letTest are not the same variable
}());

Tags: Javascript

Posted on Tue, 05 May 2020 20:18:06 -0400 by lucerias