Introduction to JavaScript Fall 2010 Class 3

esse quam videri
Jump to: navigation, search

Back to Introduction to JavaScript Fall 2010

Introduction

This week we'll cover some more of the basics of JavaScript. I'll talk about using functions to organize your code. I'll also cover some of the other JavaScript types, including Objects and Arrays. Finally, I'll talk about JavaScript "control flow", and how you can write code that makes decisions as it runs.

Code Blocks

One concept that I haven't introduced yet is the idea of a code block. Code blocks are groups of code, much like paragraphs are groups of sentences. In JavaScript, code blocks are contained inside open and close curly brackets

  {
     var message = "hello";
     alert(message);
  }

Code blocks can be used by themselves, like the example above, but they are usually used in combination with the concepts that I will introduce today.

Functions

When you're writing code, it often helps to group chunks of code into reusable blocks. The blocks can be given a name so that they can be called later on. In JavaScript, functions give you the ability to create named blocks of code and then run those blocks of code later on.

Below is an example of a simple function declaration

  function alertUser() {
     alert("Hello user");
  }

The declaration creates a new function called alertUser. The code between the brackets will be executed every time you call the function like this

  alertUser();

Functions can also take in a list of parameters. The parameters are listed in between the parentheses. Below is an updated version of the alertUser function that takes in 2 parameters.

  function alertUser(firstName, lastName) {
      alert("Hello " + firstName + " " + lastName);
  }

alertUser now takes in parameters for the first name and last name of the user that should be alerted. When the built in alert function gets called it adds the first name and last name parameters to the phrase that should be sent to the screen. The new function can be called like this

  alertUser("Matt", "Ephraim");

When the function gets called, the message "Hello Matt Ephraim" will be sent to the screen.

Finally, functions can return one value when they complete

  function getUserMessage(firstName, lastName) {
      return "Hello " + firstName' + " " + lastName;
  }

This function returns a message that has been created for the user. You can use the value that is returned when you call the function

  var userMessage = getUserMessage("Matt", "Ephraim");

userMessage will be equal to the value that was returned by getUserMessage.

Comparison Operators

Comparison operators are special operators that you can use to compare 2 values. After the comparison is made, they will return a boolean. Remember from last week that booleans can only be set to true or false.

Below are some of the comparison operators you can use in JavaScript:

  • Equal To (===)

The equal to operator will compare two values and return true if they are equal to each other

  // returns true
  42 === 42
  
  // returns false
  42 === 1
  

Note: If you are familiar with JavaScript already or have used other languages, you may be wondering why I didn't use the double equals (==) operator instead. In most languages, this is the recommended operator. The problem with JavaScript is that the == operator will automatically convert one of the types being compared and return true if the converted value is equal to the other value. For example

  // returns true
  1 == "1"
  
  // returns false
  1 === "1"
  

In the example, the number 1 is compared to the string "1". The string "1" is automatically converted to a number and the number is compared to 1. Maybe that's what you wanted to happen in your code. Usually, though, it's not what you really wanted to happen, and sometimes your code may behave strangely as a result:

  // returns true
  0 == ""
  
  // returns false
  0 === ""

Always use the === as the equal to operator unless you have a really good reason not to.

  • Not Equal To (!==)

The not equal to operator is just like the equal to operator, but it returns true if the first value is not equal to the second value

 // returns true
 42 !== 1
 
 // returns false
 42 !== 42

Note: Just like the equal to opeator, make sure you use !== instead of !=, for the same reasons listed for the equal to operator.

  • Greater Than (>)

The greater than operator compares 2 values and returns true if the first one is greater than the second

  // returns true
  42 > 1
  
  // return false
  1 > 42
  • Less Than (<)

The less than operator works similar to the greater than operator, but it returns true if the first value is less than the second one

  // returns true
  1 < 1984
  
  // returns false
  1984 < 1
  • Greater Than or Equal To

The greater than or equal to operator is like the greater than operator, but it will return true if the first value is greater than or equal to the second

  // returns true
  42 >= 42
  
  // returns false
  42 >= 1984
  • Less Than or Equal To

The less than or equal to operator is like the less than operator, but it will retrun true if the first value is less than or equal to the second

  // returns true
  42 <= 42
  
  // returns false
  42 <= 1

Logical Operators

