Why does this for loop in Javascript give me a number instead of the list of numbers from 0 to 4?

Viewed 135

I know that the normal behavior of a for loop is similar to this:

for(let i = 0; i<5; i++){
    console.log(i);
}

which gives me this result:
0

1

2

3

4

However the following code gives me a 5 as a result and I do not know why it doesn't give me a result similar to the example above.It doesn't behave as a for loop because it doesn't have into account the initializer. Thanks a lot for your help.

 function charCount(str){

    for(var i=2;i<=str.length;i++){
        result = [i]
    }
    return result; 
}
charCount('hello')
3 Answers
function charCount(str) {
    result=[];
    for(var i=2;i<=str.length;i++){
        result.push(i);
    }
    return result; 
}
charCount('hello')

When doing result=[i], you are just resetting whole array, push() appends i to the existing array in every iteration.

This code return "5" because

In your code you return last value of result

for example you pass string "hello" then for loop iterate 2 to 5(str.length) so in the last result variable has a value as 5 so when you return result valriable it return 5.

for returning all number 0 to 5 then modify your code

result.push(i)

so every time number store iin result list and in the last you return that list

You can also iterate through the count and push the values into a new array using the keys without .push() by referencing the key in a bracket within the for loop. By assigning the arrays key value with a bracket before you define the next value, you are ensuring that you are iterating through to a new key\value pair inside the array with each iteration up to the str length.

function charCount(str) {
    result=[];
    for(var i = 0; i < str.length; i++){
        result[i] = i;
    }
    return result; 
}
console.log(charCount('hello'))

Also consider the following code using a forEach loop where you can define your key/value pairs for parsing within the loop...

function charCount(str) {
    result=[];
    str = str.split(''); // split the string 
    str.forEach(function(value, index){
      result[index] = value;
      // or result[index] = index --> to push in the numbered values of the keys as values to the array --> [0,1,2,3,4];
    })
    return result; 
}
console.log(charCount('hello'))

Related