2. If / else if / else - Got it right; but don't understand why :(


#1


https://www.codecademy.com/courses/javascript-beginner-en-qDwp0/0/2?curriculum_id=506324b3a7dffd00020bf661


I am trying to understand isNaN(number) -- don't we want to say, in plain english:

"if isNaN returns true then write "Not a number (or similar)!"

so I thought it would be as such:

else if ( isNaN(number) = true) {
return "Not a number!"
}

but how come:

else if (isNan(number)) {
return "Not a number!"
}

... works just the same? I can't understand this logic, please help!

Thanks in advance!


var isEven = function(number) {
  // Your code goes here!
  if (number%2 === 0) {
      return true;
  }
  else if (isNaN(number)=true) {
      return ("Put a number in here dude!");
  }
  else {
      return false;
  }
};


#2

this is invalid:

else if ( isNaN(number) = true)  {
return "Not a number!"
}

it should result in a error: ReferenceError: invalid assignment left-hand side

if you want to compare, use two or three equal signs, a single equal sign is assign.

so your question is why are both isNaN(number) == true and isNaN(number) the same?

take a look at this condition:

if (true){  console.log("perfectly valid");}

see? A boolean is perfectly valid for a if condition, and isNaN is a function, which returns true or false, so you don't have to compare it with true. You may of course, but it isn't strictly necessary.


#4

First of all, thanks for your time stetim94, okay so am I understanding this properly:

it is implicitly understood that any function is true?

isNaN(number)

another question:

but we need to be explicit if we need a function to be false? so for example in this case would be:

isNaN(number) = false

if you can elaborate on that, that would be awesome - thanks again for all your help


#5

no, isNaN is a build in function, but no different from a function you can write using the function keyword. The person who build the isNaN (is not a number) function decided to return true if the argument (in this case number) is not a number, if it is a number, false is returned.

well, that would always be false, since you use a single equal sign (which means assign), use two equal sings to compare the result of isNaN(number) with false


#6

ok, I think I understand, thanks!


#7

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.