Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declare var before assigning multiple values in Javascript?

Tags:

javascript

In Javascript, which format of var declarations is better:

function test1() {
  switch(type) {
    case 1:
        var test = "Hello One"
      break;
    case 2:
        var test = "Hello Two"
      break;
  }
}

Or:

function test2() {
  var test;

  switch(type) {
    case 1:
        test = "Hello One"
      break;
    case 2:
        test = "Hello Two"
      break;
  }
}

In test2(), there is 1 extra line of code to declare test as a var before assigning a value, but this saves having to declare var test twice. Is either way better than the other?

like image 411
projeqht Avatar asked Dec 12 '22 12:12

projeqht


1 Answers

javascript does not have block scope, so declaring variables in a switch block does not work like you would expect.

furthermore, due to variable hoisting, all variable declarations in a function block are hoisted to the top by the interpreter and your code would look like this:

function test1() {
  var test;
  var test;

  switch(type) {
    case 1:
        test = "Hello One"
      break;
    case 2:
        test = "Hello Two"
      break;
  }
}

After performing the hoist, it is easy to see why the first block is incorrect.

like image 76
jbabey Avatar answered Jan 05 '23 01:01

jbabey