Javascript is initialized to undefined or null or ""

Java script has a lot of fake values ​​when I started to learn. I have a program that gets values ​​from a service and loads into an array like this:

function loadNames() {
    Global.names = // what should I use here? undefined, null, "", 0, {} or anything else
    var lnames = getLNames(); // this is doing some magic
        if ( lnames.length !== 0 ) {
            Global.names = new Array();
            for ( var i = 0; i < lnames.length; ++i)
                Global.names[i] = lnames[i];
    }
}

I want to know the correct way to reset Global.names. What is most appropriate here? In the code, I only want to check howif ( Global.names )

PS: I can’t just return the return value to Global.names, since the return object will be destroyed later. Therefore, I need to make a deep copy

thank

+5
source share
5 answers

Adapted from JavaScript: the good parts are:

" if . , . :

  • undefined

  • ''

  • 0

  • NaN "

, , var , if (var) {...}

+11

, GLobal.names = []; , Global.names.length != 0. reset, .

+5

,

if ( Global.names.length )

, ,

function loadNames() {
  Global.names = getLNames().concat();
}
+3

. :

if (!Global.names) Global.names = [];
// add members to Global.names

:

Global.names = Global.names : [];

reset , :

Global.names = [];

delete Global.names;
+1
source

Setting it up nullis good, because you know that a variable exists, but it has no value. Thus, you can easily see the state - if it is undefined, then you forgot to declare it, if it nullwas declared, but never assigned a value, and if it is Array, you can check the length from there.

0
source

All Articles