GDI logo

JavaScript for Beginners

Class 2

Review

In this code, spot the comments, variables, operator, function, argument, and return value.


function calculateTip(total) {
    var tipPercent = 0.15; //Can be changed
    return (total * tipPercent);
}

var billPreTip = 10;
var billTip   = calculateTip(billPreTip);
var receipt   = 'Meal: ' + billPreTip + ' Tip: ' + billTip + 
    ' Total: ' + (billPreTip + billTip);
console.log(receipt); 
				

Variable Scope

The scope of a variable is how long the computer will remember it.

Global Scope

A variable declared outside a function has a global scope and can be accessed anywhere, even in a function.


var awesomeGroup = 'Girl Develop It'; //Global scope
function whatIsAwesome() {
    console.log (awesomeGroup + ' is pretty awesome.'); //Will work
}
whatIsAwesome();

				

Local Scope

A variable declared within a function has a local scope and can only be accessed within that function.


function whatIsAwesome() {
    var awesomeGroup = 'Girl Develop It'; //Local scope
    console.log ('I made a variable called awesomeGroup with a value of ' + awesomeGroup); //Will work
}
whatIsAwesome();
console.log (awesomeGroup + ' is pretty awesome.'); //Won't work
				

Boolean Variables

Boolean variables represent the logical values True and False


var catsAreBest = true;
var dogsRule = false;
				

If you try to use another variable as a boolean, JavaScript will guess. The number 0, the empty string '', undefined, and null are considered false, everything else reads as true.

The if statement

Use if to decide which lines of code to execute, based on a condition.


if (condition) {
  // statements to execute
}
				

var bananas = 5;
if (bananas > 0) {
  console.log ('You have some bananas!');
}
				

Comparison Operators

Example Name Result
a == b Equal TRUE if a is equal to b (can be different types).
a === b Identical TRUE if a is equal to b, and the same type.
a != b Not equal TRUE if a is not equal to b (can be different types).
a !== b Not identical TRUE if a is not equal to b, or they are not the same type.
a < b Less than TRUE if a is strictly less than b.
a > b Greater than TRUE if a is strictly greater than b.
a <= b Less than or equal to TRUE if a is less than or equal to b.
a >= b Greater than or equal to TRUE if a is greater than or equal to b.

Watch out!

Don't mix up = and ==

Let's Develop It

Make a variable called "temperature." Write some code that tells you to put on a coat if it is below 50 degrees.

The if/else statement

Use else to provide an alternate set of instructions.


var age = 28;
if (age >= 16) {
    console.log ('Yay, you can drive!');
} else {
    console.log ('Sorry, but you have ' + (16 - age) + 
    ' years until you can drive.');
}
				

The if/else if/else statement

If you have multiple conditions, you can use else if.


var age = 20;
if (age >= 35) {
    console.log('You can vote AND hold any place in government!');
} else if (age >= 25) {
    console.log('You can vote AND run for the Senate!');
} else if (age >= 18) {
    console.log('You can vote!');
} else {
    console.log('You can\'t vote, but you can 
    still write your representatives.');
}
				

Let's Develop It

Modify your "wear a coat" code for these conditions:

  1. If it is less than 50 degrees, wear a coat.
  2. If it is less than 30 degrees, wear a coat and a hat.
  3. If it is less than 0 degrees, stay inside.
  4. Otherwise, wear whatever you want.

Logical Operators

Example Name Result
a && b And TRUE if both a and b are TRUE.
a || b Or TRUE if either a or b is TRUE.
! a Not TRUE if a is not TRUE.

Using logical operators

You can use these operators to combine conditions.


var bananas = 5;
if (bananas >=2 && bananas <7) {
    console.log ('You have a reasonable number of bananas');
} else {
    console.log ('Check your banana supply');
}
				

Let's Develop It

Add a logical operator to your what to wear program.

While loops

While will repeat the same code over and over until some condition is met.


var bottlesOfBeer = 99;
while (bottlesOfBeer >= 1) {
    console.log (bottlesOfBeer + ' bottles of beer on the wall');
    bottlesOfBeer = bottlesOfBeer - 9;
}
				

Infinite Loops

Make sure something changes in the loop, or your loop will go on forever...

For loops

For loops are very similar, but you declare a counter in the statement.


//will count 1 to 10
for (var i = 1; i <= 10; i++) {
    console.log (i); 
}
				

Loops and logic

You can add other statements or logical operators inside the loops.


//Count from 1 to 50
for (var i = 1; i <= 50; i++) {
    console.log (i);       
    //Says 'Buzz' after multiples of three
    if (i % 3 == 0) {
        console.log (' Buzz');
    }        
    //Says 'Bang' after multiples of five
    if (i % 5 == 0) {
        console.log (' Bang');
    }
}
				

Break

To exit a loop, use the break statement.


//Count from 100 to 200              
for (var i = 100; i <= 200; i++) {
    console.log('Testing ' + i);
    //Stop at the first multiple of 7
    if (i % 7 == 0) {
        console.log('Found it! ' + i);
        break;
    }
}
				

Let's Develop It

Write a loop that gives you the 9's times table,
from 9 x 1 = 9 to 9 x 12 = 108.

Finish early? Try using a loop inside a loop to write all the times tables, from 1 to 12.

Arrays

Arrays are ordered lists of values.


var arrayName = [element0, element1, ...];
				

You can put different types of data into an array.


var rainbowColors = ['Red', 'Orange', 'Yellow', 'Green', 
'Blue', 'Indigo', 'Violet'];
var lotteryNumbers = [33, 72, 64, 18, 17, 85];
var myFavoriteThings = ['Broccoli', 1024, 'Sherlock'];
				

Array Length

The length property tells you how many things are in an array


var rainbowColors = ['Red', 'Orange', 'Yellow', 'Green', 
'Blue', 'Indigo', 'Violet'];
console.log(rainbowColors.length);
				

Using Arrays

You can access items with "bracket notation" by using the position of the object you want. Programmers start counting at zero.


var rainbowColors = ['Red', 'Orange', 'Yellow', 'Green', 
'Blue', 'Indigo', 'Violet'];
var firstColor = rainbowColors[0];
var lastColor = rainbowColors[6];
				

Changing arrays

You can use bracket notation to change an item in an array


var myFavoriteThings = ['Broccoli', 1024, 'Sherlock'];
myFavoriteThings[0] = 'Asparagus';            
                

Expanding arrays

Arrays do not have a fixed length. You can use "push" to add something to an array.


var myFavoriteThings = ['Broccoli', 1024, 'Sherlock'];
myFavoriteThings.push('Dancing');              
                

Let's Develop It

Create an array of your favorite foods. Echo a few values onto your screen.

Iterating through arrays

Use a for loop to easily process each item in an array.


var rainbowColors = ['Red', 'Orange', 'Yellow', 'Green', 'Blue', 'Indigo', 'Violet'];
for (var i = 0; i < rainbowColors.length; i++) {
  console.log(rainbowColors[i]);
}              
                

Let's Develop It

Use a loop to make a list of all your favorite foods.

Resources