Different ways for finding even or odd numbers.
While the modulo operator works fine for testing if a number is even or odd, a faster technique (which I would not expect a beginner to know about) is to use bitwise AND - i.e. &
. Refer to this article for a thorough explanation of how it works.
function isEven(number) {
return !(number & 1);
}
for (let x = 0; x < 6; x++) {
console.log(x, ' is even: ', isEven(x));
}
Other review aspects
Filtering the array
As Lucas already mentioned Array.prototype.filter()
can be used to simplify the addition of elements into evenNumbers
. Array.prototype.reduce()
could be used though it wouldn’t be as concise as each iteration would need to return the cumulative array, and the initial value would need to be set to an array.
While you didn't ask specifically about performance, if you want the code to be as efficient as possible (e.g. it will be run millions (or more) times in a short amount of time, then avoid iterators - e.g. functional techniques with array.filter()
, array.map()
, as well as for...of
loops - use a for
loop.
Declaring variables
const
could be used instead of var
to avoid accidental re-assignment for both arrays, and if the variables were inside a block, the scope would be limited to the block. Note that "It's possible to push items into the array"1 even if it is declared with const
.
Promoting user for input
window.prompt()
“displays a dialog with an optional message prompting the user to input some text.”2. A friendly message could be passed as the first argument to give the user information about the expected input- e.g.
window.prompt(“Please enter a number”);
Additionally:
Please note that result is a string. That means you should sometimes cast the value given by the user. For example, if their answer should be a Number, you should cast the value to Number.
const aNumber = Number(window.prompt("Type a number", ""));
3
So the Number
constructor could be used to store numbers in the array.
numList.push(Number(window.prompt("Please enter a number")));
Sending output with document.write()
Note: Because document.write()
writes to the document stream, calling document.write()
on a closed (loaded) document automatically calls document.open(), which will clear the document.
4
So don’t plan on using that function on scripts that run on webpages with DOM elements existing on the page, lest they get removed.