Reputation: 972
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);
Upvotes: 0
Views: 37
Reputation: 532445
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)
Upvotes: 1
Reputation: 904
(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.
Upvotes: 1
Reputation: 23660
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.
Upvotes: 2