Press key to advance. Zoom in/out: Ctrl or Command + +/-.

Basic JavaScript

Conditionals & Loops

Estelle Weyl

Conditional Statements

if/then

if (condition is true) {
    // then do this ....
}
if(2 + 2 == 4) {
    console.log("You are a mathmatician!");
}
if(prompt("Your name?") != "Estelle"){
    console.log("You are an imposter!");
}

Back to Booleans

true
false
var truthy = true,
    falsey = false;

Falsey

Everything value can return a Boolean Value.

False

false
undefined
null
0 (-0)
""
NaN

Everything else is truthy

Truthy

Everything that is not falsy is truthy

Truthy

true
42
0.000001
"Estelle"

Objects, arrays, functions & regular expressions

function foo(){}
[1,2,3]
[]
{firstName: "Estelle", age: 29, isAwesome: true}
{}
/\w{6,9}/

Comparison Operators

OperatorDefinition
==Equal to
===Equal to & same type
!=Not Equal to
!==Not Equal to / not same type
>Greater than
>=Greater or equal to
<Less than
<=Less or equal to
!Not
&&AND
||OR

Comparison Operators

Does foo exist? Is it truthy?

if(foo) { } 

true or false?

if(x > y) { } 

Is x truthy? If not, is y truthy?

if(x || y) { } 

are x and y BOTH truthy

if(x && y) { } 

Comparison Operators

Strict Equality Operator: ===

console.log(5 ==  "5");
console.log(5 === "5") 
console.log(5 !=  "5");
console.log(5 !== "5") 

When you're looking for a truthy or falsy value, pass the value into your if statement, negating with ! if necessary. When you're looking specifically for true or false, use === or !==.

Use == or != only when you NEED what it does, like to compare null and undefined.

What happens with differing types?

The Abstract Equality Comparison Algorithm, or "How does the == operator work? Given x == y"

Type(x)          Type(y)          Result
If x & y are the same typef follow === operator rules
Null             Undefined        true
Undefined        Null             true
Number           String           x == toNumber(y)
String           Number           toNumber(y) == x
Boolean          (any)            toNumber(x) == y
(any)            Boolean          x == toNumber(y)
String or Number Object           x == toPrimitive(y)
Object           String or Number toPrimitive(x) == y
Otherwise...                      false

Conditional Examples

if(5 > 4)
if("Clinton" > "Bush")
if(5 == '5')
if(5 === '5')
if(0 < x && x < 10)
if(!firstName)
if(heroes.length === 1)
if(isNaN('fruitcake'))

Comparing Case Insensitive Strings

If a data entry point is not case sensitive (like username rather than password), realize that your user's capitalization may not match what you have stored:

var firstName = prompt('First Name?');
  if(firstName.toUpperCase() === 'ESTELLE') {
    alert(firstName);
  }
var errMsg,
     email1 = prompt('Your email address:');
     email2 = prompt('Re-enter email address:');

  if(email1.toLowerCase() !== email2.toLowerCase()) {
  	errMsg += "Email addresses do not match\n";
  }

Comparing Numbers

var age = parseInt(prompt('Lie about your age?'));

if(isNaN(age)) {
  // not a number!! 
  errMsg += "At least make it a number so it's plausible, silly"
} 

Otherwise ...

if ... else if .... else

var msg,
    age = +prompt("how old are you?");
    
if(!age || isNaN(age)) {
  msg = "You're too old to tell us your age?";
} else if (age <= 18 || age >= 65) {
  msg = "Kudos to you for getting mad skillz";
} else if (age > 45) {
  msg = "You should have lied about your age.";
} else if (age < 25) {
  msg = "You're too young to rent a car,\
  but old enough to rock JS";
} else {
  msg = "There's nothing wrong with being average.";
}

While Loops

while (condition) {
    statements;      
}
while (condition is true) {
    // do these things
    // alter the condition       
}
var count = 0, 
    iterations = 4;
while (count < iterations) {
    // do these things
    counter++;
}

For loop

Declared in one line

for (initialization; condition; increment) {
    statement;
}
for(count = 0; count < iterations; count++) {
    // do these things
}
var pets, i;

pets = ['Spazzo', 'Poopers', 'Sassafrass'];
for (i = 0; i < pets.length; i++){
    console.log('Pet ' + (i + 1) + ": " + pets[i]);
}

Iterate even if condition is never met

do while

var num;
do {
    num = window.prompt('Number?');
    console.log('Guess? ' + num)
} while (num !== '5')

Will execute code block at least once, even if condition is never met.

Don't forget to increment your counter or your browser will crash

infinite loop

Exercises

  • Is your user old enough to vote? Drink? Rent a car? Run for president? Retire?
  • Multiplication Table: pick a number? How many multiplication values do you want?
    Example input: 9, 3.
    Example output: 9 x 1 = 9, 9 x 2 = 18, 9 x 3 = 27
  • If you used the while loop for the above, do it with the for loop. If you used the for loop, rewrite it as a while loop.
  • Have the user guess your number. Tell them they're warm if close or cold if far off.

Next

Go