lukas.pukenis
lukas.pukenis

Reputation: 13597

What's the best way to initialize empty variables in JS?

If I know the variable will be object later, I use:

var obj;

but it doesn't really matter if I initialize it as null or undefined:

var obj = null;

or

var obj = undefined;

For strings I personally use:

var str = '';

as later on I can do

str += 'some text';

and if I use null for example I get "nullsome text".

null, undefined, empty string or 0 are all falsy values so to check if they are defined. which is the correct way to initialize variables if my variable will be used as object, dom node, etc.. ?

Upvotes: 17

Views: 54787

Answers (2)

Elias Van Ootegem
Elias Van Ootegem

Reputation: 76413

In an ideal scenario, you'd just declare your variables at the top of the scope like so:

var foo, bar, obj, domNode;

All of these variables will be undefined, as in their value is undefined. If you know for a fact one of these variables will be used as a string in a loop, for example, rather thant writing foo = (foo === undefined ? '' : foo) + 'add this';, just write:

var foo = '', bar, obj, domNode;

If you're going to use the obj var as an object literal, just assign it {my: 'objec', vals: 'here'} when the time comes, or initialize it to {}, and add properties obj.as = 'you'; obj[foo] = 'go';. If you're going to assign a reference to a DOM element, keep it undefined, as any assignment will just generate pointless overhead.
Same goes for any type of reference (function objects, arrays, objects...). Just postpone the assignment, because it'll just overwrite any previous assignment.

As for numbers, undefined + 123 will get evaluate to NaN, so in that case, initializing to 0 makes sense. However, in case of loop counters:

var foo, i, obj, arr = [1,2,3];
for (i=0;i<arr.length;i++)
{
    console.log(arr[i]);
}

is equivalent to:

var foo, i= 0, arr = [1,2,3];
for (;i<arr.length;i++)
{
    console.log(arr[i]);
}

Only the latter almost looks wantonly complicated. Just use your common sense and you'll be all right.

Just know that variable declarations are hoisted to the top of the scope, but assignments aren't:

console.log(foo);//undefined
var foo = 123;
console.log(foo);//123

because it's translated into:

var foo;
console.log(foo);
foo = 123;
console.log(foo);

So why not write your code as it'll be interpreted by the engine?

Upvotes: 6

Karoly Horvath
Karoly Horvath

Reputation: 96266

It's initialized to undefined by default, just use that, you don't have to write it out:

var obj;

If it you want to concatenate to a string, use '', for counters use 0... Just use common sense.

Upvotes: 15

Related Questions