4

I have been using python for a while now, and have just started learning javascript. In javascript you can, as I understand it, declare a variable without assigning a value to it (var cheese compared to var cheese = 4) in what situation would you want to declare a variable but not assign a value to it straight away?

vaultah
  • 44,105
  • 12
  • 114
  • 143
T0m
  • 153
  • 2
  • 12
  • Conditional values. Say you have a variable that shouldn't have any value until you hit a specific condition. If you don't declare that variable, and later on you reference it, it won't exist. – Sterling Archer Jan 14 '17 at 22:04
  • 2
    it's for **hoisting** purposes., see: http://stackoverflow.com/q/7506844/104380 – vsync Jan 14 '17 at 22:07
  • Duplicate question: http://stackoverflow.com/questions/2485423/is-using-var-to-declare-variables-optional http://stackoverflow.com/questions/581679/why-isnt-it-a-must-to-declare-a-variable-in-javascript-before-using-it http://stackoverflow.com/questions/20220862/in-javascript-can-i-use-a-variable-before-it-is-declared – artamonovdev Jan 14 '17 at 23:17
  • @artamonovdev, read question again - it does have nothing in common with questions from links... – sinisake Jan 14 '17 at 23:24
  • @sinisake, I think of these links the author can find the answer to your question. Here are good answers http://stackoverflow.com/a/20220928/5754223 and http://stackoverflow.com/a/581858/5754223 – artamonovdev Jan 14 '17 at 23:35
  • @torazaburo - you declare all variables used in a function in the beginning of that function, and later (in the code) assign values to them if one wasn't assigned when they were declared. this is best-practice to avoid hoisting and also is nicer to read. I assume you know what hoisting is since you are highly-profiled member of the community and you know its affects on code order. – vsync Jan 15 '17 at 09:32

3 Answers3

0

Consider this snippet.

if (someCondition) {
    var x = 5;
} else if (someOtherCondition) {
    var x = 4;
}

if (x) {
    doFunc();
}

Since x needs to exist for the doFunc to run, you simply add an undefined declaration above. var x; so that the if (x) doesn't return an error.

Sterling Archer
  • 22,070
  • 18
  • 81
  • 118
  • Python has the same issue, FWIW... e.g. `python3 -c 'if x: print("yes")'` will throw a `NameError` exception. The difference is there is no way to declare a variable in Python except assigning some value (even if that value is `None`). – Dan Lowe Jan 14 '17 at 22:24
  • Technically speaking, your snippet is valid javascript in non-strict mode, it's just bad practice. – Patrick Roberts Jan 14 '17 at 22:37
0

You do this when you want the value of the variable to be undefined.

var cheese;
console.log(cheese); // undefined

It's simpler than

var cheese = undefined;

The undefined value doesn't seem much useful, but this will allow to assign some other value later.

Oriol
  • 274,082
  • 63
  • 437
  • 513
  • @sinisake I was already editing to clarify; yes, usually some other value will be assigned later. But initially the value is set to undefined instead of e.g. 4 because there is no value that makes sense in there (yet). – Oriol Jan 14 '17 at 22:32
  • To rephrase my self: is this 'good practice', do we actually gain something by doing this? :) e.g can we easily declare var later in script and give it meaningful value? – sinisake Jan 14 '17 at 22:33
  • 1
    @sinisake This just declares a variable, and assigns the undefined value as a side-effect. If there is some other value that makes sense, then using the other value is better practice. If at that moment there is no known such value, then I would use this. Declaring later may be a possibility, but it may have readability costs or behave differently. – Oriol Jan 14 '17 at 22:36
  • undefined is not a reserved word and could be replaced by an arbitrary value, such as a number or string. – artamonovdev Jan 15 '17 at 08:34
  • @artamonovdev That's why I said "is simpler than" instead of "is equivalent to", because `undefined` can be shadowed (not replaced) with some other value. – Oriol Jan 15 '17 at 14:50
-1

var cheese; can be perfectly useful (even if you never assign anything to it). Of course it's a shorter way to type var cheese = undefined;, but that's not the only reason…

Using var declares a local variable, and this has a nice property: it hides variables from parent scopes.

There's another part to your question:

If we're going to assign a value to var cheese anyway: why not assign immediately?.

Answer: it may be fine for your algorithm to return cheese without ever assigning anything to it — i.e. "undefined is valid".

Here's an example which illustrates how var hides variables from parent scopes:

var a = 3;
console.log(a); // prints 3; "a" is defined in this scope

function findEvenNumber(numbers) {
    var a; // we declare this local variable, to ensure that we do _not_ refer to the variable that exists in the parent scope
    numbers.forEach(function(number) {
        if (number % 2 === 0) {
            a = number;
        }
    });
    return a; // if no even number was found, it returns undefined (because we never assigned anything to a)
}
findEvenNumber([1, 2]); // returns 2;

console.log(a); // prints 3; the "a" in this scope did not get overwritten by the function

Speculation: maybe the var cheese; syntax exists in ECMA to enable programmers to declare all variables at the beginning of their function. Such a convention was enforced by the C89 compiler, and some people grew fond of it.

Community
  • 1
  • 1
Birchlabs
  • 7,437
  • 5
  • 35
  • 54