What passes as true (or false) in an if statement for a variable
Asked Answered
T

2

6

In this code, what values of myVar will behave as true and false?

if(myVar){}

In JavaScript for example, the following values are falsy

null
undefined
0
''
false
Thersathersites answered 27/6, 2011 at 12:57 Comment(0)
O
13

Object

false if the instance is null; true otherwise

String

false if the value is null or the empty string ""; true otherwise

Number, int, or uint

false if the value is NaN or 0; true otherwise

null

false

From here.

Odellodella answered 27/6, 2011 at 13:6 Comment(0)
P
1

If (myVar) is a bool, then it'll obvious pass if it's true, and fail if not. If the bool was never initialized (like var myBool:Boolean; instead of var myBool:Boolean = true) then it's false by default. This same concept applies to builtin objects like Number, int etc. Pretty much for everything else, it will only pass as true if the object has been initialized through the object constructor or through a direct assignment, like so:

var a:MovieClip = new MovieClip();

var b:MovieClip = a;
Ptolemy answered 27/6, 2011 at 13:5 Comment(1)
One minor correction to what I said about how this concept pretty much applies to all "builtin" objects, that even isn't necessarily true. Some objects like the Array object are null unless initialized as well. And as you've stated in your question it's pretty much the same, null and undefined will fail.Ptolemy

© 2022 - 2024 — McMap. All rights reserved.