Javascript Conditionals and Loops
Conditionals
Ternary Operator
- `[condition] ? [condition is true] : [the condition is false]
Switch Statements
let firstName = 'John';
let job = 'teacher';
switch (job) {
case 'teacher': // two case staements in a row like this will make the same code
case 'instructor': // execute for both of them
console.log(firstName + ' teaches kids how to code.');
break; // stops it from checking other cases
case 'driver':
console.log(firstName + ' drives an uber in Lisbon.');
break;
case 'designer':
console.log(firstName + ' designs beautiful websites.');
break;
default: // like an else statement in an if/else
console.log(firstName + ' does something else.');
}
while
Loops
while(someCondition){
// run some code
}
- example 1a:
let count = 1;
while(count < 6){
console.log("count is: " + count);
count++;
}
// count is: 1
// count is: 2
// count is: 3
// count is: 4
// count is: 5
- example 2a:
let str = "hello";
let count = 0;
while(count < str.length){
console.log(str[count]);
count++;
}
// "h"
// "e"
// "l"
// "l"
// "o"
- NO writing Infinite Loops -- make sure to increment count or break loop
for
Loops
.forEach
Loops
- built-in way of iterating over an array
- syntax:
arrayName.forEach(someFunction)
- example with anonymous function:
let colors = ['red', 'orange', 'yellow', 'green'];
colors.forEach(function(color){
//color is a placeholder, call it whatever you want
console.log(color);
});
- example with named function:
let colors = ['red', 'orange', 'yellow', 'green'];
function printColor(color){
console.log('***************');
console.log(color);
console.log('***************');
}
colors.forEach(printColor);
- the function given to the forEach loop is the callback function
- the callback function can take up to three arguments (must have at least one)
- first: represents each element in the array (per loop iteration) that
forEach
was called on
- second: represents the index of said element
- third: represents the array that
forEach
was called on (the same for every iteration)
- example with anonymous function:
[1, 2, 3].forEach(function(el, i, arr){
console.log(el, i, arr);
});
//1 0 [1, 2, 3]
//2 1 [1, 2, 3]
//3 2 [1, 2, 3]
- example with named function:
function logNums(el, i, arr){
console.log(el, i, arr);
}
[1, 2, 3].forEach(logNums);
//1 0 [1, 2, 3]
//2 1 [1, 2, 3]
//3 2 [1, 2, 3]
Building Our Own forEach
Function
- see buildingOurOwnForEach.js in the repository: the-web-developer-bootcamp/javascript
for-of Loops (ES6)
const pets = ['cat', 'dog', 'snake', 'hamster', 'bird']
for (const pet of pets) console.log(pet)
// cat
// dog
// snake
// hamster
// bird
- automatically loops over the array, giving us access to the element in the current iteration
- don't need to create code block when only have one statement on the same line
- works on any iterable
- can still use
continue
, break
, return
, yield
, and await
- finding the index of the current element:
for (const pet of pets.entries()) {
console.log(pet)
}
// ▶︎ (2) [0, 'cat']
// ▶︎ (2) [1, 'dog']
// ▶︎ (2) [2, 'snake']
// ▶︎ (2) [3, 'hamster']
// ▶︎ (2) [4, 'bird']
orconsole.log([...menu.entries()])
// ▼ (7) [Array(2), Array(2), Array(2), Array(2), Array(2)]
// ▼ 0: ︎Array(2)
// 0: 0
// 1: 'cat'
// ▶ 1: ︎(2) [1, 'dog']
// ▶ 2: ︎(2) [2, 'snake']
// ▶ 3: ︎(2) [3, 'hamster']
// ▶ 4: ︎(2) [4, 'bird']
.entries
is an 'Array Iterator' - returns new arrays for each element with the index number and the element
- can use to print numbered lists, etc:
for (const pet of pets.entries) {
console.log(`${pet[0] + 1}: ${pet}`)
}
// 1: cat
// 2: dog
// 3: snake
// 4: hamster
// 5: bird
- can write this slightly more eloquently using destructuring (see destructuring notes) and get the same output result
for (const [i, pet] of pets.entries) {
console.log(`${i + 1}: ${pet}`)
}
// 1: cat
// 2: dog
// 3: snake
// 4: hamster
// 5: bird
Comparing Types of for Loops
for
vs forEach
- in a
for
loop we are dealing with a number, which we are using to access elements of an array
- in a
forEach
that's abstracted away, we are just dealing with a placeholder name that is used
inside a function- more common to use with anonymous functions than named functions
- there are cases where
forEach
doesn't exist
.forEach
vs for-of Loops
from this stackoverflow post
This is a very intersting question which has been discussed in many other sites. I'll post the basics
of what I have read.
ForEach exclusively belong to the royal family of Arrays. The forEach method was
introduced with lineage to the prototypal inheritance of Array object! Needless to say, the
forEach clause works only with those data structure which are Arrays. The method
basically iterates over the elements of the array and executes a callback function [basically
some executable function/ fun activity].
The for-of loop is adequately new to the JS world and packs in super-powers!
Voilaaaaaaa! The for-of loop creates a loop iterating over iterable member objects. The list
is an extensive one such as
•Array
•Map
•Set
•String
•TypedArray
•Other W3C classes
You need to know that this bad-ass boy emerged with the birth of ES6 in 2015. So, it offers
plenty of flexibility in usage
Performance
In performance, for...of is faster than forEach. Results can be found here
forEach is 24% slower than for...of
Continue and Break
var john = ['John', 'Smith', 1990, 'designer', false, 'blue'];
for (var i = 0; i < john.length; i++) {
if (typeof john[i] !== 'string') continue;
console.log(john[i]);
// John
// Smith
// designer
// blue
}
- if the element is not a string the loop will just continue to the next iteration
var john = ['John', 'Smith', 1990, 'designer', false, 'blue'];
for (var i = 0; i < john.length; i++) {
if (typeof john[i] !== 'string') break;
console.log(john[i]);
// John
// Smith
}
- if the element is not a string the loop will terminate
Looping Backwards
var john = ['John', 'Smith', 1990, 'designer', false, 'blue'];
for (let i = jihn.length - 1; i >= 0; i--) {
console.log(john[i]);
// blue
// false
// designer
// 1990
// Smith
// John
}