Results Of "truthy" And "falsey" Is Confusing In JavaScript
Solution 1:
typeof
returns the type name of the value, which is always a non-empty string. A non-empty string is truthy.
> typeof someUndefinedVariable
"undefined"
> typeof (typeof someUndefinedVariable)
"string"
> Boolean("undefined")
true
See also All falsey values in JavaScript
Solution 2:
First, I'll explain what happened in the code you've shown, just to be sure you understand it. Maybe you already understand the first half, but since you say you are very confused, I will assume you don't.
myVariable = undefined ? "truthy" : "falsey";
// result: "falsey"
Here you are looking at a value, undefined
, and asking a question: is it truthy or falsey? Based on that you choose a string. Then you store that string into myVariable
. It is effectively the same as this code:
var myVariable;
if (undefined) {
myVariable = 'truthy';
} else {
myVariable = 'falsey';
}
Since undefined
is always falsey, at the end, myVariable
contains the string 'falsey'
.
Here is your second snippet of code:
myVariable = typeOf someUndefinedVariable ? "truthy" : "falsey";
// result: "truthy"
First, I must point out that typeOf
is not a valid function or operator in any Javascript runtime I know of. I will assume that was a typo, and you meant to use typeof
instead. The code above, as written, should throw a syntax error. Corrected, we have...
myVariable = typeof someUndefinedVariable ? "truthy" : "falsey";
// result: "truthy"
And for clarity, let's rewrite it as an if/else:
var myVariable;
if (typeof someUndefinedVariable) {
myVariable = 'truthy';
} else {
myVariable = 'falsey';
}
As another answerer has pointed out, typeof will always return, as a string, the type of the symbol you give to it.
typeof(someUndefinedVariable);
"undefined"
And since all strings except the empty string are truthy, you get truthy back.
There are only 7 falsey values in Javascript.
false Boolean false
undefined If a symbol is not defined at all
null A defined symbol, but it has no value inside
0 Numeric positive 0
-0 Numeric negative 0
'' or "" Empty string
NaN Magic value "Not a Number"
All other values in Javascript are truthy.
- any string except empty string
- any number except 0
- any array, including an empty array
- any object, including an empty object
- functions
- etc ...
Post a Comment for "Results Of "truthy" And "falsey" Is Confusing In JavaScript"