Javascript condition [closed]

0

I started to study javascript recently and the following code is only giving me the wrong answer, where did I go wrong?

When I play at the prompt to check if it's right, it gives me "n1 is odd"

// Verifique se um número é par ou ímpar
var n1 = 4;
var sobra = n1%2;

if(sobra = 0){
    console.log("n1 é par")
}else{
    console.log("n1 é ímpar")
};
    
asked by anonymous 09.10.2018 / 14:33

1 answer

2

Hello, the error is very simple, you are using the assignment operator '=', the correct serious comparison operator '=='.

Documentation for more information about the operators .

var n1 = 4;

var  sobra = n1%2;

if (sobra == 0) {
    console.log('n1 é par');
} else {
    console.log('n1 é impar');
}

Another way to do it serious :

var n1 = 4;

if ((n1 % 2) == 0) { 
    console.log('n1 é par');
} else {
  console.log('n1 é impar');
}

With ternary operator, more information in the documentation :

var n1 = 4;
(((n1 % 2) == 0) ? console.log('n1 é par') : console.log('n1 é impar'));
    
09.10.2018 / 14:44