Introduction to JavaScript Spring 2011 Class 4
Back to Introduction to JavaScript Spring 2011
Contents
Conditionals Continued: Switch Statement
Nesting a lot of if statements gets pretty ugly. Often you can avoid nesting with by using a switch statement instead.
switch (userInput){ case "a": console.log("apple"); break; case "b": console.log("bats!"); case "c": console.log("cougar"); case "d": console.log("drats!"); break; default: console.log("nothin' to see here"); }
Functions
Our simplest function defines a block of code (contained in {braces}) that we want to use over and over again.
var chickens = 38; var livers = 43; function addEmUp1() { var mySum = chickens + livers; console.log("chickens + livers = " + mySum); } addEmUp1();
The problem with that example is that the variables are hardcoded. What if I wanted to add up something other than chickens and livers?
function addEmUp2(myVar1, myVar2){ var mySum = myVar1 + myVar2; console.log("chickens + livers = " + mySum); }
That example is better, but what if I wanted to do something with the sum other than logging it to the console?
addEmUp2(chickens, livers); addEmUp2(4, 9328); function addEmUp3(myVar1, myVar2){ var mySum = myVar1 + myVar2; return mySum; } var myHolder = addEmUp3(chickens, livers); console.log(myHolder); console.log("I have " + addEmUp3(chickens, livers) + " livers");
Objects
declare a new object then assign properties
var myObject = new Object; myObject.myString = "I'm object 1'"; myObject.myNumber = 47; myObject.myBool = false; console.log(myObject); console.log(myObject.myString);
declare a new variable, and assign multiple properties to it, making it an object
var myObject2 = {myString: "I'm Object 2", myNumber: 47, myBool: false}; console.log(myObject2); console.log(myObject2.myString);
assign a method to an object that already exists
myObject2.sayString = function(){ console.log(this.myString); } myObject2.sayString();
declare a variable, and assign properties and a method to it
var myObject3 = {myString: "I'm object 3", sayString: function(){ console.log(this.myString + ", and my favorite number is " + this.myNumber); }, myNumber: 48}; myObject3.sayString();
Home Work
Proposal for Project #1
Make an html page linked from your portfolio that has at least one paragraph that explains what your website for project 1 will be. Project one should start as a simple html site that empathies quiality over quantity. Javascript will be added to enhance the website with out interfering any of the standard functionality. I will show examples in class week 5 & 6.