1

I have the following JavaScript code:

function f(){
}

var arrOfFuncs = [f, f, f, f];

for (var i in arrOfFuncs){
    console.log(typeof i);
    console.log(i);
}

When I run the script it prints:

string
0
string
1
...
string
3

Since I am iterating over an array of functions, isn't "typeof i" supposed to be "function" and i.toString() supposed to be "function f(){}"?

2
  • which browser are you using? Commented Sep 6, 2014 at 5:37
  • I am using Chromium browser. Commented Sep 6, 2014 at 15:59

5 Answers 5

2

No. The for…in construct iterates over the keys of an object or array, not its values.

You can use a simple for loop:

for (var i = 0; i < arrOfFuncs.length; i++){
    console.log(typeof arrOfFuncs[i]);
    console.log(arrOfFuncs[i]);
}

Or modify your for…in loop like this:

for (var i in arrOfFuncs){
    console.log(typeof arrOfFuncs[i]);
    console.log(arrOfFuncs[i]);
}

Or you could use the forEach method (introduced in ECMAScript 5.1):

arrOfFuncs.forEach(function(f) {
    console.log(typeof f);
    console.log(f);
});
Sign up to request clarification or add additional context in comments.

Comments

1

When you iterate over keys of an object with for(var in in ...) i will equal the key - in the case of an array you are getting the indices as well as properties of the array (0, 1, 2, length, etc) and the type of that index or property key might very well be a string.

You want to access the value of the array at that key, so you need to do arrOfFuncs[i] - that said, it is probably better to use either .forEach or some equivalent if you can or use

for (var i = 0, l = arrOfFuncs.length; i < l; i++) {
    var value = arrayOfFuncs[i];
}

Because you avoid the risk of accessing properties on the array you don't intend to access.

Comments

0

in your code i is the key it's not value. so your code should be like this to get function type:

function f(){
}

var arrOfFuncs = [f, f, f, f];

for (var i in arrOfFuncs){
    console.log(typeof arrOfFuncs[i]);
    console.log(arrOfFuncs[i]);
}

Comments

0

When you use for..in you are running over keys and not over values. Read about JavaScript for..in loops.

This code will do what you want:

function f(){
}

var arrOfFuncs = [f, f, f, f];

for (var i in arrOfFuncs){
    console.log(typeof arrOfFuncs[i]);
    console.log(i);
}

JSFIDDLE

Comments

0

in for in iteration over arrays, i doesn't represent the element, it represents the index.

the below code works:

var array = [function f(){}, function k(){}];

for (var i in array) {
    console.log(array[i]); //function()
    console.log(typeof array[i]); //function
}

Comments

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.