JavaScript Conditionals & Operators

Notes on what I learned from the JavaScript section of The Complete Web Developer in 2018: Zero to Mastery class on Udemy


Conditionals

Q: What are conditional expressions?
A: Conditional expressions perform different computations or actions depending on whether a specified Boolean condition evaluates to true or false.


Types of Conditionals

IF statement

var name = prompt(“What is your name?”);
    Creates a popup that asks the user “What is your name?” and gives them a place to input


if (name === “Kandis”) {
    alert(“Hi Kandis!”);
}
    If the user input “Kandis”, there’s another popup that says “Hi Kandis!” If any other input is made, nothing happens.


Else statement

var name = prompt(“What is your name?”);
    Creates a popup that asks the user “What is your name?” and gives them a place to input


if (name === “Kandis”) {
    alert(“Hi Kandis!”);
 } else {
    alert(“User unknown. Please try again.”);
}
    If the user input “Kandis”, there’s another popup that says “Hi Kandis!” If any other input is made, the popup says “User unknown. Please try again.”


Else If statement

var name = prompt(“What is your name?”);
    Creates a popup that asks the user “What is your name?” and gives them a place to input


if (name === “Kandis”) {
    alert(“Hi Kandis!”);
} else if (name === Susy”) {
    alert(“Hi Susy!”);
} else {
    alert(“User unknown. Please try again.”);
}
    If the user input “Kandis”, there’s another popup that says “Hi Kandis!” If the user input “Susy”, there’s another popup that says “Hi Susy!” If any other input is made, the popup says “User unknown. Please try again.”

Logical Operators

Q: What are logical operators?
A: Logical operators are programming-language symbols that denote a logical operation.


Types of Logical Operators

AND (&&)

if (firstName === “Jane” && lastName === “Smith”) {
    alert(“Hi Jane Smith!”);
}
    If firstName is Jane and lastName is Smith, a popup is created that says “Hi Jane Smith!” If any other input is made, nothing happens.


OR (||)

if (name === “Kandis” || name === “Sally”) {
    alert(“Hi Kandis or Sally!”);
}
     If name is Jane or name is Sally, a popup is created that says “Hi Kandis or Sally!” If any other input is made, nothing happens.


IF NOT (!) 

(returns true if an answer is not equal to something)

Input:
name = “Sally”
if (!(name === “Kandis”)) {
    alert(“Hi Kandis”);
}
    If (name is equal to Kandis) is NOT true, return “true”.


Output:
true

No comments