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

If Statements Syntax

if (val > 10) {
// Value is greater than 10
}
else if (val < 5) {
// Value is smaller than 5
}
else {
// Value is between 5 and 10
}

Check to see if a variable is an array using .isArray()

var activities = ["Yoga", "Working", "Sports", "Reading"];
var car = "Ford";
if (Array.isArray(activities)) {
    console.log(activities + " Is an array!");
}
if (Array.isArray(car) != true) {
    console.log(car + " Is not an array!");
}

 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.

Switch Statements - Lets you know what day it is.

var day;
switch (new Date().getDay()) {
  case 0:
    day = "Sunday";
    break;
  case 1:
    day = "Monday";
    break;
  case 2:
     day = "Tuesday";
    break;
  case 3:
    day = "Wednesday";
    break;
  case 4:
    day = "Thursday";
    break;
  case 5:
    day = "Friday";
    break;
  default:
    day = "Saturday";
}
console.log("Today is " + day);
document.write("Today is " + day);

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.

String Variables In Javascript

(condition) ? 'If true' : 'If False';

String Variables In Javascript

// Ternary Operator: If > .5 multiply by 1 if not -1
// Randomizes direction of velocity
vel = 100 * (Math.random() > .5 ? 1: -1);

Facebook Video