Esc6 variable and string part 1

JavaScript Tutorial
ECMAScript 6
ES6 Variables and Strings
10
1/3
               

var & let



In ES6 we have three ways of declaring variables:var a = 10;
const b = 'hello';
let c = true;

The type of declaration used depends on the necessary scopeScope is the fundamental concept in all programming languages that defines the visibility of a variable.

var & let
Unlike the var keyword, which defines a variable globally, or locally to an entire function regardless of block scope, let allows you to declare variables that are limited in scope to the block, statement, or expression in which they are used. 
For example:
if (true) {
let name = 'Jack';
}
alert(name); //generates an error
Try It Yourself

In this case, the name variable is accessible only in the scope of the if statement because it was declared as let.

To demonstrate the difference in scope between var and let, consider this example:
function varTest() {
var x = 1;
if (true) {
var x = 2; // same variable
console.log(x); // 2
}
console.log(x); // 2
}

function letTest() {
let x = 1;
if (true) {
let x = 2; // different variable
console.log(x); // 2
}
console.log(x); // 1
}
Try It Yourself

One of the best uses for let is in loops:
for (let i = 0; i < 3; i++) {
document.write(i);
}
Try It Yourself

Here, the i variable is accessible only within the scope of the for loop, where it is needed. 
let is not subject to Variable Hoisting, which means that let declarations do not move to the top of the current execution context.

Comments