Sometimes, you may want to chain multiple comparisons together and get the results of all of those statements together. You can use the 2 logical operators to do this.

  • The And Operator (&&)

The and operator chains together multiple comparisons and returns true if all of the statements are true

  // returns true because both statement are true
  42 > 1 && 42 < 1984
  
  // return false because the first statement was false
  42 > 1984 && 42 < 1984
  • The Or Operator (||)

The or operator chains together multiple comparisons, but returns true if any one of the statements is true

  // returns true because the second statement is true
  "JavaScript" === "Java" || "JavaScript" !== "Java"
  
  // returns false because both statements are false
  "JavaScript" === "Java" || "JavaScript" === "C++"
  
  // returns true because one of the statements was true
  ("JavaScript" === "Java" || "JavaScript" === "C++" || "JavaScript" !== "C#")

Notice that in the last comparison, the statements were grouped by parentheses. You can group multiple statements together with parentheses.

  • The Not Operator (!)

The not operator (!) will take the result of the comparison or series of comparisons and return the opposite

 // result will be set to false, because the comparison returned true
 var result = !(42 < 1984);
 
 // result will be set to true because the two comparisons 
 var result = !("JavaScript" === "Java" || "JavaScript" === "C++");
 

You don't have to always use the not operator at the same time you're doing a comparison. You can use it at any time to get the opposite of a boolean

 // Sets result to true
 var result = 42 < 1984;
 
 // Sets opposite to false by getting the opposite of result
 var opposite = !result;

Control Flow

Often, you will want your code to make decisions while it's running. Under certain conditions you want the program to behave one way, but under other conditions you'll want it to behave another way. For example, last week, I used a function called bakeCookies as an example. The function would bake cookies if the number of cookies was less than 20. Otherwise, the function wouldn't do anything. You can use control flow to make a real function that behaves this way.

If Statements

The comparison operators that I introduced above, and the boolean values that they returns are pretty useless by themselves. However, they can come in handy when you want to control the flow of your program. The simplest way to control the flow of your program is with an if statement.

If statements control the flow of your program by checking some condition and then executing a block of code if the condition is true

 if (1 > 2) {
     alert("That's impossible!");
 }

The example above uses the greater than operator to check if 1 is greated than 2. The result of the statement 1 > 2 is the boolean false. If statements only execute if the condition is true, so the code block doesn't run.

Remember that you can negate or get the opposite of a boolean by using the exclamation point. So, the code below will actually run

  if (!(1 > 2)) {
      alert("Negating the statement");
  }

Else Statements

Else statements go hand in hand with if statements. You can an add an else statement after your if statement and the code block that goes with the else statement will run only if the code block for the if statement didn't run

  // The code for the if statement will never run.
  // Instead, the code for the else statement will run
  if (1 > 2) {
      alert("That's impossible!");
  }
  else {
      alert("1 is never going to be greated than 2!");
  }

You can write if statements without else an statement, but else statements always require an if statement.

Else If Statements

Sometimes, you might want to chain multiple if statements together and check several different conditions. If you only want one if statement to get checked if another fails, you can use the chain if statements with else statements to create a series of conditions to check

  // Pretend you have a program that has to translate the language
  // based on country the user is from
  
  // The country is USA, so only the first if statement will execute
  var country = "USA";
  if (country === "USA") {
      alert("the language is English");
  }
  else if (country === "Spain") {
      alert("the language is Spanish");
  }
  else if (country === "Germany") {
      alert("the language is German");
  }
  else {
      alert("I don't have a language for your country");
  }

In the example above, there is a variable for the user's country. The series of if and if else statements checks the value of country for several different countries. As soon as it finds a condition that returns true it will run the code that matches and ignore the other statements. If it never finds a statement that's true, it will run the code in the last else statement.

Using Control Flow

If and else statments can be used to update the bakeCookies function so that it will check that the maximum number of cookies that can be baked isn't exceeded.

First let's look at what the example function declaration from last week looks like

  // Use makeCookies to bake a custom
  // amount of cookies. The maximum
  // number of cookies is 20.
  // Our cookie sheet becomes
  // overloaded after 20 cookies.
  function bakeCookies(numberOfCookies) {
     
  }

The function is called bakeCookies and it takes in one parameter numberOfCookies.

