Kodeclik Blog


Javascript 'if not'

In Javascript, "if not" is not a specific operator or syntax. However, the logical NOT or Negate operator (!) can be used inside an if statement to negate a Boolean value. The NOT operator reverses the Boolean value of an operand. For example, it changes true to false, and vice-versa. It is considered a negation.
Here's an example of how to use the NOT operator in an if statement:
In the code above, we first declare a variable isActive and assign it a value of false. We then use the NOT operator (!) inside an if statement to negate the value of isActive. Since isActive is false, the condition inside the if statement is true, and the code inside the block is executed. Therefore, the output to the console is "not active".
Using the NOT operator in an if statement can make your code more concise and easier to read, especially in cases where you need to negate a Boolean value.

Using “if not” in a text adventure game

Let's create a simple text adventure game where the player comes to a fork in the road and has to choose which path to take. We'll use "if not" to check if the player has entered a valid choice.
In the code above, we first declare a variable choice and use the prompt() function to ask the player which path they want to take. We then use "if not" (!) to check if the player has entered a valid choice. If choice is null, undefined, or an empty string, the condition inside the first if statement is true, and the code inside the block is executed. Therefore, the output to the console is "You didn't enter a choice. Please try again.".
If the player has entered a choice, we use toLowerCase() to standardize it, i.e., to convert the choice to lowercase and compare it to the strings "left" and "right". If the choice is "left", the condition inside the second if statement is true, and the code inside the block is executed. Therefore, the output to the console is "You chose to go left. You come across a river.". If the choice is "right", the condition inside the third if statement is true, and the code inside the block is executed. Therefore, the output to the console is "You chose to go right. You come across a mountain.".
If the player has entered a choice that is not "left" or "right", the condition inside the first if statement is false, and the condition inside the second if statement is false. Therefore, the condition inside the fourth if statement is true, and the code inside the block is executed. Therefore, the output to the console is "That's not a valid choice. Please try again.".
If you liked this blogpost, checkout our post on understanding the use of NaNs in Javascript.
Want to learn Javascript with us? Sign up for 1:1 or small group classes.

Join our mailing list

Subscribe to get updates about our classes, camps, coupons, and more.
  • ABOUT

Copyright @ Kodeclik 2024. All rights reserved.