Jon
Jon

Reputation: 786

javascript undefined check not working

in javascript i am trying to check if a "key" has been defined on an array, and if it doesn't create it and assign a value 0 to it.

the following code is part of a large script and it is inside some loops that change the value of project, country and month

console.log(typeof total_searches[project][country][month]);
if(typeof total_searches[project][country][month] !== "number");
    total_searches[project][country][month] = 0;

but for some reason, when it goes over this 'if' for the second time (all the keys are defined by then) it evaluates as TRUE and assigns 0 to it.

The console.log shows "number" when doing a debug using chrome.

i also tried if(!(month in total_searches[project][country]))

but it still evaluates to TRUE and goes in

what am i doing wrong?

thanks

Upvotes: 0

Views: 177

Answers (3)

Veger
Veger

Reputation: 37905

You have a semicolon after your if-statement, which is seen as the true-statement. So the next line is always executed as it is seen as 'just' another line of code.

Upvotes: 1

Martin Hennings
Martin Hennings

Reputation: 16846

You got a nasty sneaky semicolon after the if.

if(typeof total_searches[project][country][month] !== "number"); // <-- here

Upvotes: 5

brian brinley
brian brinley

Reputation: 2364

!== also does a type match as well. try just !=

Upvotes: 1

Related Questions