In this tutorial I am going to write about variable declaration in JavaScript.So lets start with some basic difference between var, let and const.
var
- var is scoped to the nearest function block.
- You can declare the same variable multiple times using var.
- You can use variable before even initialize.
- Global variables defined with var will be added as properties on the global window object.
//Example
function test(){
for( var i = 0; i < 5; i++ ) {
//i is visible here
}
//i is visible here
}
//i is not visible here
// You can declare the same variable multiple times using var.
'use strict';
var a;
var a;
//You can use variable before even initialize.
function fun () {
typeof a;
var a = 'big';
}
fun();
/*Global variables defined with var will be added as properties
on the global window object*/
var a = 'go'; // globally scoped
console.log(window.a); // 'go'
let
- let is scoped to the nearest enclosing block (both are global if outside any block), which can be smaller than a function block.
- let says variable will be used only in the block it’s defined in.
- The use case for `let` tends to be for loops or mathematical algorithms.
- Use let where you need to reassign a variable like in loops.
- Assuming strict mode,you can't declare the same variable multiple times using let.
- Always initialize your identifiers before you try to use them.
- Global variables defined with let will not be added as properties on the global window object
for( let i = 0; i < 5; i++ ) {
//i is only visible in here
//and there is a separate i variable for each iteration of the loop
}
//i is not visible here
// You can't declare the same variable multiple times using let.
'use strict';
let a;
let a; // SyntaxError: Identifier 'b' has already been declared
//always initialize your identifiers before you try to use them
function fun () {
typeof a;
let a = 'big';
}
fun(); // Uncaught ReferenceError: bar is not defined
/*Global variables defined with let will not be added as properties
on the global window object*/
let a = 'go'; // globally scoped
console.log(window.a); // undefined
const
- Constants are block-scoped
- The value of a constant cannot change through re-assignment, and it can't be redeclared.
- const says the identifier won’t be reassigned.
- Naming convention for const variable is to use all-uppercase letters.
//Example
// define MY_NUM as a constant and give it the value 17
const MY_NUM = 17;
// this will throw an error
MY_NUM = 20;
// will print 17
console.log('my number is: ' + MY_NUM);
// trying to redeclare a constant throws an error
const MY_NUM = 20;
// the name MY_NUM is reserved for constant above, so this will also fail
var MY_NUM = 20;
// this throws an error also
let MY_NUM = 20;
I feel you found this article useful and now you got a clear picture about where and how to use var, let and const more effectively.
Happy Learning :-)
0 on: "JavaScript ES6 : Difference between var, let and const"