Javascript Activity

Welcome to the Javascript activity page! Here you will learn step-by-step how to code in Javascript!

Look for the text in bold for basic instructions and information; the regular text will give more details if you need them.

1 Getting Started

  1. Let's get started! So to write your own Javascript, you don't need anything more than just a simple text editor. During these lessons, we are going to use Firefox Thimble, because it provides a nice way to work with Javascript as you make changes to it, however everything can as well be done in a simple text editor off-line.
  2. Now, let's have a look at Javascript code! Log in to Firefox Thimble and open the provided sample website. You should see something like this:
  3. An image showing Firefox Thimble screen

2 Input and Output

  1. To start programming in Javascript you need to tell the browser the location of the Javascript. To do that put the <script> tag code right before the </body> tag:

    <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
    <script>
    </script>
  2. Type console.log("Hello World!") between the tags <script></script>.
    1. console.log("") tells Javascript what it is supposed to do (in this case, print something to the log something out to the screen).
    2. "Hello World!" tells Javascript what is supposed to be printed to screen.
  3. Type var x = prompt('What is your name?') underneath console.log("Hello World!").
    1. prompt() asks the user to type something by displaying a message. The message displayed is whatever is inside the parentheses.
    2. The result of whatever the user types in will be stored in the variable x.
  4. Type console.log("Your name is " + x).
  5. Try modifying these commands to ask the user for their name, age, and birthday. After you get this information, print out "Hi <name>, you are <age> years old and your birthday is <birthday>".

3 Variables

  1. Variables are nothing but space in the computer’s memory to store values. You can give it a name and use that name to refer to the value stored in that space. The name can only contain letters, numbers and underscore.
    1. In the previous section, we executed var x = prompt('What is your name?') to store the user's name into xx is an example of a variable.
  2. A variable name and can have many characters, but can only contain letters, numbers and underscore.
  3. To create a variable, we write the word var and unique variable name and assign it a value using the = sign.
    1. For example var num = 1 means that we have made a variable called num and assigned it a value of 1.
    2. Variables can store decimal values too. var myfloat = 7.2.
    3. To store text (or strings), use single or double quotes. For example, var str_hw = "Hello World!" or var mystring = 'hello'.
    1. Now lets use multiple variables at the same time. To do this we will use math operators (or symbols) like +,-,*, and /. The goal will be to take two numbers and add them to gether.
      1. Type var x = 1 under the Javascript from the previous section.
      2. Now write console.log(x). You see that the console at the bottom of the screen prints 1.
      3. Now make another variable var y = 2.
      4. Using math operators we can add the two variables together. Type var z = x + y, and output the results with console.log(z)
  4. Once you create a variable you change the value with the = sign. For example what does the following lines of code display?
      var i = 1
      console.log(i)
      i = 2
      console.log(i)
  5. Challange section

  6. Create a variable and assign it the value of your favourite number. Then print the number to console or the webpage.
  7. Prompt (using prompt("") and ask for the favourite color. Create a variable and assign it to be the prompted favourite color. Then print the number to console or the webpage.
  8. Now on your own create variables and solve the following math problems and output the result with console.log(). Try using as few lines as possible while only using 5 and 10 one time.
    1. 5+10
    2. 15*5
    3. 75/10

4 If Statements

  1. If statements are used to test variable values. Paste in the following lines of Javascript and run it. What happens when you put in spam as your favourite food? What happens when you put in another food?
    var food = prompt("What is your favourite food?")
    if (food == "spam"){
      console.log("Ummmm, my favourite!")
    }
  2. If-else statements are an extended form of if statements. The else statement tells Javascript what should happen if the if-statement is not true.
  3.   var food = prompt('What is your favourite food?')
      if (food == "spam"){
        console.log("Ummmm, my favourite!")
        console.log("But not spam EMAIL.")
      }
      else{
        console.log("No, I won't have it. I want spam!")
      }
  4. Ask user for their name and age. Display "Hi <name>, you can drive!" if their age is more than 16, otherwise display, "Hi <name>, you still have <x> years to go", where x is the difference between their age and 16.

5 For Loops

  1. For loops are used when you want instructions to run a certain number of times. For example, if I wanted to print the number 1 through 10, I would run a for loop 10 times printing the number each time.
  2. for(var i = 1; i <= 10; i++){
      console.log(i)
    }
  3. Let's unpack for(var i = 1; i <= 10; i++) now.
    1. var i = 1 creates a variable i that has the value 1.
    2. i<=10 makes the loop keep happening until i equals 10.
    3. i++ adds 1 to i at the end of the for loop which marked by the curly brace }. To decrease the number by one
  4. Now find the value of 10! (the ! means factorial). To do factorial you multiply all the numbers 1 through 10 together. Extra credit print only the resulting value not any numbers in between.
  5. Now find the value of 4! * 5!

