简体   繁体   中英

Javascript Function not defined error in code

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);

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.

(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.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM