JavaScript for Beginners

Class 1

Download class files

Table of contents

Welcome!

Philly Tech Sistas is here to provide affordable and accessible programs to learn software through mentorship and hands-on instruction.

Some "rules"

  • We are here for you!
  • Every question is important.
  • Help each other.
  • Have fun.

Welcome!

Tell us about yourself.

  • Who are you?
  • What do you hope to get out of the class?
  • What do you like about summer?

What is JavaScript?

  • JavaScript interfaces with HTML and CSS.
  • JavaScript lets you build dynamic webpages that respond to input from users.

JavaScript is a client-side language

JavaScript is a client-side processing language. A browser reads the code and runs it directly.

Laptop and server connected via the internet

Photo credits: Andrew E. Larson and John Seb Barber cc

What is JavaScript?

Let's Develop It

Let's write your first JavaScript program. Open your js101-downloads folder and find the practice.html file. Place this code inside, before the closing body tag:

<script>
    alert('Hello World!');
</script>

Open practice.html in a web browser to see your code in action.

Script Tags

You can mix JavaScript and HTML. The script tag tells your browser the stuff inside is JavaScript, not HTML.

<script>
    CODE GOES HERE
</script>

JavaScript Files

Just like with CSS, you can keep your JavaScript separate in its own file, and load it from your HTML file.

<script src="path/to/file.js"></script>

JavaScript statements

After each individual statement, you must add a semicolon.

<script>
    console.log('Hello World!');
    console.log('I am glad to meet you');
    console.log('I am fuzzy');
</script>

Comments

You can leave comments in your code—notes that people can read and computers will ignore.

<script>
    /*I can wrap long comments 
    with multiple lines 
    like this*/
    console.log('Hello World!'); //Or mark short comments like this
</script>

Tip: You can select text or a line in Sublime Text and comment it out easily with the keyboard:

  • Control + / (Windows)
  • Command(⌘) + / (Mac)

Getting results onto your screen

Open a popup box.

alert('Hello World!');

Display a message in your console.

console.log('Hello World!');

Add something to the page.

document.write('Hello World!');
document.getElementById('headline').innerHTML = 'Hello World!';

Let's Develop It

  • Open practice.html. Add a comment to the code.
  • Try different ways of printing your message.
  • Create a new file called mycode.js. Move your JavaScript code to this file and link it to your page.
  • Hint: remove any <script> open and close tags from your new JavaScript file, since these are HTML tags and only work in .html files.

Variables

  • A variable is a place to store values.
  • The value of a variable can change over time.

Variable Values

When you first create a variable, it can be undefined (it has no value) or you can give it a value.

var numberOfKittens; // undefined
var numberOfKittens = 5; // value is the number 5
                

Declaring a Variable

To declare (create) a variable, just type the word "var" and the variable name.

var numberOfKittens;
                

It is a good idea to give your variable a starting value. This is called initializing the variable.

var numberOfKittens = 5;
                

Variable value types

Variables can hold different types of information, like words, numbers, and collections of data.

var numberOfKittens = 10; // a number
var numberOfKittens = 'ten'; // a word
var numberOfKittens = [0, 10, 15, 2]; // a list of numbers
                

Naming Variables

  • The variable name is case-sensitive.
  • A new variable needs to have a unique name.
  • Variable names need to start with a letter, $, or _.
  • Variable names can only be made of letters, numbers, $, or _.

Using a Variable

Once you have created a variable, you can use it in your code. Just type the name of the variable.

var numberOfKittens = 5;
console.log(numberOfKittens);

Let's Develop It

In your JS file, create a variable and give it a valid name and a value. Then, display the value.

var numberOfKittens = 5;
console.log(numberOfKittens);
document.getElementById('headline').innerHTML = numberOfKittens;

Refresh your page to see where the variable value appears.

Numbers

Variable can be numbers, either integers or floats (decimals).

var numberOfKittens = 5;
var cutenessRating = 9.6;

Arithmetic Operators

Once you have numbers, you can do math with them!

var numberOfKittens = 5;
var numberOfPuppies = 4;
var numberOfAnimals = numberOfKittens + numberOfPuppies;

Arithmetic Operators

Example Name Result
-a Negation Opposite of a.
a + b Addition Sum of a and b.
a - b Subtraction Difference of a and b.
a * b Multiplication Product of a and b.
a / b Division Quotient of a and b.
a % b Modulus Remainder of a divided by b.

Let's Develop It

Create two variables and try some arithmetic operators. Don't forget to display your results!

var numberOfKittens = 5;
var numberOfPuppies = 4;
var numberOfAnimals = numberOfKittens + numberOfPuppies;
document.getElementById('headline').innerHTML = numberOfAnimals;

Strings

Variable can be strings, groups of characters. You put your string in quotes.

var kittensName = 'Fluffy';

If you want to use a quote in your string, you'll need to "escape" it with a backslash.

console.log('I\'d like to use an apostrophe');
				

String Operators

You can put strings together with a +, the concatenation operator.

var kittensName = 'Fluffy ';
var fullName = kittensName + ' McDougle';
console.log(fullName); //Outputs 'Fluffy McDougle'

String Operators

You can also use += to add things to the end of a string.

var kittensName = 'Admiral ';
kittensName += ' Snuggles';
console.log(kittensName); //Outputs 'Admiral Snuggles'

Let's Develop It

Create two variables, a first name and a last name, and then put them together to make a full name. Don't forget to display your results!

Let's Develop It: The Fortune Teller

Cootie catcher

Why pay a fortune teller when you can just program your fortune yourself?

  • Store the following into variables: city or place, job title, home, and hobby.
  • Output your fortune to the screen like so: "You will be a _job_ living in a _home_ in _city or place_. For fun you will _hobby_."

Need help? See one possible solution on Github.

Functions

Functions are separable, reusable pieces of code.

Using Functions

First, declare the function.

function turtleFact() {
    console.log('A turtle\'s lower shell is called a plastron.');
}

Then, use it as many times as you want!

turtleFact();
turtleFact();
turtleFact();

Let's Develop It

Turn the code you wrote to output someone's full name into a function, then use it to output the name to the practice.html page.

function sayMyName() {
  var firstName = 'Kelly ';
  var lastName = 'Rowland';
  var fullName = firstName + lastName;
  document.getElementById('headline').innerHTML = fullName;
}

sayMyName(); // don't forget to call it!

Bonus: Make your function automatically add a space between the names.

Arguments

Functions can accept input values, called arguments.

function callKitten(kittenName) {
    console.log('Come here, ' + kittenName + '!');
}
callKitten('Fluffy'); //outputs 'Come here, Fluffy!'
callKitten('Pumpkin'); //outputs 'Come here, Pumpkin!'

Let's Develop It

Update your full name function to take multiple arguments as inputs, so that it outputs different names to the page depending on how you call it:

sayMyName('Destiny\'s', 'Child'); // should output "Destiny's Child"
sayMyName('Kelly', 'Rowland'); // should output "Kelly Rowland"
sayMyName('Michelle', 'Williams');
sayMyName('Beyoncé', 'Knowles');

Arguments

Argument values can be numbers, which means we can make Javascript do math for us over and over.

function addNumbers(a, b) {
    console.log(a + b);
}
addNumbers(5,7); //outputs 12
addNumbers(9,12); //outputs 21

Arguments

You can also pass variables into functions. Note: These variables do not have the same name as the function arguments.

function addOne(inputNumber){
    var newNumber = inputNumber + 1;
    console.log('You now have ' + newNumber);
}
//Declare variables
var numberOfKittens = 5;
var numberOfPuppies = 4;
//Use them in functions
addOne(numberOfKittens);
addOne(numberOfPuppies);    

Returning Values

You can have a function give you back a value, to use later.

function square(num) {
    return num * num;
}
console.log(square(4));   // outputs '16'.

Return will immediately end a function.

Returning Values

You can use variables to save the return value from a function.

function square(num) {
    return num * num;
}
var squareOfFive = square(5); // will make squareOfFive equal 25.

