Reputation: 109
Learning about the typeof
keyword and need some clarification:
While troubleshooting I outputted this code to the console:
console.log(typeof object.prop[someNum - 1]);
(in this case sumNum === 0
)
The console printed out undefined
which is what I expected because the index position [someNum - 1]
in the prop[]
array doesn't exist (so I thought).
However when I do something like this:
if(typeof object.prop[someNum - 1])
//some code
else
//other code
It evaluates as true and runs //some code
but when I do this:
if(object.prop[someNum - 1])
//some code
else
//other code
It evaluates as false and runs //other code
.
I was under the impression that undefined
is considered a falsy value
and would evaluate false in an if statement
. Why is the if(typeof object.prop[someNum - 1])
statement evaluating as as true? Also can someone point me in the right direction as to where I can learn more about negative indexing arrays in js
? Are they handled the same across multiple languages like c#, c++, java, & php
. I thought when evaluating a negative array
index number it would be underfined
or throw an error.
Upvotes: 3
Views: 80
Reputation: 782785
As other answers have pointed out, typeof
returns a string, and it will always be truthy because it never returns an empty string. If you want to test if the type is undefined
, you need to compare the string.
if (typeof object.prop[someNum - 1] == "undefined") {
// some code
} else {
// some code
}
You could also just test whether the value is undefined
:
if (object.prop[someNum - 1] === undefined) {
// some code
} else {
// some code
}
Make sure you use ===
rather than ==
, so it won't report a match if object[someNum - 1]
is null
.
Upvotes: 1
Reputation: 147553
As SLaks says, you're evaluating if the string "undefined" is truthy, which it is.
If you want to see if an object has a property called "someNum - 1" then you can use the in operator:
if ((someNum - 1) in object.prop)
which will return true if object.prop has such a property anywhere on itself or its [[Prototype]]
chain, or:
if (object.prop.hasOwnProperty(someNum - 1))
to test for the property directly on the object.
Upvotes: 1
Reputation: 888303
typeof
always returns a string.
Therefore, you're writing if ("undefined")
.
Since non-empty strings are truthy, that if will run.
Upvotes: 5