0

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);
  • You should delete one of console.log(boxSize) – Ferhat BAŞ Oct 05 '17 at 09:42
  • It works as it should, use `let` instead of `var` when declaring `boxSize`. Check "Block Scoping Rules" here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/block – Walk Oct 05 '17 at 09:43

3 Answers3

2

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
Rohit Agrawal
  • 1,496
  • 9
  • 20
0

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);
Andrew Bone
  • 7,092
  • 2
  • 18
  • 33
0

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
vicky patel
  • 699
  • 2
  • 8
  • 14