0

I have a following task from my mentor:

  1. Type a value with a prompt and make it a number with unary plus

  2. console.log if it's even or odd

  3. If it's not a number, add another console log

Here's the code I have right now, and I can't really understand what's wrong:

x = prompt("Enter your value: ");

if(x % 2 === 0) {
    console.log("x is an even number");
} else  {
    console.log("x is an odd number")
}

if (typeof x === "!Number"){
    console.log("Whoops, it seems like you're mistaken");
} 

1
  • 1
    Try logging typeof x and will find it is always '"string"' Commented Apr 9, 2021 at 0:42

1 Answer 1

2

There're several issues in your code:

  1. You should check the type of x before you judge it's even or odd.

  2. The type of x can only be string since it's come from prompt, but you can still know if it's a valid number string by isNaN() function.

  3. If you want to know whether a type of a variable is number or not, it should be typeof x !== 'number'. typeof x === '!Number' will never be true(also the case matters).

Here's an example that how you could write the code:

let x = prompt("Enter your value: ");

if (isNaN(x)){
    console.log("Whoops, it seems like you're mistaken");
} else if(x % 2 === 0) {
    console.log("x is an even number");
} else  {
    console.log("x is an odd number")
}

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.