0

I am new to Javascript and I don't understand why I am getting an error for this piece of code. Please help me understand what syntax I am got wrong.

var isEven = function(number){
    if(number % 2 = 0){
        return true;
    } else {
        return false;
    };
};

isEven(5);
2
  • 1
    What browser did you run this in? In Chrome at least it gives a fairly obvious error message in the console: Invalid left-hand side in assignment Commented May 31, 2015 at 13:35
  • 1
    @RGraham It's a tutorial in codecademy - I am not familiar with how to respond to the error messages yet - But now I'll know what that means in future Commented Jun 1, 2015 at 11:10

3 Answers 3

2

Change

if(number % 2 = 0)

to

if(number % 2 === 0)

because you want to test if the modulo 2 of number has no remainder. What you wrote was an illegal assignment operation.

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

1 Comment

Thanks! I keep forgetting this coming from a VBA background. Much appreciated.
1
(number % 2 = 0)

should be

(number % 2 == 0)

or

(number % 2 === 0)

One equal sign is assignment, the double equal sign is "equal to."

More info:

Triple equal sign matches type and value. (This is a good habit to get into using when possible.) Types are like "number", "object", "string" etc.

(number % 2 == 0) // true
(number % 2 == "0") // true
(number % 2 === 0) // true
(number % 2 === "0") // false

Otherwise, == might work with other things the computer considers zero, maybe null, maybe empty quotes, or maybe not, there's so many caveats in JS typing, === prevents most of those type headaches.

Comments

1

You are using the assignment operator instead of the equality operator in your if statement. This causes a JavaScript error because the value on the lefthand side of the operator isn't a variable, it's an expression.

What you want to do is check for equality. To do this, change = to === in your if statement.

if (number % 2 === 0)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.