Let's Develop It

Add a return statement to your name function. Use that function to set the value of a variable.

function sayMyName(first, last) {
    // this also adds a space between the 2 arguments
    return first + ' ' + last;
}
var name1 = sayMyName('Kelly', 'Rowland');
var name2 = sayMyName('Michelle', 'Williams');

alert(name1);
document.getElementById('headline').innerHTML = name2;

Let's Develop It: The Calculator

Part 1 of 4

Write a function called squareNumber that will take one argument (a number), square that number, and return the result. It should also log a string like "The result of squaring the number 3 is 9."

See one possible solution on Github.

Let's Develop It: The Calculator

Part 2 of 4

Write a function called halfNumber that will take one argument (a number), divide it by 2, and return the result. It should also log a string like "Half of 5 is 2.5.".

See one possible solution on Github.

Let's Develop It: The Calculator

Part 3 of 4

Write a function called percentOf that will take two numbers, figure out what percent the first number represents of the second number, and return the result. It should also log a string like "2 is 50% of 4."

See one possible solution on Github.

Let's Develop It: The Calculator

Part 4 of 4

Write a function called areaOfCircle that will take one argument (the radius), calculate the area based on that, and return the result. It should also log a string like "The area for a circle with radius 2 is 12.566370614359172."

  • Bonus: Round the result so there are only two digits after the decimal.

See one possible solution on Github.

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); 

Boolean Variables

Boolean variables represent the logical values True and False

var catsAreBest = true;
var dogsRule = false;
        

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.

Truthy and Falsy

If you try to use a value other than "true" or "false" JavaScript will treat them as "truthy" or "falsy."

"Falsy" values:

  • The number 0
  • the empty string ""
  • undefined
  • null are considered false

Everything else is "truthy."

Strict and loose equality

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.

if (temperature > 60 && temperature < 70) {
    document.getElementById('welcome-message').innerHTML = 
        'the weather is lovely, wear whatever you like';
} else if (temperature > 100 || temperature < 0) {
   document.getElementById('welcome-message').innerHTML = 
        'stay inside, the weather is awful'; 
}

Let's Develop It

JavaScript Puzzle: What number is bigger?

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];
        

Let's Develop It

Create an array of your favorite foods. Display a few values on your screen.

var myFaveFoods = ['chocolate', 'pickles', 'avocados'];
console.log(myFaveFoods[0]);
console.log(myFaveFoods[1]);
console.log(myFaveFoods[2]);
        

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

Change the first and last items in your favorite foods array using bracket notation, and add new items using the "push" function. Then display your new values on the page.

var myFaveFoods = ['chocolate', 'pickles', 'avocados', 'tofu scramble', 'pancakes', 'donuts'];
myFaveFoods[0] = 'chocolate cake to be more specfic';
myFaveFoods.push('lemons');
document.getElementById('foods').innerHTML = myFaveFoods;           

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); 
}
        

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. For now, use console.log to view the list.

var myFaveFoods = ['pancakes', 'avocados', 'donuts'];
for (var i = 0; i < myFaveFoods.length; i++) {
  console.log(myFaveFoods[i]);
}

Let's Develop It

Now update your loop so it can output the list of foods on your HTML page.

var foodString = '';
for (var i = 0; i < myFaveFoods.length; i++) {
  foodString += myFaveFoods[i] + ', ';
}             
document.getElementById('foods').innerHTML = foodString;

Alternate solutions..

  • Save `myFaveFoods[i]` as a variable to make it reusable for outputting in different ways.
  • Make each food an li element inside an unordered list (ul).

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;
    }
}
        

Group exercise: Fizz Buzz

Write a program that prints the numbers from 1 to 100.

But for multiples of three print “Fizz” instead of the number and for the multiples of five print “Buzz”.

For numbers which are multiples of both three and five print “FizzBuzz”.

//Count from 1 to 100
for (var i = 1; i <= 100; i++) {

}
        

Let's Develop It

JavaScript Puzzle: Even/Odd Counter

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.

Resources