for loop returns 0 if array length more than 1 Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of for loop returns 0 if array length more than 1 without wasting too much if your time.

The question is published on by Tutorial Guruji team.

I am doing a coding challenge where you are given an array of string like so: [life, Petes kata, eating, kata]

and your code is supposed to return a value based of of whats in the string:

kata = 5
function paul(x) {
    let returnString = 0
    var i;
    for (i = 0; i < x.length; i++) {
        if (x.includes('life') === true) {
            returnString += 5
        } else if (x.includes('eating') === true) {
            returnString += 1
        } else if (x.includes('Petes kata') === true) {
            returnString += 10

    return returnString

At the moment my function works fine if there is only one word in the array. life returns 5, and Petes kata returns 10, as it should. However when there is more than 1 word in the array, the function will always return 0, and I am not sure why.

I thought that wrapping the if statements with a for loop would make the function add to returnString several times, and if it were only working on the first word I could also understand that, but returning 0 has been puzzling me for a while.
I thank you in advance for your help.


With the change to requirement, you can approach the problem of counting occurrences like so….

 function paul(x) {            
        let score = 0;   
        x.forEach(s =>  {
          if(s == 'life') score+=5;
          else if(s == 'eating') score +=1;
          else if(s == 'Petes kata') score +=10;
        return score
    console.log(paul(['life', 'Petes kata', 'eating', 'kata','life']))
We are here to answer your question about for loop returns 0 if array length more than 1 - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji