0

I'm trying to merge this two codes to run as a working function that print out odd and even numbers. but I don't know on how to use a var

let num = [1,2,3,4,5,6,7,8,9,];

console.log('even numbers are');
for (var i = 1 ; i < 10 ; i += 2 ) {
   console.log(i);
}


console.log('odd numbers are ');
for (var i = 2 ; i < 10 ; i += 2 ) {
  console.log(i);
}

Help. Thanks

1

2 Answers 2

3
const isOdd = (n) => (n & 1) === 1;

const num = [1,2,3,4,5,6,7,8,9];

console.log( `Odd numbers are ${ num.filter( n => isOdd(n))}` );
console.log( `Even numbers are ${ num.filter( n => !isOdd(n))}`);
Sign up to request clarification or add additional context in comments.

2 Comments

I dont understand the (n) and the arrow sign
That's an arrow function, syntactic sugar for a function assignment. You could also say const isOdd = function(n) { return n & 1 === 1 }
1

Use below code to print out Even Numbers and in the same way you can get Odd numbers list given in an Array

    var arr = [1, 2, 3, 4, 5, 6];

    for (var i = 0; i < arr.length; i++) {
        if (arr[i] % 2 === 0) {
            console.log(arr[i] + "");
        }
    }

If you are trying to put your JS code inside HTML Page, refer to the link for more details Find Even Numbers in JS

8 Comments

Im using only javascript so i have no idea about the %, and the document.write
Well, you can use console.log method to print out numbers instead of document. Write method and % is an arithmetic operator to check reminder. If Num%2==0(0 is a reminder) it means Number is Even
what should i console log?
just print numbers using Console.log(arr[i])
good to listen. provide positive feedback if it helped so other community can also take benefit of that
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.