Console log two times but it needs to show only the first console.log(boxSize)
var size = 100;
if (size > 50) {
var boxSize = size * 5;
console.log(boxSize);
}
console.log(boxSize);
Console log two times but it needs to show only the first console.log(boxSize)
var size = 100;
if (size > 50) {
var boxSize = size * 5;
console.log(boxSize);
}
console.log(boxSize);
This is a behaviour called hoisting in Javascript.
Hoisting is a JavaScript mechanism where variables and function declarations are moved to the top of their scope before code execution.
var
in javascript are not block scoped.
You can use the keywords let
or const
in ES6 which declare variables which are only available to the block where it s declared.
var size = 100;
if (size > 50) {
let boxSize = size * 5;
console.log(boxSize);
}
console.log(boxSize);// Uncaught ReferenceError: boxSize is not defined
I would suggest using let over var for this
The difference is scoping. var is scoped to the nearest function block and let is scoped to the nearest enclosing block, which can be smaller than a function block. Both are global if outside any block.
src: https://stackoverflow.com/a/11444416/4891666
Example:
var size = 100;
/* Using Var */
if (size > 50) {
var varExample = size * 5;
console.log("With var inner: " + varExample);
}
console.log("With var outer: " + varExample);
/* Using Let */
if (size > 50) {
let letExample = size * 5;
console.log("With let inner: " + letExample);
}
console.log("With let outer: " + letExample);
let size = 100;
if (size > 50) {
let boxSize = size * 5;
console.log(boxSize);
}
console.log(boxSize);
/* Es6 let declers a block scope
local variable(not function level scope like var)
*/
//trying to access the variable in the block before the variable declaration resulsts in a ReferenceError