Why there is no Syntax error in the following code?
var num = 8;
var num = 10;
console.log(num) // 10
whereas
var num = 8;
let num = 10;
console.log(num) // already decleared error
Why there is no Syntax error in the following code?
var num = 8;
var num = 10;
console.log(num) // 10
whereas
var num = 8;
let num = 10;
console.log(num) // already decleared error
The first case will be rendered as:
var num;
num = 8;
num = 10;
console.log(num); // output : 10
The second case will be rendered as:
var num;
num = 8;
let num; // throws Uncaught SyntaxError: Identifier 'num' has already been declared
num = 10
console.log(num);
Because unlike var, variables cannot be re-declared using let, trying to do that will throw a Syntax error: Identifier has already been declared. What is important if you will avoid anti-patterns like global variables, if you will keep your vars in the scope and make the methods small, you will avoid redeclaration of the vars bugs.. probably. What is important number two: var declaration works faster then const and let, so in loops, if you HAVE TO OPTIMIZE the method you can use var instead of let/const.