Question about JavaScript variables
August 2, 2012 10:17 AM   Subscribe

In JavaScript, if I define a variable within in a conditional block, is the variable defined through a type of hoisting even if the condition isn't met?

Example: Is the following code correct?
if (qtyOrdered>143)
{
   var discount=.1;
}
else if (customerRank<100)
{
  discount=.05;
}
posted by markcmyers to Technology (5 answers total) 1 user marked this as a favorite
 
Response by poster: Sorry, I mean "declared," not "defined."
posted by markcmyers at 10:18 AM on August 2, 2012


Yes, that'll work fine. The var declaration will be hoisted to the top of the function.

To people not familiar with Javascript, this looks like an error, but it's not. This is why some people suggest that all var statements should be placed on the top of functions to make things more obvious to anyone reading the code.
posted by zsazsa at 10:27 AM on August 2, 2012


Scoping in JS is weird. If qtyOrdered is greater than 143, your variable will be declared but for this block only (using var). If qtyOrdered is less than 143, and customerRank is less than 100, the variable will be global (by not using var).

I think the following is better:
var discount;
if (qtyOrdered > 143){
    discount = .1;
}
if (customerRank < 100){
    discount = .05;
}

posted by monospace at 10:27 AM on August 2, 2012


Hoisting will happen, and discount will be local no matter what set of conditionals are met. The fact that discount is declared in a conditional block isn't relevant, because JavaScript doesn't have block scope.

That said, I wouldn't call it "correct." It's a needlessly confusing way of writing the code. I can't think of a good reason to ever do it that way.
posted by zjacreman at 10:32 AM on August 2, 2012


monospace: While your example is more readable (and what I'd write, personally), hoisting actually transforms the code in the asker's code to be functionally equivalent. Discount will not be made a global. This is a good overview of hoisting.
posted by zsazsa at 10:34 AM on August 2, 2012 [2 favorites]


« Older Los Angeles birthday exchange   |   Be polite, HELO or EHLO first Newer »
This thread is closed to new comments.