CobaltBabyBear
CobaltBabyBear

Reputation: 2218

Odd thing with javascript "undefined"

I have the following simple Javascript code.

var input = [
    'one',
    'two'
];

for(var i in input){
    if(typeof input[i+1] == undefined){
        console.log("i is the last index");
    }
}

I don't know if I did something wrong but the console.log() part never executes. Which means it never enters the if condition while clearly the index beyond the last index is undefined.

You can see it in this fiddle.

Please explain..

Upvotes: 0

Views: 108

Answers (7)

Dancrumb
Dancrumb

Reputation: 27529

typeof returns a string. You're comparing it to the undefined value.

Use

if(typeof input[i+1] === "undefined"){

Upvotes: 0

Rob Johnstone
Rob Johnstone

Reputation: 1734

This:

if(typeof input[i+1] == undefined){

Should be:

if(input[i+1] === undefined){

(no need to use typeof)

Upvotes: 5

Shadow Wizard
Shadow Wizard

Reputation: 66389

Turns out that the type of i is string, so to make the code work properly you need to cast it to integer:

for(var i in input){
    if(typeof input[parseInt(i, 10) + 1] === "undefined") {
        console.log(i + " is the last index");
    }
}

Updated fiddle.

Upvotes: 0

Software Guy
Software Guy

Reputation: 3280

That is because the typeof operator returns an string. You need to compare with a string "undefined" like so:

var input = [
    'one',
    'two'
];

for(var i in input){
    if(typeof input[i+1] == "undefined"){
        console.log("i is last");
    }
}

Upvotes: 1

Sergey Rybalkin
Sergey Rybalkin

Reputation: 3026

javascript typeof operator always returns string, so you should compare against 'undefined' like this:

if(typeof input[i+1] === 'undefined')

Here is an updated fiddle - http://jsfiddle.net/Pharaon/V7EJZ/

Upvotes: 0

asifrc
asifrc

Reputation: 5841

Undefined should be a string, "undefined", working fiddle: http://jsfiddle.net/asifrc/vRTsE/1/

Upvotes: 3

Seer
Seer

Reputation: 739

if(typeof input[i+1] === 'undefined') { ... }

Upvotes: 6

Related Questions