This should be something simple, but I miss why this code outputs 'undefined', while I expect to get an array with numbers: [1, 2]. I tried to debug it in console step by step, but still don't understand why newArr doesn't return from the function. Could someone explain, please.
function filterList(arr) {
let newArr = []
for(let i = 0; i <= arr.length; i++) {
if (typeof arr[i] !== "number") {
return
}
if (typeof arr[i] === 'number') {
newArr.push(arr[i])
}
}
return newArr
}
console.log(filterList([1,2,'a','b']))
The first return that is reached inside a function will end the function call and will return whatever you set there.
In your case, you are pushing 2 values in the array, but as soon as you reach the third one a you are just using return. This means that you are returning undefined. You should return newArr
function filterList(arr) {
let newArr = []
for(let i = 0; i <= arr.length; i++) {
if (typeof arr[i] !== "number") {
return newArr
}
if (typeof arr[i] === 'number') {
newArr.push(arr[i])
}
}
return newArr
}
console.log(filterList([1,2,'a','b']))
remove return in for loop
function filterList(arr) {
let newArr = []
for(let i = 0; i < arr.length; i++) {
if (typeof arr[i] === 'number') {
newArr.push(arr[i])
}
}
return newArr
}
const arr = [1,2,'a','b']
console.log(filterList(arr))
// with Array.filter
let result1 = arr.filter(ele => typeof ele === 'number')
console.log(result1)
// with Array.reduce
let result2 = arr.reduce((res, ele) => typeof ele === 'number' ? [...res, ele] : res, [])
console.log(result2)
function stopFunc(isStop = false) {
let total = 0
for(let i = 0; i < 10; i++) {
total += i
if(isStop) return 999
}
return total // return 45
}
console.log(stopFunc())
console.log(stopFunc(true))
you can check stopFunc function in my example, The return statement ends function execution and specifies a value to be returned to the function caller. . in your function :
if (typeof arr[i] !== "number") {
return
}
return omitted, undefined is returned instead.
You can check document return
You're returning from the function immediately on finding an element that isn't a number, and the return value from the function is undefined not the array you've been patiently pushing numbers into. Just remove that statement altogether.
function filterList(arr) {
const newArr = [];
for (let i = 0; i <= arr.length; i++) {
if (typeof arr[i] === 'number') {
newArr.push(arr[i]);
}
}
return newArr;
}
console.log(filterList([1, 2, 'a', 'b', 3, 4]))