The comment says that the oven can only handle 20 cookies. So, let's create a variable that holds the maximum number of cookies

  // Use makeCookies to bake a custom
  // amount of cookies. The maximum
  // number of cookies is 20.
  // Our cookie sheet becomes
  // overloaded after 20 cookies.
  function bakeCookies(numberOfCookies) {
     var MAX_COOKIES = 20;
  }

Now the function needs some way of checking that the number of cookies doesn't exceed the maxmimum allowed. An if statement can be used to limit the number of cookies that get baked

  // Use makeCookies to bake a custom
  // amount of cookies. The maximum
  // number of cookies is 20.
  // Our cookie sheet becomes
  // overloaded after 20 cookies.
  function bakeCookies(numberOfCookies) {
     var MAX_COOKIES = 20;
     if (numberOfCookies <= MAX_COOKIES) {
         // bake the cookies
     }
  }

The function checks that numberOfCookies doesn't exceed MAX_COOKIES by using the less than or equal to operator to compare numberOfCookies to MAX_COOKIES. If the statement is false, the code won't run.

Loops

In addition to checking if a block of code should be run, JavaScript also allows you to execute a block of code repeatedly while certain conditions are met.

While Loops

While loops take in a boolean and continually execute the block of code while the boolean value is true. Once the boolean changes to false, the loop stops running

  var count = 0;
  while(count < 10) {
      alert(count);
      count = count + 1;
  }

In the example above, a variable called count is created and set to 0; The while loop checks that the value of count is less than 10, and if it is, it executes the code. If the value is equal to 10 or more, the loop will stop running.

Notice that the last line of the loop increments the value of count by 1. If the code block didn't add 1 to count, the count would always be less than 10, which would mean that the loop would run forever.

Note: the while loop could have also be written like this:

  var count = 0;
  while(count < 10) {
      alert(count);
      count++;
  }

The only difference being that count = count + 1 has been replaced by count++. The ++ operator automatically takes the variable adds 1 to it. It's a nice shortcut that gets used quite often.

For Loops

For loops are similar to while loops. They will check for a condition and run a block of code if the condition is true. For loops also let you set up an initial variable and then let you make changes to that variable each time the code block runs

   for(var count = 0; count < 10; count++) {
       alert(count);
   }

The beginning of a for loop is broken up into 3 parts that are separated by semicolons. In the first part, you create a variable that will be used in the loop. In this case, the variable count is created:

  for(var count = 0; count < 10; count++)

The next part of the for loop is condition that is required to be true to keep the loop running:

 for(var count = 0; count < 10; count++)

And finally, the last part of the for loop statement modifies the variable each time the loop runs. In this case, the variable is being incremented by 1 using the ++ operator:

 for(var count = 0; count < 10; count++)

Today's Interesting JavaScript Site

Microsoft's Beauty of the Web / IE9 Showcase

Microsoft promises that Internet Explorer 9 will be more standards compliant and will support many of the exciting features coming with HTML5. This is their site to show off what the current beta of IE9 is capable of.

Activities

Activity 1

Use the instructions from last week to create a new HTML page and a JavaScript file to go with the new page.

In your JavaScript file create a function called writeName.

The function should take 2 parameters: firstName and lastName.

The function should use Firebug's console.log function to write out the first name and the last name.

Activity 2

Use the Firebug console to try out the comparison operators above.

Activity 3

Modify the bakeCookies function below to complete the activies

  // Use makeCookies to bake a custom
  // amount of cookies. The maximum
  // number of cookies is 20.
  // Our cookie sheet becomes
  // overloaded after 20 cookies.
  function bakeCookies(numberOfCookies) {
     var MAX_COOKIES = 20;
     if (numberOfCookies <= MAX_COOKIES) {
         // bake the cookies
     }
  }
  
  // Call the function
  bakeCookies(2);

Right now the bakeCookies function will bake the cookies as long as the number of cookies is below 20. If the number of cookies is above 20, the function won't do anything.

Modify the function so that if will continue to behave like it does above, but will also alert the user with an error message if the number of cookies is above 20.

Activity 4

Use a loop to bake each cookie. If the number of cookies is below the maximum, start with 0 (in programming, loops generally start with 0), and run a loop that will write a message that says "Cookie # baked." for each cookie baked. You can use the console.log function built into Firebug to write the messages, rather than the alert() function.

Example output for bakeCookies(2)

  Cookie 0 baked.
  Cookie 1 baked.