Help me understand logical operator "not" or!


#1

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

"write an if/else statement inside happy so that happy returns true if programming is false and false otherwise."
This is how I read the code inside function "happy": if true, return true, else return false. I read it this way because !programming would equal true, since I defined it as equaling false, correct? please help. (The below code said way to go when I pressed run, that's why I'm confused, because the code reads the opposite of the instructions.)

// Declare your variables here!
var programming = false;

var happy = function() {
  // Add your if/else statement here!
  if (!programming) 
  {
      return true;
      
  }
  else 
  {
      return false;
      
  }
};


#2

Yeah it is a wee bit confusing and took me a second to figure it out.

So, you are right when you think you have made programming false when you use (!) on programming, as it makes the false expression true.

!false; // => true

But in your (if) the code is saying "if programming is true then return true" but as you have declared programming as false at the start it returns false.

So your (if) is asking if programming is true which it is not, thus it returns false.

Does that make sense? Let me know if I didn't explain it clearly enough.

But if this got your head around it please mark my reply as the solution. :slight_smile:


#3

This answer definitely helped me look at the code differently, and now I understand! For some reason I was thinking that I was changing the variable to true, instead of saying "if x is true". Thank you for your help, I love that "Aha!" moment. :slight_smile:


#4

No worries at all, I completely agree its all about that "Aha!" moment. Haha.


#5

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