Lessons 162 & 163 – Complete 2020 Web Development Bootcamp

Lesson 162 – How to use Switch Statements in Javascript

A switch statement will take the code down a different tract depending on the value of the variable.

This is the code which uses a switch statement to play a sound depending on which image on the screen is clicked.

var numberOfDrumButtons = document.getElementsByClassName("drum").length;

for (var i = 0; i < numberOfDrumButtons; i++) {
  document.getElementsByClassName("drum")[i].addEventListener("click", 
  function () {

	var buttonInnerHTML = this.innerHTML;

	switch (buttonInnerHTML) {
		case "w":
		  var kickBass = new Audio("sounds/kick-bass.mp3");
		  kickBass.play();
		break;

		case "a":
		  var snare = new Audio("sounds/snare.mp3");
		  snare.play();
	        break;
		case "s":
		  var tom1 = new Audio("sounds/tom-1.mp3");
		  tom1.play();
		break;
		case "d":
		  var tom2 = new Audio("sounds/tom-2.mp3");
		  tom2.play();
		break;
		case "j":
		  var tom3 = new Audio("sounds/tom-3.mp3");
		  tom3.play();
	        break;
		case "k":
		  var tom4 = new Audio("sounds/tom-4.mp3");
		  tom4.play();
		break;
		case "l":
		  var crash = new Audio("sounds/crash.mp3");
		  crash.play();
		break;

		default: console.log(buttonInnerHTML);

		}

	});
}

Lesson 163 – Objects, their Methods and the Dot Notation

A method is a function that is associated with an object.

When using properties or calling a method you always use the dot notation. For example –

bellBoy1.moveSuitcase();

You can incorporate a method into a constructor function like this –

var BellBoy (name, age, hasWorkPermit, languages) {
  this.name = name;
  this.age = age;
  this.hasWorkPermit = hasWorkPermit;
  this.languages = languages;
  this.moveSuitcase = function() {
    alert("May I take your suitcase?");
    pickUpSuitcase();
    move();
 }
}