Philly Tech Sistas is here to provide affordable and accessible programs to learn software through mentorship and hands-on instruction.
Some "rules"
Tell us about yourself.
JavaScript is a client-side processing language. A browser reads the code and runs it directly.
Photo credits: Andrew E. Larson and John Seb Barber cc
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.
You can mix JavaScript and HTML. The script tag tells your browser the stuff inside is JavaScript, not HTML.
<script>
CODE GOES HERE
</script>
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>
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>
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:
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!';
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
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;
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
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);
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.
Variable can be numbers, either integers or floats (decimals).
var numberOfKittens = 5;
var cutenessRating = 9.6;
Once you have numbers, you can do math with them!
var numberOfKittens = 5;
var numberOfPuppies = 4;
var numberOfAnimals = numberOfKittens + numberOfPuppies;
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. |
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;
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');
You can put strings together with a +, the concatenation operator.
var kittensName = 'Fluffy ';
var fullName = kittensName + ' McDougle';
console.log(fullName); //Outputs 'Fluffy McDougle'
You can also use += to add things to the end of a string.
var kittensName = 'Admiral ';
kittensName += ' Snuggles';
console.log(kittensName); //Outputs 'Admiral Snuggles'
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!
Why pay a fortune teller when you can just program your fortune yourself?
Need help? See one possible solution on Github.
Functions are separable, reusable pieces of code.
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();
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.
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!'
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');
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
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);
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.
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.
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;
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."
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.".
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."
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."
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 represent the logical values True and False
var catsAreBest = true;
var dogsRule = false;
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!');
}
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. |
If you try to use a value other than "true" or "false" JavaScript will treat them as "truthy" or "falsy."
"Falsy" values:
""
Everything else is "truthy."
Don't mix up = and ==
Make a variable called "temperature." Write some code that tells you to put on a coat if it is below 50 degrees.
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.');
}
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.');
}
Modify your "wear a coat" code for these conditions:
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 . |
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');
}
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';
}
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'];
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);
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];
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]);
You can use bracket notation to change an item in an array
var myFavoriteThings = ['Broccoli', 1024, 'Sherlock'];
myFavoriteThings[0] = 'Asparagus';
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');
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 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;
}
Make sure something changes in the loop, or your loop will go on forever...
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);
}
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]);
}
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]);
}
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..
li
element inside an unordered list (ul
).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');
}
}
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;
}
}
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++) {
}
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.