Part 2
Control Flow and More Data Types
function calculateTip(total) {
var tipPercent = 0.15;
return (total * tipPercent);
}
var billTotal = 10.00;
var billTip = calculateTip(billTotal);
var receipt = 'Total: ' + billTotal + ' Tip: ' + billTip;
console.log(receipt);
statement
console.log(receipt);
variable
var billTotal = 10.00;
expression
var receipt = 'Total: ' + billTotal + ' Tip: ' + bill;
operator
+
function
function calculateTip(total) {
var tipPercent = 0.15;
return (total * tipPercent);
}
argument
(total)
(billTotal)
return value
return (total * tipPercent);
if
statements
if
StatementUse if
to tell JS which statements to execute, based on a condition.
What if
looks like:
if (condition) {
// statements to execute
}
if
Worksif
statements execute only if your condition is true. Example:
var x = 5;
if (x > 0) {
console.log('x is a positive number!');
}
What happens here?
Comparison Operators
Use these operators to compare two values for equality, inequality, or difference.
true
or false
var myAge = 26;
if (myAge == 26) {
// stuff
}
Important!
Don't confuse assignment (=
) with equality comparisons (==
)!
var myAge = 26;
if (myAge === 26) {
// stuff
}
What happens when we do this?
var age = '26';
if (age === 26) {
// stuff
}
var myAge = 26;
if (myAge != 26) {
// stuff
}
var myAge = 26;
if (myAge !== 26) {
// stuff
}
myAge > 26
myAge < 26;
myAge >= 26
myAge <= 26
AND, OR, NOT
true
or false
AND - &&
Returns true if: both statements are true.
var posNum = 4;
var negNum = -2;
True expressions:
posNum > 0 && negNum < 0
4 > 0 && -2 < 0
False expressions:
posNum > 0 && negNum > 0
4 > 0 && -2 > 0
Inclusive OR - ||
Returns true if: either statement (or both) is true.
var posNum = 4;
var negNum = -2;
True expressions:
posNum > 0 || negNum > 0
4 > 0 || -2 > 0
False expressions:
posNum > 0 || negNum < 0
4 > 0 || -2 < 0
Negation - !
Inverts the truth of another expression
var wants_to_dance = true;
var friends_of_mine = true;
if (!wants_to_dance) {
friends_of_mine = false;
}
Used to increment or decrement a variable by one
var start = 0;
start++;
console.log(start); // 1
console.log(start++); // Postfix - 1
console.log(start); // 2
console.log(++start); // Prefix - 3
Most commonly used in a for
loop
When combining together multiple conditions, use parantheses to group:
var friends = false;
if (favorite_band === 'The Mountain Goats' || has_beer) {
friends = true;
}
An important lesson: truthy and falsey
If you don't use a comparison or logical operator, JavaScript tries to figure out if the value is "truth-y".
var dogsRule = true;
if (dogsRule) {
console.log("Yay dogs!");
}
Values that are "false-y": false
, the empty string (""
), the number 0
, undefined
, null
.
var name = '';
if (name) {
console.log("Hello, " + name);
}
var points = 0;
if (points) {
console.log("You have " + points + " points.");
}
var firstName;
if (firstName) {
console.log("Your name is " + firstName);
}
How JavaScript saves us time!
JavaScript evaluates all logical operators from left to right. It stops evaluating as soon as it knows the answer.
When it stops depends on the operator you're using.
&&
Stops as soon as it hits a false
expression because it requires all things to be true.
var name = "";
var age = 26;
if (name && age) {
console.log("Hello!);
}
Because name
is false, it won't ever get to age
.
||
Stops as soon as it hits a true
expression because it only needs one thing to be true.
var name = "";
var age = 26;
if (name || age) {
console.log("Hello!);
}
name
is false, but age
is true, so this goes the whole way through.
If we change this around to:
if (age || name) {
console.log("Hello!);
}
age
is true, so it stops evaluating.
if
, else if
, and else
statements
if
/else
statementsUse else
to give JavaScript an alternative statement. else
runs when the if
statement fails.
...
if (is_admin) {
delete_user();
} else {
alert('Only admins can delete users');
}
if/else/else if
If you want multiple checks, you can use else if
to run through them all.
...
if (!zipcode) {
console.log('No name given');
} else if (zipcode.length !== 5 || isNaN(parseInt(zipcode, 10))) {
console.log("Invalid zipcode");
} else {
console.log("Your zipcode is " + zipcode);
}
if/else
If you get stuck, raise your hand.
while
loopThe while
loop tells JavaScript to repeat statements while the condition remains true
var x = 0;
while (x < 5) {
console.log(x);
x++;
}
do/while
Exactly like while but will run the body at least once before quitting
var name = null;
do {
name = prompt('What is your name?');
} while (!name);
console.log(name);
Pretty rare with specific use-cases
for
loopThe for
loop is another way of repeating statements, more specialized than while
. There are more pieces:
for (initialize variable(s); condition; update) {
// statements to repeat
}
for
loopWhat it looks like with real values:
for (var i = 0; i < 5; i++) {
console.log(i);
}
The for loop used when you have a known start/stop for your loop
break
To prematurely exit a loop, you can use the break
statement:
for (var current = 100; current < 200; current++) {
console.log("Testing " + current);
if (current === 155) {
console.log("Found it! " + current);
break;
}
}
continue
Used to skip an iteration
for (var current = 100; current < 200; current++) {
if (current === 155) {
console.log('Skip 155');
continue;
}
console.log('Current: ' + current);
}
If you get stuck, raise your hand.
A data type containing an ordered list of values.
Arrays are a data type that hold an ordered list of values. These values can be any type. Arrays look like this:
var arrayName = [element0, element1, element2];
We can make an array of our favorite bands:
var favoriteBands = [
"The Mountain Goats", "Timber Timbre", "Fleet Foxes"
]
And find out the length (property):
console.log(favoriteBands.length);
You can access things in an array using bracket notation and the index (location). The first item in your array is at index 0 (Blame Martin Richards)
var colors = ['Red', 'Orange', 'Yellow', 'Green'];
var firstColor = colors[0];
var lastColor = colors[colors.length - 1];
You can also use bracket notation to change items in the array.
var favoriteBands = [
"The Mountain Goats", "Timber Timbre", "Fleet Foxes"
];
favoriteBands[1] = 'Valaska';
Adding to an array is done with the push()
method of the array
var favoriteBands = [
"The Mountain Goats", "Timber Timbre", "Fleet Foxes"
];
favoriteBands.push("Good Old War");
console.log(favoriteBands);
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]);
}
Modern browsers (IE9+) support the forEach method, which is cleaner than a for loop
var rainbowColors = [
"red", "orange", "yellow", "green", "blue", "indigo", "violet"
];
rainbowColors.forEach(function (color, index) {
console.log(color);
});
// compared to
for (var i = 0; i < rainbowColors.length; i++) {
console.log(rainbowColors[i]);
}
Google for questions or check Stack Overflow. Also look on the Mozilla Developer Network.