javascripttypeerror

TypeError : a is not iterable


const a= [1,2,3,4,5,6,7,8,9,10];
function evenNum (a){
    for (let element of a){
        if (element%2===0){
            console.log(element);
        }
    }
};

console.log(oddNum());


function oddNum (a){
    for (let element of a){
        if (element%2!=0){
            console.log(element);
        }
    }
};

console.log(evenNum([1,2,3,4,5,6,7,8,9,10]))

Learning javascript as a complete beginner to programming in general. As I was following this video text in this "exercise" we wanted to display only the odd and even numbers in the array.

While the second function works ok, I don't understand why can't I declare an array before the evenNum function and use the array as a parameter of the next function.

Was expecting the same results as the function below.


Solution

  • This is the problem:

    function evenNum (a) {
    

    This function definition declares a as a local function parameter, so it is NOT the same variable as the global array that is also named a.

    It will probably be easier to understand if you give the function parameter a different name than the global array.

    This is also a problem:

    console.log(oddNum());
    

    You defined the oddNum() function to require a parameter, and yet you are calling it without a parameter.