JS Odds & Ends

What we'll cover

  • Control Flow
  • Loops
  • Timers
  • Dates
  • Regular Expressions

Control Flow

if...else if ...else

  • only one of the blocks will execute, then it moves to the code below
  • checks expressions in order
  • braces optional if one line long
  • defensive check - to protect if a value that won't work with your code is passed
  • Don't Repeat Yourself in the blocks
  • THE EXPRESSIONS YOU PROVIDE MUST EVALUATE TO A TRUTHY/FALSY VALUE
  • BEWARE 0
if (<expression>) {
  do a...
} else if (<expression2>) {
  do b...
} else if (<expression3>) {
  do c...
} else {
  do d...
}

function doSomething(person) {
  if (!person) return; // <-- defensive check
  
  ...
  ....
}

if (<expression>) {
  do a...
} else if (<expression2>) {
  do b...
  do a...
} else if (<expression3>) {
  do c...
  do a...
} else {
  do d...
  do a...
}

switch statements

  • for concrete cases
  • you can use expressions that evaluate to something for the main expression to match against
  • default case
  • break; exits the switch
  • multi-case single-operation
  • chained operations (no break statement)
  • adding block scopes
  • reference
var mnemonicWord;

switch (<checked value>) {
   case <value>: //<-- case clause
     //...do something
     break;
   default:
     mnemonicWord = '';
}

switch (rainbowColor) {
   case 'red':
     mnemonicWord = 'Richard';
     break;
   case 'orange':
     mnemonicWord = 'of';
     break;
   default:
     mnemonicWord = '';
}

switch (<main) {
   case 'a':
   case 'b':
     ... ;
     break;
   default:
     mnemonicWord = '';
}

Loops

Old Loops

for loop

  • for iterating over things (when there's no better method)
  1. need a var (let is better) to keep track of where you're up to
  2. a condition to determine if the loop should run again
  3. instructions for what to do when each 'iteration' of the loop ends
for(){
// do something
}

//In the parenthesis we make 3 conditions
// - the initial starting conditions
// - the condition required to continue
// - what we do after every cycle of the loop

for(var i=0; //first part

for(var i=0; i < 10; //second part

for(var i=0; i < 10; i++){ //third part
    // do something
}

//maybe

var buttons = 
  document.getElementsByClassName('button');

for(var i=0; i < buttons.length; i+=1){
    console.log('text: ' 
      + button[i].innerText);
}

while loop

  • for when you don't know how many times the loop will have to run
  • while will only run if the condition is met
  • BEWARE RECURSION
var i = 0;

while (i < 3) {
  console.log('while', i);
  i+=1;
}

// OUTPUT

// 'while', 0
// 'while', 1
// 'while', 2

do...while loop

  • for when you don't know how many times the loop will have to run, but it should run at least once
  • do...while runs at least once
  • BEWARE RECURSION
var i = 0;

do {
  console.log('do...while', i);
} while (i > 0)

// OUTPUT

// 'do...while', 0

Picking between do and do...while

  • while is when you only want things to be done IF something is the case, and you don't know how many times these things will need to be done.
  • do...while is when you're attempting to change your environment and you want to perform actions until it has been changed sufficiently to meet your needs.

break and continue

  • break terminates the current loop or switch (or in es6 exits the current block <-- don't worry about this)
  • continue prevents any more code being run in this iteration
  • demo

New(ish) loops

for...in loop

  • for iterating over the properties of an object
    • needs hasOwnProperty check to avoid going through ALL the object's properties (demo)
var obj = {a: 1, b: 2, c: 3};
    
for (var prop in obj) {
  console.log('obj.' + prop 
     + ' = ' + obj[prop]);
}

// Output:
// "obj.a = 1"
// "obj.b = 2"
// "obj.c = 3"


// AVOIDING THE PROTOTYPE CHAIN

var triangle = {a: 1, b: 2, c: 3};

function ColoredTriangle() {
  this.color = 'red';
}

ColoredTriangle.prototype = triangle;

var obj = new ColoredTriangle();

for (var prop in obj) {
  if (obj.hasOwnProperty(prop)) {
    console.log('obj.' + prop 
     + ' = ' + obj[prop]);
  } 
}

// Output:
// "obj.color = red"

(for...of is ES6)

Timers

setTimeout

Used to wait a while and then do something

  • example might be that the user hasn't interacted for a while and you want to prompt them
  • Available globally
  • Needs 2 args:
    • callback
    • delay time (in ms) (so 3000 is 3 seconds)
  • Need to save the timer to be able to cancel it with clearTimeout
var timer = setTimeout(function(){
  console.log('BOO!');
}, 3000);

// ^ Waits 3 seconds then
// logs 'BOO!' to the console


// Clear using:
clearTimeout(timer);

setInterval

Used to do something every <x> timespan

  • example might be to redraw a clock with the new time
  • Available globally
  • Needs 2 args:
    • callback
    • delay time (in ms) (so 3000 is 3 seconds)
  • Need to save the timer to be able to cancel it with clearInterval
var seconds = 0;
var timer = setInterval(function(){
  seconds += 1;
}, 1000);

// 'timer' gives you id of the timer

document.getElementById('seconds')
  .innerText = seconds;

// ^ Updates the seconds display 
// on a page

// TO CLEAR
clearInterval(timer);

setInterval vs setTimeout

Date()

Regular Expressions

JS: Odds & Ends

By James Sherry

JS: Odds & Ends

Control Flow, Loops, Timers, Dates, Regular Expressions

  • 1,473