7

Say I have a piece of code like this:

const number = 3;

function fooFunction() {
  let numberTwo = 5;
  var answer = number + numberTwo;
  return answer;
}

finalAnswer = fooFunction();

console.log(finalAnswer);

Assuming an ES2015 compatible browser, what would be the advantages/disadvantages of using the above code, over:

const number = 3;

function fooFunction() {
  var numberTwo = 5;
  var answer = number + numberTwo;
  return answer;
}

finalAnswer = fooFunction();

console.log(finalAnswer);

Are there any advantages or disadvantages, given they both return the same number?

12
  • As per this answer they are identical within a function like yours Commented May 20, 2016 at 17:47
  • What about from a security and performance point of view? Commented May 20, 2016 at 17:47
  • Per your usage above, there is no difference. Commented May 20, 2016 at 17:48
  • If there were a difference in security or performance they would not be identical Commented May 20, 2016 at 17:49
  • 1
    no, var is hoisted to the top of the function, not outside the function :) Commented May 20, 2016 at 17:53

2 Answers 2

5

As others have mentioned, in your example you can use let and var interchangeably. The difference is that let is block-scoped and var is not.

For example with var you can do this (prints 'foo'):

function printFoo(param) {
  if (param) {
    var x = "foo";
  }

  console.log(x);
}

printFoo("hello");

You cannot do this with let because let x is scoped to the if block and therefore is not defined.

Sign up to request clarification or add additional context in comments.

Comments

1

Within the code sample you've provided, the two are interchangeable. Where let comes in handy is in limiting the scope to block-level as opposed to function-level. Using let inside of a for loop, for example.

It's worth noting that variables created with the var keyword are hoisted, whereas variables created with the let keyword are not.

There is an excellent breakdown of this topic by Kyle Simpson on David Walsh's blog: https://davidwalsh.name/for-and-against-let#implicit-hazards

2 Comments

technically, let variables are hoisted, but not referenceable. see temporal dead zone. In ECMAScript 2015, let will hoist the variable to the top of the block. However, referencing the variable in the block before the variable declaration results in a ReferenceError. The variable is in a "temporal dead zone" from the start of the block until the declaration is processed.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.