Why does the function return undefined?

  • 0
    let arr = [1,1,1,1,1,2,3,4,1,2,3,4,2,3];
    function nam(val){
        let array= val;
        let res = [];
    
        for(let i = 0; i < array.length; i++){
            if(res.includes(array[i]) ) return
            res.push(array[i])
        }
    
        return res;
    }
    nam(arr);


    I know how to write it correctly, but why exactly this record returns undefined? There is a check, "if the array contains an element X, then go to the next iteration. But logically, if the condition is false, then the loop should go further and add the element to the array?"
    JavaScript Anonymous, Nov 5, 2019

  • 1 Answers
  • 0
    Because the line feed after return is perceived by the JS engine as a boundary between operators. It's like there is a semicolon.

    If written in one line, it will not be undefined:

    if(res.includes(array[i]) ) return res.push(array[i])




    Well, in general, return is not needed here at all.

    After all, return is an exit from a function.

    And you need to exit the current loop iteration - this is continue.
    Anonymous

Your Answer
To place the code, please use CodePen or similar tool. Thanks you!