# Simple functions don't work :(

#### yoop

Hi. I've been learning javascript for a few days. I got two tasks to solve and I have no idea why they don't work.

First:

Code:
function filterEvenNumbers(numbers) {
let evenNumbers = [];

for (let i = 0; i < numbers.lenght; i++) {
if (numbers[i] % 2 === 0) {
evenNumbers.push(numbers[i]);
}
}

return evenNumbers;
}
console.log(filterEvenNumbers([1, 2, 3, 4, 5, 6]));

function returns an empty array

and second:

Code:
function countOccurrences (array, element) {
let counter = 0;
for (let i = 0; i < array.lenght; i++) {
if (array[i] === element){
counter++;
}
}
return counter;
}
console.log(countOccurrences([2, 1], 1));

functions always returns 0, and in this case it should be 1

#### FResher

It's a keyword bad syntax ... fix your lenght , by length

#### yoop

omg... Im so stupid.

Thanks

#### VBService

As a curiosity, also check out this record of the "for" loop

JavaScript:
function filterEvenNumbers(numbers) {
const evenNumbers = [];
for (const number of numbers)
if (number % 2 === 0)
evenNumbers.push(number);
return evenNumbers;
}
console.log(filterEvenNumbers([1, 2, 3, 4, 5, 6]));

or

JavaScript:
function filterEvenNumbers(numbers) {
for (const index in numbers)
if (numbers[index] % 2 !== 0)
numbers.splice(index, 1);
return numbers;
}
console.log(filterEvenNumbers([1, 2, 3, 4, 5, 6]));

JavaScript:
function filterEvenNumbers(numbers) {
const evenNumbers = [];
numbers.forEach((index) => {
if (numbers[index] % 2 === 0)
evenNumbers.push(numbers[index]);
});
return evenNumbers;
}
console.log(filterEvenNumbers([1, 2, 3, 4, 5, 6]));

or

JavaScript:
function filterEvenNumbers(numbers) {
numbers.forEach((number, index) => {
if (number % 2 !== 0)
numbers.splice(index, 1);
});
return numbers;
}
console.log(filterEvenNumbers([1, 2, 3, 4, 5, 6]));

BTW,
I don't know what exactly you are learning, something about:
• Functions
• Loops
• Arrays

JavaScript:
function filterEvenNumbers(numbers) {
return numbers.filter(number => number % 2 === 0);
}
console.log(filterEvenNumbers([1, 2, 3, 4, 5, 6]));

or use Array.reduce() in this unusual way

JavaScript:
function filterEvenNumbers(numbers) {
return numbers.reduce((filtered, number) => {
if (number % 2 === 0)
filtered.push(number);
return filtered;
}, []);
}
console.log(filterEvenNumbers([1, 2, 3, 4, 5, 6]));

Last edited:

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

### Members online

No members online now.