Reputation: 382
I want to set a Value in a javascript object only when it is not set. My (test) function looks like:
var test = function(){
this.value = {};
this.setValue = function(seperator, newValue){
console.log((this.value[seperator] === "undefined")); //Why both times false?
if(typeof(this.value[seperator] === "undefined")){
this.value[seperator] = newValue;
}else{
//noop
}
console.log(this.value[seperator]);
}
}
var blubb = new test();
blubb .setValue("foo","bar");
blubb .setValue("foo","notme");
in the js console it returns
false
bar
false
notme
Can someone tell me why both time my test of "undefined" told me that is not defined?
thanks in advance
Upvotes: 3
Views: 6460
Reputation: 27765
Because undefined
in JS is not a string, it's a property of global object and you comparing by type using ===
.
===
will compare not only values but their types too:
1 === "1" // false
1 == "1" // true
Try this:
console.log(( typeof this.value[seperator] === "undefined"));
typeof
operator transforms variable type to string and only then you can check if your variable is equal to string undefined
.
In your second piece of code:
if(typeof(this.value[seperator] === "undefined")){
you use typeof
operator outside of the variable so your code first checks if this.value[seperator] === "undefined"
then it returns false
to you and then you check by "typeof false", it will return boolean
for you.
In final step your code converts to:
if( "boolean" ){
And this is always true
as string is not empty.
Upvotes: 5
Reputation: 38345
Your brackets are in the wrong place in this line:
if(typeof(this.value[seperator] === "undefined")){
You're doing the typeof of (this.value[seperator] === "undefined")
- that's a boolean condition (will return true
or false
) so I'd expect typeof
to give you "boolean"
. Then your if
statements condition is the string "boolean"
which, since it's not zero length, is considered true in JavaScript.
What you wanted is:
if((typeof this.value[seperator]) === "undefined") {
Upvotes: 0
Reputation: 39532
Short answer:
"undefined"
!== undefined
Check for undefined
instead.
> var foo = { foo: 'foo' };
> foo['bar']
undefined
> typeof(foo['bar'])
"undefined"
Also note that typeof(this.value[seperator] === "undefined")
means typeof(boolean)
as it'd first evaluate your expression (this.value[seperator] === "undefined"
) and then get the type of that.
You probably meant typeof(this.value[seperator]) === "undefined"
.
Upvotes: 0