What will get printed in console.log()
?
Q1:
1
2
3
4
| "use strict"
let x = 1;
let x = 2;
console.log(x); // ?
|
Solution:
1
2
3
4
| "use strict"
let x = 1;
let x = 2;
console.log(x); // Uncaught SyntaxError: Identifier 'x' has already been declared
|
let
and const
were introduced in ES6(2015) version. They are used to declare a block-scoped
variables and redeclaring a block-scoped variable in the same scope is not allowed in ES6
Q2:
1
2
3
4
| "use strict"
var x = 1;
var x = 2;
console.log(x); // ?
|
Solution:
1
2
3
4
| "use strict"
var x = 1;
var x = 2;
console.log(x); // 2
|
Variables declared using var
keyword can be redeclared using var
keyword only.
Q3:
1
2
3
| var x = 1;
var x = 2;
console.log(x); // ?
|
Solution:
1
2
3
| var x = 1;
var x = 2;
console.log(x); // 2
|
Variables declared using var
keyword can be redeclared using var
keyword only. It doesn’t matter if we are using strict mode
or not.