0

What happens when I try to loop on an int like this:

var x = 0;
for (var k in x) {
  // x[k]
}

Should I look for unexpected behavior or does it just not enter the loop? (so far my experiments seem to show that it does not enter the loop... but it could do something I don't see)

3 Answers 3

2

There are no methods defined in the vanilla JavaScript Number object prototype. Your code enters the loop (all objects in JS can be iterated) but there is nothing to iterate over in this case.

If you would do:

Number.prototype.foo = "bar";

Your loop body would run once for the foo property.

Sign up to request clarification or add additional context in comments.

3 Comments

Actually, there are methods: toFixed, toPrecision, etc. but I assume they are not enumerable.
@Felix: You are right. They also do not show up in the Chrome debugging console (console.dir(0) says "no properties").
Yes I tried the same. I think in this case the value is not converted to an object. console.dir(new Number(0)) works though (__proto__ shows contains these methods).
1

x isn't a collection. What is there for it to iterate through?

3 Comments

because I'm not he only one to use my code. Very short example: function f (x) { for (var k in x) { document.write(x[k] + "<br />"); } } f(0); f(mycollection); (sorry for the bad formating)
@Hugo: That's what documentation is for. If someone passes values to your function that it does not understand: not your problem.
You're absolutly right. But you'll agree that getting a better knowledge on how things work cannot harm (thx for your comments, btw)
0

Only objects can be iterated with the for in loop.

So, say you have a variable a that holds a reference to something. If typeof a !== 'object' then you cannot iterate over your a var.

Note that you can iterate over arrays, as arrays are objects too (alert(typeof [])).

As for your example, x is not an object, it is a number (typeof x == 'number'), so the for in will not work; but if you declare your number as a Number object :

var x = new Number(0);

you can loop over its methods since now typeof x == 'object'

1 Comment

I think JavaScript will automatically convert the number to a Number object in this case.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.