JavaScript Conditional Logic

Javascript Conditional Logic

JavaScript Conditional Logic - If Statements

If statements are used to make decisions in code. If this happens then do this. If not, do this instead. The order matters once the first condition is met it does not check any other conditions.

Use the else if statement to specify a new condition if the first condition is false. Use the else statement to specify a block of code to be executed if all other conditions are false

 Comparison Operators

== Equal operator

= assigns
== compares 

=== Strict equal operator  

There is no variable type conversion.
Meaning a string does not equal an integer.
3 === 3   True
3 === ‘3’  False

!= NOT equal !== Strict NOT equal
> Greater than < Less than
>= Greater than or equal to <= Less than or equal to
&& AND operator

If (val <= 50 && val >=25) {
// Both these must be true
}

|| OR operator

If (val < 50 || val >20) {
// if val is 49 - 21
}

JavaScript Switch Statements

The switch statement allows you to perform different actions based on different conditions. It then runs a block of code based off of those conditions.

The default keyword specifies the code that will run if there is no match.

The Break Keyword stops the execution inside the switch block. Used to jump outside of the switch statement and not make any further checks. The last condition doesn’t need a break as that happens automatically.

Ternary Operator

The Ternary Operator ? Is a shortcut for If/Else Statements. Allows you to shorten the condition into one line. It will assign a value to a variable based on some condition. The downside is it can make the code harder to read.

Facebook Video