If you're seeing this message, it means we're having trouble loading external resources on our website.

If you're behind a web filter, please make sure that the domains *.kastatic.org and *.kasandbox.org are unblocked.

Main content

Conditionals with if, else, and Booleans

As humans, we make decisions every day, like what to eat for lunch or whether to wear a raincoat. When we make those decisions, we consider many conditions of our world, like the contents of our fridge for the lunch decision, or the weather outside for the raincoat decision.
Computer programs also make decisions, using Boolean expressions (true/false) inside conditionals (if/else). Thanks to conditionals, programs can respond differently based on different inputs and parameters.

A simple conditional

Imagine we're writing a program to help us decide what to wear outside each day. There are a lot of conditions we can come up with this program, but let's start simple: if the temperature is below freezing, the program should warn us to wear a snow jacket.
Here's that logic in a flowchart:
Flowchart that starts with diamond that says "Is temperature less than or equal to 32?". Diamond has arrow labeled "TRUE" that leads to rectangle that says "Display: "Wear a snow jacket!".
We can program that flow in JavaScript using an if statement:
if (temperature < 32) {
  println("Wear a snow jacket!");
}
Let's breakdown that syntax. The general structure of every if statement looks like this:
if (<condition>) {
  <instructions>
}
The condition and instructions are what differ; that's where the magic happens.
The condition is a Boolean expression: an expression that evaluates to either true or false. Boolean values are another type of data type in programming languages, and they can only ever hold true or false.
For example, we can store the results of that Boolean expression in a variable:
var belowFreezing = temperature < 32;
Depending on the current value of temperature, the belowFreezing variable will now store either true or false.
We can even substitute the condition with the variable:
var belowFreezing = temperature < 32;
if (belowFreezing) {
  println("Wear a snow jacket!");
}
However we code it, the condition needs to evaluate to either true or false, because that tells the computer whether to execute the instructions inside the curly brackets or not.
The instructions can be anything your program is capable of doing, and they can be as long as necessary.
✏️ Try changing the value of temperature in the program below and see what happens. You can also change the condition or the instructions.
📝 See similar code in: App Lab | Snap | Python
Note: typically, a program like this would read the value of temperature from a sensor or other input device, but for simplicity, we're hardcoding the value into the program.

Comparison operators

Our Boolean expression above used the comparison operator <= to determine whether one number is less than or equal to another number. There are many comparison operators in programming languages to determine different relationships between values, especially numbers.
Here are the relational operators in JavaScript:
OperatorMeaningTrue expressions
>Greater than60 > 32
>=Greater than or equal60 >= 3232 >= 32
<Less than20 < 32
<=Less than or equal20 <= 3232 <= 32
===Strict equality32 === 32
==Equality32 == 32"32" == 32
!==Strict inequality30 !== 32"32" !== 32
!=Inequality30 != 32
JavaScript is a bit of a tricky language here, because it has both equality operators and "strict" equality operators.
The equality operators will first try to force both sides of the expression to be the same type (like by converting them both to numbers), and then check for equality. The strict equality operator will see that two values are different types and immediately decide they can't possibly equal each other. We recommend using the strict operators because they lead to more predictable code.
Most programming languages do not have both types of equality operators, but you may encounter other differences in the way that languages decide if two variables are equal.
✏️ The program below displays all sorts of messages based on the yourAge variable. Try changing that to different values to see what output is displayed. You can also add more if statements to the program.
📝 See similar code in: App Lab | Snap | Python

The else statement

With if statements, our programs can execute a set of instructions only if the condition is true. If we want our programs to execute a different set of instructions when the condition is false, then we can use an else statement.
Imagine a super simple password checking program. The logic flow looks like this:
Flowchart that starts with diamond that says "Is password equal to TOPSECRET?". First arrow is labeled "TRUE" and leads from diamond to rectangle that says "Display: 'You got it!'". Second arrow is labeled "FALSE" and leads from diamond to rectangle that says "Display: 'Try again!'".
We can program that using an if statement followed by an else statement:
if (password === "TOPSECRET") {
   println("You got it!");
} else {
   println("Try again!");
}
📝 See similar code in: App Lab | Snap | Python
Our program is guaranteed to always go down one of the two paths: either the condition is true and it goes down the first path, or it's false and it goes down the second path.
✏️ The program below builds on the earlier age checking program, adding else statements everywhere. Now you can easily see what you can and cannot do at any age. Fiddle with the yourAge variable and see how the output changes.
📝 See similar code in: App Lab | Snap | Python

Conditionals in pseudocode

This pseudocode represents a single if statement:
IF (<condition>)
{
     <instructions>
} 
This pseudocode includes an else statement with a second set of instructions that can be executed instead:
IF (<condition>)
{
     <instructions 1>
} 
ELSE 
{
     <instructions 2>
}
These are the relational operators in pseudocode:
OperatorMeaning
a = bEquality
a ≠ bInequality
a > bGreater than
a < bLess than
a ≥ bGreater than or equal
a ≤ bLess than or equal
Here's the password checker logic in pseudocode:
IF (password = "TOPSECRET")
{
   DISPLAY("You got it!")
}
ELSE {
   DISPLAY("Try again!");
}

🙋🏽🙋🏻‍♀️🙋🏿‍♂️Do you have any questions about this topic? We'd love to answer— just ask in the questions area below!

Want to join the conversation?

  • leaf red style avatar for user layaz7717
    What does "JavaScript is a bit of a tricky language here, because it has both equality operators and "strict" equality operators.
    The equality operators will first try to force both sides of the expression to be the same type (like by converting them both to numbers), and then check for equality. The strict equality operator will see that two values are different types and immediately decide they can't possibly equal each other. We recommend using the strict operators because they lead to more predictable code," mean?
    (3 votes)
    Default Khan Academy avatar avatar for user
    • leaf green style avatar for user Shane McGookey
      There are two equality operators in JavaScript, the "equality operator" (==) and the "strict equality operator" (===). The equality operator will attempt to convert operands that are different types so that it can compare them. For example,

      '10' == 10

      will evaluate to true, whereas

      '10' === 10

      will evaluate to false.

      The first part of the example uses the equality operator, which will perform an implicit conversion to compare two elements of differing types. In this case, we compared a string ('10') and a number (10), and after conversion they were found to be equivalents.

      The second part of the example uses the strict equality operator, which does not perform implicit conversion. The strict equality operator compares the values of the elements and their data types. In this situation, since the data types did not match (we compared a string and a number) they were found to not be equivalents.
      (14 votes)
  • hopper cool style avatar for user Lucky
    what are the { } indicating ? Is this part of the boolean expression? also when a { starts on the same row following a sequence, or when it starts on the next row
    {
    then a sequence
    }
    is this the pseudocode for true , false or boolean for if , else ? whats the difference if so?
    (1 vote)
    Default Khan Academy avatar avatar for user
    • starky ultimate style avatar for user KLaudano
      The curly braces { } indicate that whatever code inside of them is grouped together. For example, suppose we have the following code.

      if (x < 10)
      {
      println("Less than 10");
      println(x);
      }
      else
      {
      println("Greater than 10");
      println(x);
      }


      The braces after the if statement group the two println calls together. So, both "Less than 10" and the value of x are printed to the screen if x < 10. Similarly, both "Greater than 10" and the value of x are printed if x >= 10 because they are grouped within braces in the else statement.
      (1 vote)
  • blobby green style avatar for user PrasharJaagat1
    Hey!

    Shouldn't the password checker logic in pseudocode be as follows?

    IF (password = "TOPSECRET")
    {
    DISPLAY("You got it!")
    }
    ELSE
    {
    DISPLAY("Try again!")
    }
    (0 votes)
    Default Khan Academy avatar avatar for user
  • cacteye purple style avatar for user kkcool1220
    Isn't it suppose to be

    IF, AND, OR,

    NOT

    IF, ELSE
    (0 votes)
    Default Khan Academy avatar avatar for user
  • leaf red style avatar for user Gamar
    Aren't the strict and regular inequality examples in the operator table are wrong here?
    (0 votes)
    Default Khan Academy avatar avatar for user
  • blobby green style avatar for user D M
    If I copy the code that is in khan academy and paste it into visual code, it doesn't work. Could you tell me why please ?
    (0 votes)
    Default Khan Academy avatar avatar for user
    • leaf green style avatar for user Shane McGookey
      The code above is represented in a pseudocode format, so it does not translate directly over to JavaScript. You will need to make slight modifications to the code to run it using VSCode (e.g. change println() statements to console.log() statements).

      Also, the execution of JavaScript relies on an interpreter in the browser reading and interpreting each line of the code. Therefore, it is a tad difficult to run JavaScript directly in VSCode. You will need a JavaScript runtime environment (i.e. Node.js) that, once installed, will allow you to run JavaScript programs through VSCode by running node <program_name.js> in VSCode's built-in terminal.
      (1 vote)
  • blobby green style avatar for user Jon Loh
    How do nested if statements work?
    (0 votes)
    Default Khan Academy avatar avatar for user
    • leaf red style avatar for user Cavan P
      The computer reads each one like it did the last. If the outer condition is true, then the code inside the if statement is run. If the condition for the inner statement is true, then the code inside that if statement is run. If it's false, it runs the remaining code inside the outer if statement. If the outer condition is false, then the inner one will never be reached, as the computer skips over it.
      (0 votes)
  • blobby green style avatar for user suv
    i dont the inequality button so what to do?
    (0 votes)
    Default Khan Academy avatar avatar for user
    • leaf green style avatar for user Shane McGookey
      The inequality operator is two separate characters, an exclamation point (!) and an equals sign (=). Type the two characters individually, one after another to yield !=.

      If you do not have access to these characters, you might need to change your keyboard configuration (however since you composed your question with characters from the alphabet for Modern English and a question mark, your current configuration should be okay).

      If you exhaust all other options, then you can highlight the inequality operator used in the article and copy & paste it as necessary - this approach is inefficient, so see if the approaches above work first.
      (0 votes)
  • blobby green style avatar for user siddickpeerbocus
    (environmental policy)and(environmental AND policy)will retrieve what kind of results?
    (0 votes)
    Default Khan Academy avatar avatar for user
  • blobby green style avatar for user lauravala0927
    Hello, how can you use the output of the first try if statement to then is used to make the second if statement true?

    if (clb1 == 68) { // yellow
    clb1 = (231);
    clb2 = (114);
    clb3 = (42);
    }
    if (cbl1 == 231) { // light blue
    clb1 = 70;
    clb2 = 60;
    clb3 = 121;
    }
    if (cbl1 == 231){ // yellow
    clb1 = 68;
    clb2 = 60;
    clb3 = 117;
    }
    }
    (0 votes)
    Default Khan Academy avatar avatar for user