Wednesday, June 5, 2024
 Popular · Latest · Hot · Upcoming
47
rated 0 times [  51] [ 4]  / answers: 1 / hits: 16980  / 13 Years ago, fri, may 20, 2011, 12:00:00

Java script has many falsy values as I started learning. 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 right way of resetting Global.names. What is most appropriate here? In code I only want to check like if ( Global.names )



PS: I can't just take the return value into Global.names as the returned object is destroyed later. Hence, I need to do a deep copy



Thanks


More From » undefined

 Answers
181

Taken from JavaScript: the good parts :



The if statement changes the flow of the program based on the value of the expression. The then block is executed if the expression is truthy. Here are the falsy values:




  • false


  • null


  • undefined


  • the empty string ''


  • the number 0


  • the number NaN




So basically if you set your var to any of those values, you'll be able to do a if(var){...}


[#92137] Thursday, May 19, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
brianaclaras

Total Points: 23
Total Questions: 106
Total Answers: 111

Location: Japan
Member since Sat, Jun 6, 2020
4 Years ago
;