Skip to content

Instantly share code, notes, and snippets.

@crtr0
Created December 27, 2012 18:24
Show Gist options
  • Save crtr0/4390616 to your computer and use it in GitHub Desktop.
Save crtr0/4390616 to your computer and use it in GitHub Desktop.
Can anyone explain why the if statement below never succeeds? I am running it as part of a Node.js v0.8.7 app.
var arr = ['a', 'b', 'c'];
for (i in arr) {
if (i === 0) {
console.log('do something special')
}
}
// sadly, that console.log never happens
@paranoiacblack
Copy link

Uh, I'm guessing you mean to do i == 0 to match 'a' instead of i === 0. The difference is that == will try to do type coercion to transform 'a' into 0, but === will not.

@xdenser
Copy link

xdenser commented Dec 27, 2012

Bacause this
var arr = ['a','b','c']; for(i in arr) console.log(typeof i);
shows
string string string
I think this is in operator giving strings as it is intended to list object keys.

@crtr0
Copy link
Author

crtr0 commented Dec 27, 2012

You're right, but why isn't it an integer in the first place? Why is it "0", "1" and "2" instead of 0, 1 and 2?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment