Conditional Statements (if, if else and else if)…30daysofjavascript => Day 3
Conditional statements in JavaScript is a control behaviour that determines whether a block of code should run or not. Let us move away from tech terms a bit and site an example. For instance, I want to buy food from restaurant ‘A’ also, I want an African dish, which means that my order is more specific but what happens if the said restaurant does not have what I want? Do I sit and just wait there? Do I go to the next restaurant? Do I go home? Or do I even order something entirely different? These actions are based on conditions of the first restaurant not having an African dish. That brings us to the types of conditionals in JavaScript.
- The ‘If’ statement: This statement specifies a block of code to be executed if a specified condition is true. E.g. If restaurant ‘A’ has an African dish, buy two plates of the first one on the menu.
- The ‘Else’ statement: This statement specifies the execution for a block of code if the same condition is false. E.g. If restaurant ‘A’ does not have an African dish, buy mac and cheese.
- The ‘Else If’ statement: This statement specifies a new test if the first condition is false.
- The ‘switch’ statement: This is used to specify many alternative blocks of code to be executed. An example of this would be seen in a code snippet.
Operations used in Conditional Statements

Operations goes beyond the use of +, -, *, / and %. Operations in conditional statements is used to test if a condition is true or false, for example, 2 == 2 is true but 22 == 33 is false.


You can use multiple if-else conditionals, but note that only the first else if block runs. JavaScript skips any remaining conditionals after it runs the first one that passes. Read more on conditionals here or here.
Tips
- The assignment operator (
=
) assigns a value to a variable. - If you add a number and a string, the result will be a string!
Bonus — About Ternary Operator
Ternary Operator is the only operator that takes three operands. In general, it has the syntax as shown below :
Condition ? expression_1 : expression_2
The condition is the expression that evaluates boolean values, if the condition is true it executes expression_1 else it goes on to execute expression_2. Ternary operators are very useful when writing if-else statements as you get to write fewer codes for the same effect.