I am writing a very simple program in JavaScript to check a number is an odd number or even number. and here is my code.
function run(number) {
var result;
if(number % 2 == 0) {
result == 'even';
}
else {
result == 'odd';
}
return result;
}
As you can see, very easy to understand, right? I have the variable number and check it. I thought that my algorithm is correct. But the program still does not run.
Could you please show me why the program has the problem ? Thank you very much for your time.
Two things here
function run(number) {
var result;
if (number % 2 == 0)
result = 'even';
else
result = 'odd';
return result;
}
const val = run(11);
console.log(val);
You should be using = (assignment operator) as you're assigning value to a variable and not comparing them (== or === are called comparison operators).
And make sure you actually call the function
As the other answers & comments already point out, == is not storing the result but instead, an operator to compare two variables. One equal sign would do the job. Additionally, I'm suggesting the shorthand version (recommended once you understood what went wrong in the first place):
function run(number) {
return (number % 2 == 0) ? 'even' : 'odd';
}
console.log(run(5))
console.log(run(6))