Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.. ?

like image 435
lukas.pukenis Avatar asked Jul 15 '13 11:07

lukas.pukenis


1 Answers

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.

like image 140
Karoly Horvath Avatar answered Sep 29 '22 20:09

Karoly Horvath