6 Lists

  1. The list is a most versatile data type available in Javascript. It can be written as a list of comma-separated values (items) between square brackets. Items in a list do not have to be of the same type.
  2. You can create a list like this:
    var list1 = ['physics', 'chemistry', 1997, 2000]
    var list2 = [1, 2, 3, 4, 5]
    var list3 = ["a", "b", "c", "d"]
  3. We can access specific elements of a list using their position number (called index). What does this return?
    console.log(list3[3])
  4. Lists count positions from 0, so to display the first element, you can use console.log(list3[0]), and to print the last element, console.log(list3[3]).
  5. You can use for loops to go through all the elements of the list one by one.
        for(var i = 0; i < list1.length; i++){
          console.log(list1[i])
        } 

    Here, the variable list1.length is the length of the list. You can use it to find the length of strings too.
  6. Take the following list and write a program that prints out all the elements of the list.
    a = [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
  7. You can combine a for loop and an if statement to do more interesting things. This time we will loop through the list in reverse order, starting from 5 going to 1. To do that we decrease i-- at the end of the for loop statement.
    1.     var list = [1, 2, 3, 4, 5]
          for(var i = list.length; i >= 0; i--){
            if(i < 3){
              console.log("we found " + list[i])
            }
          }
    2. What happens when then value of i is less than 5?
  8. Now it is your turn take the following list and write a program that prints out all the elements of the list that are less than 20.
    a = [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]

7 Functions

  1. Functions in Javascript are a re-usable collection of statements.
  2. Copy the following function to your website and put it within the <script></script>:
    function sayHello(){
      console.log("hello")
    }
    1. In Javascript all functions start with the word function
    2. Next comes the name, which has the same rules as variable names
    3. Then you use parentheses()
    4. Last is curly brackets you put all the statements you want for your function in curly brackets {console.log("hello")}
  3. Now that you have a re-usable function you can write sayHello() anywhere and you will print "hello" where ever you use the function.
  4. What do you think will happen when you add the following code:
    for(var i = 1; i<=5; i++){
      sayHello()
    }
  5. Functions in Javascript can use variables, which are called arguments. You put the arguments in the parentheses. For example:
    function sayWord(word){
      console.log("this is a word " + word)
    }
    var wordToSay = "hello"
    sayWord(wordToSay)
    1. This function will take the argument word and print it to console.
  6. Now you try to create a function that has an argument number and will print number.
  7. There can be any number of arguments, they must be separated by commas. For example:
    function addNumbers(num1, num2){
    var added = num1 + num2
      console.log(added)
    }
    var number1 = 2
    var number2 = 5
    var number3 = 1
    addNumbers(number1, number2)
    addNumbers(number1, number3)
    1. This function will take two arguments add them and print to console.
  8. Now it is your turn write a function named calculateDogAge that:
    1. takes 1 argument: your puppy's age.
    2. calculates your dog's age based on the conversion rate of 1 human year to 7 dog years.
    3. outputs the result to the screen like so: "Your doggie is NN years old in dog years!"
  9. Call the function three times with different sets of values.
  10. Bonus: Add an additional argument to the function that takes the conversion rate of human to dog years.

Challenge Activities

Level 1

  1. Given a string of even length, return the first half. The string "WooHoo" yields "Woo".
  2. Print out the list a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] in reverse order.
  3. Here's a list of the total volumes of similar objects (all weigh 250 kg) that are only half immersed into the water: [0.04, 0.2, 1.2, 1.6, 0.032, 3, 9, 0.27, 0.3]. How many of these would float and how many of these would sink?

Level 2

  1. Given 3 int values, a b c, return their sum. However, if one of the values is 13 then it does not count towards the sum and values to its right do not count. For example, if b is 13, then both b and c do not count.

    Example:
    [1, 2, 3]  returns 6
    [1, 2, 13] returns 3
    [1, 13, 3] returns 1
  2. Given a list of numbers, e.g., c = [4, 1, 33, 5, 2, 10], return the difference between the largest and smallest values in the list.

    Hint: There are 2 useful built in functions, min(x1, x2) and max(x1, x2) that return the smallest and largest of the 2 numbers x1 and x2.
  3. Return the number of times that the string "code" occurs in s = "cozexxcopecode", where any letter is accepted in the place of the "d".

    Example: "aaacodebbb" returns 1, and "cozexxcope" returns 2.

More information

Comparisons

Operator Description Example
== If the values of two operands are equal, then the condition becomes true. a == b
!= If values of two operands are not equal, then condition becomes true. a != b
> If the value of left operand is greater than the value of right operand, then condition becomes true. a > b
< If the value of left operand is less than the value of right operand, then condition becomes true. a < b
>= If the value of left operand is greater than or equal to the value of right operand, then condition becomes true. a >= b
<= If the value of left operand is less than or equal to the value of right operand, then condition becomes true. a <= b

References