-1

Could someone explain me why it prints [ '01', '11', '21' ]. I'm normally a java - Python - PHP dev

function g(element){
    return element + 1;
}
function f(points, g){
    let newArray = [];
    for(let point in points){
       newArray.push(g(point));
    }
    return newArray;
}



let array = [1, 2, 3];

console.log(f(array, g));
Robbie Milejczak
  • 5,664
  • 3
  • 32
  • 65

3 Answers3

1

Yes, this is a javascript weirdness.

At first, the for in loop will iterate over the indizes, not the content of the array. This is "0", "1", "2".

The indizes do also seem to be interpreted as strings.

"0"+1=01
"1"+1=11
"2"+1=21

dan1st
  • 12,568
  • 8
  • 34
  • 67
0

You are looping of the Keys by using in keyword in your for statement, To loop over array items use of keyword.

So your loop will be like this:

for(let point of points){
    newArray.push(g(point));
}
Dahou
  • 522
  • 4
  • 12
0

The output looks as if the input array was ["0","1","2"] and not [1,2,3].

The mistake here is that the syntax for..in in javascript is used to loop through the keys/indexes of an object/array, not its values.

Something to notice here (which I did't know before and checked) is that the indexes of the array are converted to string when using a for..in, that's why the numbers were concatenated rather than summed.

Anyway, one correct syntax to loop through the elements of an array is the for..of syntax, which is used just like the for..in syntax and behaves as you expected.

kotem13
  • 71
  • 4