This is beginner level. I am trying to create separate arrays for odd and even numbers from the parent array. Below the code:
const arr = [22, 33, 44, 55, 66]
let even = []
let odd = []
function separateArray(arr) {
let j, k
for( let i = 0; i < arr.length; i++ ) {
if( arr[i]%2 === 0 ){
even[j] = arr[i]
j++
}else {
odd[k] = arr[i]
k++
}
}
}
separateArray(arr)
for( let i = 0; i < even.length; i++ ) {
console.log(even[i])
}
I tried calling the function separateArray
and then log the even numbers in the console. But it doesn’t display anything.
2
Answers
The reason why you are not seeing anything in the console is because you have not initialized the values of
j
andk
.In JavaScript, accessing an undefined variable will result in a ReferenceError. You need to initialize
j
andk
to 0 before using them as array indices:Just for fun, here is what you will be able to do one day when you get into more advanced javascript…