Skip to content

Instantly share code, notes, and snippets.

@engramar

engramar/JS_Study_Group.js

Last active Jan 16, 2021
Embed
What would you like to do?
Comment Your JavaScript Code
//1.1 Comment Your JavaScript Code
// This is an in-line comment.
/* This is a
multi-line comment */
//1.2 Declare JavaScript Variables
var myName;
//1.3 Storing Values with the Assignment Operator
var a;
a = 7;
//1.4 Assigning the Value of One Variable to Another
var a;
a = 7;
var b;
b = a;
//1.5 Initializing Variables with the Assignment Operator
var a = 9;
//1.6 Understanding Uninitialized Variables
var a = 5;
var b = 10;
var c = "I am a";
a = a + 1;
b = b + 5;
c = c + " String!";
//1.7 Understanding Case Sensitivity in Variables
var studlyCapVar;
var properCamelCase;
var titleCaseOver;
studlyCapVar = 10;
properCamelCase = "A String";
titleCaseOver = 9000;
//1.8 Add Two Numbers with JavaScript
var sum = 10 + 10;
//1.9 Subtract One Number from Another with JavaScript
var difference = 45 - 33;
//1.10 Multiply Two Numbers with JavaScript
var product = 8 * 10;
//1.11 Divide One Number by Another with JavaScript
var quotient = 66 / 33;
//1.12 Increment a Number with JavaScript
var myVar = 87;
myVar = myVar++;
//1.13 Decrement a Number with JavaScript
var myVar = 11;
myVar--;
//1.14 Create Decimal Numbers with JavaScript
var ourDecimal = 5.7;
var myDecimal = 5.7;
//1.15 Multiply Two Decimals with JavaScript
var product = 2.0 * 2.5;
//1.16 Divide One Decimal by Another with JavaScript
var quotient = 4.4 / 2.0;
//1.17 Finding a Remainder in JavaScript
var remainder;
remainder = 11%3;
//1.18 Compound Assignment With Augmented Addition
var a = 3;
var b = 17;
var c = 12;
a += 12;
b += 9;
c += 7;
//1.19 Compound Assignment With Augmented Subtraction
var a = 11;
var b = 9;
var c = 3;
a -= 6;
b -= 15;
c -= 1;
//1.20 Compound Assignment With Augmented Multiplication
var a = 5;
var b = 12;
var c = 4.6;
a *= 5;
b *= 3;
c *= 10;
//1.21 Compound Assignment With Augmented Division
var a = 48;
var b = 108;
var c = 33;
a /= 12;
b /= 4;
c /= 11;
//1.22 Declare String Variables
var myFirstName = "Brendan";
var myLastName = "Eich";
//1.23 Escaping Literal Quotes in Strings
var myStr = "I am a \"double quoted\" string inside \"double quotes\".";
//1.24 Quoting Strings with Single Quotes
var myStr = '<a href="http://www.example.com" target="_blank">Link</a>';
//1.25 Escape Sequences in Strings
var myStr = "FirstLine\n\t\\SecondLine\nThirdLine"
//1.26 Concatenating Strings with Plus Operator
var myStr = "This is the start. " + "This is the end.";
//1.27 Concatenating Strings with the Plus Equals Operator
var myStr = "This is the first sentence. ";
myStr += "This is the second sentence.";
//1.28 Constructing Strings with Variables
var myName = "Brendan";
var myStr = "My name is " + myName + " and I am well!";
//1.29 Appending Variables to Strings
var someAdjective = "fun";
var myStr = "Learning to code is ";
myStr += someAdjective;
//1.30 Find the Length of a String
var lastNameLength = 0;
var lastName = "Lovelace";
lastNameLength = lastName.length;
//1.31 Use Bracket Notation to Find the First Character in a String
var firstLetterOfLastName = "";
var lastName = "Lovelace";
firstLetterOfLastName = lastName[0];
//1.32 Understand String Immutability
var myStr = "Jello World";
myStr = "Hello World";
//1.33 Use Bracket Notation to Find the Nth Character in a String
var lastName = "Lovelace";
var thirdLetterOfLastName = lastName[2];
//1.34 Use Bracket Notation to Find the Last Character in a String
var lastName = "Lovelace";
var lastLetterOfLastName = lastName[lastName.length - 1];
//1.35 Use Bracket Notation to Find the Nth-to-Last Character in a String
var lastName = "Lovelace";
var secondToLastLetterOfLastName = lastName[lastName.length - 2];
//1.36 Word Blanks
var myNoun = "dog";
var myAdjective = "big";
var myVerb = "ran";
var myAdverb = "quickly";
var wordBlanks = myNoun + " " + myAdjective + " " + myVerb + " " + myAdverb; // Change this line
//1.37 Store Multiple Values in one Variable using JavaScript Arrays
var myArray = ['one',1];
//1.38 Nest one Array within Another Array
var myArray = [["Bulldogs", 23], ["Eels", 45]]
//1.39 Access Array Data with Indexes
var myArray = [50,60,70];
var myData = myArray[0];
//1.40 Modify Array Data With Indexes
var myArray = [18,64,99];
myArray[0] = 45;
//1.41 Access Multi-Dimensional Arrays With Indexes
var myArray = [[1,2,3], [4,5,6], [7,8,9], [[10,11,12], 13, 14]];
var myData = myArray[2][1];
//1.42 Manipulate Arrays With push()
var myArray = [["John", 23], ["cat", 2]];
myArray.push(["dog", 3])
//1.43 Manipulate Arrays With pop()
var myArray = [["John", 23], ["cat", 2]];
var removedFromMyArray = myArray.pop();
//1.44 Manipulate Arrays With shift()
var myArray = [["John", 23], ["dog", 3]];
var removedFromMyArray = myArray.shift();
//1.45 Manipulate Arrays With unshift()
var myArray = [["John", 23], ["dog", 3]];
myArray.shift();
myArray.unshift(["Paul",35]);
//1.46 Shopping List
var myList = [
["Chocolate 1", 15],
["Chocolate 2", 15],
["Chocolate 3", 15],
["Chocolate 4", 15],
["Chocolate 5", 15]
];
//1.47 Write Reusable JavaScript with Functions
function reusableFunction() {
console.log("Hi World");
}
reusableFunction();
//1.48 Passing Values to Functions with Arguments
function functionWithArgs(param1, param2) {
console.log(param1+param2);
}
functionWithArgs(1,2);
//1.49 Global Scope and Functions
// Declare the myGlobal variable below this line
var myGlobal = 10;
function fun1() {
// Assign 5 to oopsGlobal Here
oopsGlobal = 5;
}
function fun2() {
var output = "";
if (typeof myGlobal != "undefined") {
output += "myGlobal: " + myGlobal;
}
if (typeof oopsGlobal != "undefined") {
output += " oopsGlobal: " + oopsGlobal;
}
console.log(output);
}
//1.50 Local Scope and Functions
function myLocalScope() {
'use strict';
var myVar;
console.log('inside myLocalScope', myVar);
}
myLocalScope();
console.log('outside myLocalScope', myVar);
//1.51 Global vs. Local Scope in Functions
var outerWear = "T-Shirt";
function myOutfit() {
var outerWear = "sweater";
return outerWear;
}
myOutfit();
//1.52 Return a Value from a Function with Return
function timesFive(num) {
return num * 5;
}
var answer = timesFive(5);
//1.53 Understanding Undefined Value returned from a Function
var sum = 0;
function addThree() {
sum = sum + 3;
}
function addFive() {
sum = sum + 5;
}
addThree();
addFive();
//1.54 Assignment with a Returned Value
var processed = 0;
function processArg(num) {
return (num + 3) / 5;
}
processed = processArg(7);
//1.55 Stand in Line
function nextInLine(arr, item) {
arr.push(item);
return arr.shift();
}
var testArr = [1,2,3,4,5];
console.log("Before: " + JSON.stringify(testArr));
console.log(nextInLine(testArr, 6));
console.log("After: " + JSON.stringify(testArr));
//1.56 Understanding Boolean Values
function welcomeToBooleans() {
return true;
}
//1.57 Use Conditional Logic with If Statements
function trueOrFalse(wasThatTrue) {
if (wasThatTrue){
return "Yes, that was true"
}
return "No, that was false"
}
//1.58 Comparison with the Equality Operator
function testEqual(val) {
if (val == 12) { // Change this line
return "Equal";
}
return "Not Equal";
}
testEqual(10);
//1.59 Comparison with the Strict Equality Operator
function testStrict(val) {
if (val === 7) {
return "Equal";
}
return "Not Equal";
}
testStrict(10);
//1.60 Practice comparing different values
function compareEquality(a, b) {
if (a === b) {
return "Equal";
}
return "Not Equal";
}
compareEquality(10, "10");
//1.61 Comparison with the Inequality Operator
function testNotEqual(val) {
if (val != 99) {
return "Not Equal";
}
return "Equal";
}
testNotEqual(10);
//1.62 Comparison with the Strict Inequality Operator
function testStrictNotEqual(val) {
if (val !== 17) {
return "Not Equal";
}
return "Equal";
}
testStrictNotEqual(10);
//1.63 Comparison with the Greater Than Operator
function testGreaterThan(val) {
if (val > 100) {
return "Over 100";
}
if (val > 10) {
return "Over 10";
}
return "10 or Under";
}
testGreaterThan(10);
//1.64 Comparison with the Greater Than Or Equal To Operator
function testGreaterOrEqual(val) {
if (val >= 20) {
return "20 or Over";
}
if (val >= 10) {
return "10 or Over";
}
return "Less than 10";
}
testGreaterOrEqual(10);
//1.65 Comparison with the Less Than Operator
function testLessThan(val) {
if (val < 25) {
return "Under 25";
}
if (val < 55) {
return "Under 55";
}
return "55 or Over";
}
testLessThan(10);
//1.66 Comparison with the Less Than Or Equal To Operator
function testLessOrEqual(val) {
if (val <= 12) {
return "Smaller Than or Equal to 12";
}
if (val <= 24) {
return "Smaller Than or Equal to 24";
}
return "More Than 24";
}
testLessOrEqual(10);
//1.67 Comparisons with the Logical And Operator
function testLogicalAnd(val) {
if (val <= 50 && val >=25 ) {
return "Yes";
}
return "No";
}
testLogicalAnd(10);
//1.68 Comparisons with the Logical Or Operator
function testLogicalOr(val) {
if (val < 10 || val > 20 ) {
return "Outside";
}
return "Inside";
}
testLogicalOr(15);
//1.69 Introducing Else Statements
function testElse(val) {
var result = "";
if (val > 5) {
result = "Bigger than 5";
} else {
result = "5 or Smaller";
}
return result;
}
testElse(4);
//1.70 Introducing Else If Statements
function testElseIf(val) {
if (val > 10) {
return "Greater than 10";
} else if (val < 5) {
return "Smaller than 5";
} else {
return "Between 5 and 10";
}
}
testElseIf(7);
//1.71 Logical Order in If Else Statements
function orderMyLogic(val) {
if (val < 5) {
return "Less than 5";
} else if (val < 10) {
return "Less than 10";
} else {
return "Greater than or equal to 10";
}
}
orderMyLogic(7);
//1.72 Chaining If Else Statements
function testSize(num) {
if (num < 5) {
return 'Tiny'; 1
} else if (num < 10) {
return 'Small';
} else if (num < 15) {
return 'Medium';
} else if (num < 20) {
return 'Large';
} else {
return 'Huge';
}
}
testSize(7);
//1.73 Golf Code
var names = ["Hole-in-one!", "Eagle", "Birdie", "Par", "Bogey", "Double Bogey", "Go Home!"];
function golfScore(par, strokes) {
switch(true)
{
case (strokes === 1):
return names[0];
break;
case (strokes <= (par - 2)):
return names[1];
break;
case (strokes === (par - 1)):
return names[2];
break;
case (strokes === par):
return names[3];
break;
case (strokes === par + 1):
return names[4];
break;
case (strokes === par + 2):
return names[5];
break;
default:
return names[6];
break;
}
}
golfScore(5, 4);
//1.74 Selecting from Many Options with Switch Statements
function caseInSwitch(val) {
var answer = "";
switch(val) {
case 1:
answer = "alpha";
break;
case 2:
answer = "beta";
break;
case 3:
answer = "gamma";
break;
case 4:
answer = "delta";
break;
}
return answer;
}
caseInSwitch(1);
//1.75 Adding a Default Option in Switch Statements
function switchOfStuff(val) {
var answer = "";
switch(val) {
case "a":
answer = "apple";
break;
case "b":
answer = "bird";
break;
case "c":
answer = "cat";
break;
default:
answer = "stuff";
break;
}
return answer;
}
switchOfStuff(1);
//1.76 Multiple Identical Options in Switch Statements
function sequentialSizes(val) {
var answer = "";
switch(val) {
case 1:
case 2:
case 3:
answer = "Low";
break;
case 4:
case 5:
case 6:
answer = "Mid";
break;
case 7:
case 8:
case 9:
answer = "High";
break;
}
return answer;
}
sequentialSizes(1);
//1.77 Replacing If Else Chains with Switch
function chainToSwitch(val) {
var answer = "";
switch(val) {
case "bob":
answer = "Marley";
break;
case 42:
answer = "The Answer";
break;
case 1:
answer = "There is no #1";
break;
case 99:
answer = "Missed me by this much!";
break;
case 7:
answer = "Ate Nine";
break;
}
return answer;
}
chainToSwitch(7);
//1.78 Returning Boolean Values from Functions
function isLess(a, b) {
return a <= b;
}
isLess(10, 15);
//1.79 Return Early Pattern for Functions
function abTest(a, b) {
if (a < 0 || b < 0) {
return undefined;
}
return Math.round(Math.pow(Math.sqrt(a) + Math.sqrt(b), 2));
}
abTest(2,2);
//1.80 Counting Cards
var count = 0;
function cc(card) {
switch(card) {
case 2:
case 3:
case 4:
case 5:
case 6:
count++;
break;
case 7:
case 8:
case 9:
break;
case 10:
case 'J':
case 'Q':
case 'K':
case 'A':
count--;
break;
}
if (count > 0) {
return count + " Bet";
} else {
return count + " Hold";
}
}
cc(2); cc(3); cc(7); cc('K'); cc('A');
//1.81 Build JavaScript Objects
var myDog = {
"name": "Ashie",
"legs": 4,
"tails": 1,
"friends": ["Tiny", "Bear"]
};
//1.82 Accessing Object Properties with Dot Notation
var testObj = {
"hat": "ballcap",
"shirt": "jersey",
"shoes": "cleats"
};
var hatValue = testObj.hat;
var shirtValue = testObj.shirt;
//1.83 Accessing Object Properties with Bracket Notation
var testObj = {
"an entree": "hamburger",
"my side": "veggies",
"the drink": "water"
};
var entreeValue = testObj["an entree"];
var drinkValue = testObj["the drink"];
//1.84 Accessing Object Properties with Variables
var testObj = {
12: "Namath",
16: "Montana",
19: "Unitas"
};
var playerNumber = 16; // Change this line
var player = testObj[playerNumber]; // Change this line
//1.85 Updating Object Properties
var myDog = {
"name": "Coder",
"legs": 4,
"tails": 1,
"friends": ["freeCodeCamp Campers"]
};
myDog.name = "Happy Coder";
//1.86 Add New Properties to a JavaScript Object
var myDog = {
"name": "Happy Coder",
"legs": 4,
"tails": 1,
"friends": ["freeCodeCamp Campers"]
};
myDog.bark = "woof";
//1.87 Delete Properties from a JavaScript Object
var myDog = {
"name": "Happy Coder",
"legs": 4,
"tails": 1,
"friends": ["freeCodeCamp Campers"],
"bark": "woof"
};
delete myDog.tails;
//1.88 Using Objects for Lookups
function phoneticLookup(val) {
var result = "";
var lookup = {
"alpha":"Adams",
"bravo":"Boston",
"charlie":"Chicago",
"delta":"Denver",
"echo":"Easy",
"foxtrot":"Frank",
" ":"undefined"
}
result = lookup[val];
// Only change code above this line
return result;
}
phoneticLookup("charlie");
//1.89 Testing Objects for Properties
function checkObj(obj, checkProp) {
if (obj.hasOwnProperty(checkProp)){
return obj[checkProp];
} else {
return "Not Found";
}
}
//1.90 Manipulating Complex Objects
var myMusic = [
{
"artist": "Billy Joel",
"title": "Piano Man",
"release_year": 1973,
"formats": [
"CD",
"8T",
"LP"
],
"gold": true
},
// Add a record here
{
"artist": "Daft Punk",
"title": "Homework",
"release_year": 1997,
"formats": [
"CD",
"Cassette",
"LP"
],
"gold": true
}
];
//1.91 Accessing Nested Objects
var myStorage = {
"car": {
"inside": {
"glove box": "maps",
"passenger seat": "crumbs"
},
"outside": {
"trunk": "jack"
}
}
};
var gloveBoxContents = myStorage.car.inside['glove box'];
//1.92 Accessing Nested Arrays
var myPlants = [
{
type: "flowers",
list: [
"rose",
"tulip",
"dandelion"
]
},
{
type: "trees",
list: [
"fir",
"pine",
"birch"
]
}
];
var secondTree = myPlants[1].list[1];
//1.93 Record Collection
var collection = {
2548: {
albumTitle: 'Slippery When Wet',
artist: 'Bon Jovi',
tracks: ['Let It Rock', 'You Give Love a Bad Name']
},
2468: {
albumTitle: '1999',
artist: 'Prince',
tracks: ['1999', 'Little Red Corvette']
},
1245: {
artist: 'Robert Palmer',
tracks: []
},
5439: {
albumTitle: 'ABBA Gold'
}
};
function updateRecords(object, id, prop, value) {
if (prop !== 'tracks' && value !== "") {
object[id][prop] = value;
} else if (prop === "tracks" && !object[id].hasOwnProperty("tracks")) {
object[id][prop] = [value];
} else if (prop === "tracks" && value !== "") {
object[id][prop].push(value);
} else if (value === "") {
delete object[id][prop];
}
return object;
}
updateRecords(collection, 5439, 'artist', 'ABBA');
//1.94 Iterate with JavaScript While Loops
var myArray = [];
var i = 5;
while(i > -1) {
myArray.push(i);
i--;
}
//1.95 Iterate with JavaScript For Loops
var myArray = [];
for (var i = 1; i < 6; i++) {
myArray.push(i);
}
//1.96 Iterate Odd Numbers With a For Loop
var myArray = [];
for (var i = 1; i < 10; i += 2) {
myArray.push(i);
}
//1.97 Count Backwards With a For Loop
var myArray = [];
var ourArray = [];
for (var i = 9; i > 0; i -= 2) {
myArray.push(i);
}
//1.98 Iterate Through an Array with a For Loop
var myArr = [ 2, 3, 4, 5, 6];
var total = 0;
for (var i = 0; i < myArr.length; i++) {
total = total + myArr[i];
}
//1.99 Nesting For Loops
function multiplyAll(arr) {
var product = 1;
for (var i=0; i < arr.length; i++) {
for (var j=0; j < arr[i].length; j++) {
product = product * arr[i][j];
}
}
return product;
}
multiplyAll([[1,2],[3,4],[5,6,7]]);
//1.100 Iterate with JavaScript Do...While Loops
var myArray = [];
var i = 10;
do {
myArray.push(i);
i++;
} while (i < 11);
//1.101 Replace Loops using Recursion
function sum(arr, n) {
// Only change code below this line
if (n <= 0) {
return 0;
} else {
return sum(arr, n - 1) + arr[n - 1];
}
}
//1.102 Profile Lookup
var contacts = [
{
"firstName": "Akira",
"lastName": "Laine",
"number": "0543236543",
"likes": ["Pizza", "Coding", "Brownie Points"]
},
{
"firstName": "Harry",
"lastName": "Potter",
"number": "0994372684",
"likes": ["Hogwarts", "Magic", "Hagrid"]
},
{
"firstName": "Sherlock",
"lastName": "Holmes",
"number": "0487345643",
"likes": ["Intriguing Cases", "Violin"]
},
{
"firstName": "Kristian",
"lastName": "Vos",
"number": "unknown",
"likes": ["JavaScript", "Gaming", "Foxes"]
}
];
function lookUpProfile(name, prop){
for (var x = 0; x < contacts.length; x++) {
if (contacts[x].firstName === name) {
if (contacts[x].hasOwnProperty(prop)) {
return contacts[x][prop];
} else {
return "No such property";
}
}
}
return "No such contact";
}
lookUpProfile("Akira", "likes");
//1.103 Generate Random Fractions with JavaScript
function randomFraction() {
return Math.random();
}
//1.104 Generate Random Whole Numbers with JavaScript
function randomWholeNum() {
return Math.floor(Math.random() * 10);
}
//1.105 Generate Random Whole Numbers within a Range
function randomRange(myMin, myMax) {
return Math.floor(Math.random() * (myMax - myMin + 1)) + myMin;
}
//1.106 Use the parseInt Function
function convertToInteger(str) {
return parseInt(str);
}
convertToInteger("56");
//1.107 Use the parseInt Function with a Radix
function convertToInteger(str) {
return parseInt(str, 2);
}
convertToInteger("10011");
//1.108 Use the Conditional (Ternary) Operator
function checkEqual(a, b) {
return a === b ? "Equal" : "Not Equal";
}
checkEqual(1, 2);
//1.109 Use Multiple Conditional (Ternary) Operators
function checkSign(num) {
return (num > 0) ? "positive"
: (num < 0) ? "negative"
: "zero";
}
checkSign(10);
//1.110 Use Recursion to Create a Countdown
function countdown(n) {
if (n < 1) {
return [];
} else {
const arr = countdown(n - 1);
arr.unshift(n);
return arr;
}
}
//1.111 Use Recursion to Create a Range of Numbers
function rangeOfNumbers(startNum, endNum) {
if (endNum - startNum === 0) {
return [startNum];
} else {
var numbers = rangeOfNumbers(startNum, endNum - 1);
numbers.push(endNum);
return numbers;
}
}
//2.1 Introduction to the ES6 Challenges
//No code exercise for this one
//2.2 Explore Differences Between the var and let Keywords
let catName;
let quote;
function catTalk() {
"use strict";
catName = "Oliver";
quote = catName + " says Meow!";
}
catTalk();
//2.3 Compare Scopes of the var and let Keywords
function checkScope() {
'use strict';
let i = 'function scope';
if (true) {
let i = 'block scope';
console.log('Block scope i is: ', i);
}
console.log('Function scope i is: ', i);
return i;
}
//2.4 Declare a Read-Only Variable with the const Keyword
function printManyTimes(str) {
"use strict";
const SENTENCE = str + " is cool!";
for ( let i = 0; i < str.length; i+=2) {
console.log(SENTENCE);
}
}
printManyTimes("freeCodeCamp");
//2.5 Mutate an Array Declared with const
const s = [5, 7, 2];
function editInPlace() {
'use strict';
// Using s = [2, 5, 7] would be invalid
s[0] = 2;
s[1] = 5;
s[2] = 7;
}
editInPlace();
//2.6 Prevent Object Mutation
function freezeObj() {
'use strict';
const MATH_CONSTANTS = {
PI: 3.14
};
Object.freeze(MATH_CONSTANTS);
try {
MATH_CONSTANTS.PI = 99;
} catch(ex) {
console.log(ex);
}
return MATH_CONSTANTS.PI;
}
const PI = freezeObj();
//2.7 Use Arrow Functions to Write Concise Anonymous Functions
const magic = () => {
"use strict";
return new Date();
};
//2.8 Write Arrow Functions with Parameters
const myConcat = (arr1, arr2) => {
"use strict";
return arr1.concat(arr2);
};
console.log(myConcat([1, 2], [3, 4, 5]));
//2.9 Set Default Parameters for Your Functions
const increment = (number, value=1) => number + value;
//2.10 Use the Rest Parameter with Function Parameters
const sum = (...args) => {
return args.reduce((a, b) => a + b, 0);
}
//2.11 Use the Spread Operator to Evaluate Arrays In-Place
const arr1 = ['JAN', 'FEB', 'MAR', 'APR', 'MAY'];
let arr2;
arr2 = [...arr1];
console.log(arr2);
//2.12 Use Destructuring Assignment to Extract Values from Objects
const HIGH_TEMPERATURES = {
yesterday: 75,
today: 77,
tomorrow: 80
};
const { today, tomorrow } = HIGH_TEMPERATURES;
//2.13 Use Destructuring Assignment to Assign Variables from Objects
const HIGH_TEMPERATURES = {
yesterday: 75,
today: 77,
tomorrow: 80
};
const {today: highToday, tomorrow: highTomorrow } = HIGH_TEMPERATURES;
//2.14 Use Destructuring Assignment to Assign Variables from Nested Objects
const LOCAL_FORECAST = {
yesterday: { low: 61, high: 75 },
today: { low: 64, high: 77 },
tomorrow: { low: 68, high: 80 }
};
const { today: {low: lowToday, high: highToday}} = LOCAL_FORECAST;
//2.15 Use Destructuring Assignment to Assign Variables from Arrays
let a = 8, b = 6;
// Only change code below this line
[a, b] = [b, a];
//2.16 Use Destructuring Assignment with the Rest Parameter to Reassign Array Elements
const source = [1,2,3,4,5,6,7,8,9,10];
function removeFirstTwo(list) {
"use strict";
const [a,b, ...arr] = list; // Change this line
return arr;
}
const arr = removeFirstTwo(source);
//2.17 Use Destructuring Assignment to Pass an Object as a Function's Parameters
const stats = {
max: 56.78,
standard_deviation: 4.34,
median: 34.54,
mode: 23.87,
min: -0.75,
average: 35.85
};
const half = ({ max, min }) => (max + min) / 2.0;
//2.18 Create Strings using Template Literals
const result = {
success: ["max-length", "no-amd", "prefer-arrow-functions"],
failure: ["no-var", "var-on-top", "linebreak"],
skipped: ["no-extra-semi", "no-dup-keys"]
};
function makeList(arr) {
"use strict";
// change code below this line
const failureItems = [];
for (let i = 0; i < arr.length; i++) {
failureItems.push(`<li class="text-warning">${arr[i]}</li>`);
}
// change code above this line
return failureItems;
}
const failuresList = makeList(result.failure);
//2.19 Write Concise Object Literal Declarations Using Object Property Shorthand
const createPerson = (name, age, gender) => {
"use strict";
return {
name,
age,
gender
};
};
//2.20 Write Concise Declarative Functions with ES6
const bicycle = {
gear: 2,
setGear(newGear) {
this.gear = newGear;
}
};
bicycle.setGear(3);
console.log(bicycle.gear);
//2.21 Use class Syntax to Define a Constructor Function
class Vegetable {
constructor(name) {
this.name = name;
}
}
const carrot = new Vegetable('carrot');
console.log(carrot.name); // Should display 'carrot'
//2.22 Use getters and setters to Control Access to an Object
class Thermostat {
constructor(fahrenheit) {
this.fahrenheit = fahrenheit;
}
get temperature() {
return (5 / 9) * (this.fahrenheit - 32);
}
set temperature(celsius) {
this.fahrenheit = (celsius * 9.0) / 5 + 32;
}
}
const thermos = new Thermostat(76); // Setting in Fahrenheit scale
let temp = thermos.temperature; // 24.44 in Celsius
thermos.temperature = 26;
temp = thermos.temperature; // 26 in Celsius
//2.23 Create a Module Script
<html>
<body>
<!-- Only change code below this line -->
<script type="module" src="index.js"></script>
<!-- Only change code above this line -->
</body>
</html>
//2.24 Use export to Share a Code Block
const uppercaseString = (string) => {
return string.toUpperCase();
}
const lowercaseString = (string) => {
return string.toLowerCase()
}
export { uppercaseString, lowercaseString };
//2.25 Reuse JavaScript Code Using import
import { uppercaseString, lowercaseString } from './string_functions.js';
uppercaseString("hello");
lowercaseString("WORLD!");
//2.26 Use * to Import Everything from a File
import * as stringFunctions from "./string_functions.js";
stringFunctions.uppercaseString("hello");
stringFunctions.lowercaseString("WORLD!");
//2.27 Create an Export Fallback with export default
export default function subtract(x, y) {
return x - y;
}
//2.28 Import a Default Export
import subtract from "./math_functions.js";
// Only change code above this line
subtract(7,4);
//2.29 Create a JavaScript Promise
const makeServerRequest = new Promise((resolve, reject) => {
});
//2.30 Complete a Promise with resolve and reject
const makeServerRequest = new Promise((resolve, reject) => {
// responseFromServer represents a response from a server
let responseFromServer;
if(responseFromServer) {
resolve("We got the data");
} else {
reject("Data not received");
}
});
//2.31 Handle a Fulfilled Promise with then
const makeServerRequest = new Promise((resolve, reject) => {
// responseFromServer is set to true to represent a successful response from a server
let responseFromServer = true;
if(responseFromServer) {
resolve("We got the data");
} else {
reject("Data not received");
}
makeServerRequest.then(result => {
console.log (result)
});
});
//2.32 Handle a Rejected Promise with catch
const makeServerRequest = new Promise((resolve, reject) => {
// responseFromServer is set to false to represent an unsuccessful response from a server
let responseFromServer = false;
if(responseFromServer) {
resolve("We got the data");
} else {
reject("Data not received");
}
});
makeServerRequest.then(result => {
console.log(result);
});
makeServerRequest.catch(error => {
console.log(error);
});
//3.1 Introduction to the Regular Expression Challenges
//No task
//3.2 Using the Test Method
let myString = "Hello, World!";
let myRegex = /Hello/;
let result = myRegex.test(myString);
//3.3 Match Literal Strings
let waldoIsHiding = "Somewhere Waldo is hiding in this text.";
let waldoRegex = /Waldo/;
let result = waldoRegex.test(waldoIsHiding);
//3.4 Match a Literal String with Different Possibilities
let petString = "James has a pet cat.";
let petRegex = /dog|cat|bird|fish/;
let result = petRegex.test(petString);
//3.5 Ignore Case While Matching
let myString = "freeCodeCamp";
let fccRegex = /FreeCodeCAMP/i;
let result = fccRegex.test(myString);
//3.6 Extract Matches
let extractStr = "Extract the word 'coding' from this string.";
let codingRegex = /coding/;
let result = extractStr.match(codingRegex);
//3.7 Find More Than the First Match
let twinkleStar = "Twinkle, twinkle, little star";
let starRegex = /twinkle/gi;
let result = twinkleStar.match(starRegex);
//3.8 Match Anything with Wildcard Period
let exampleStr = "Let's have fun with regular expressions!";
let unRegex = /.un/;
let result = unRegex.test(exampleStr);
//3.9 Match Single Character with Multiple Possibilities
let quoteSample = "Beware of bugs in the above code; I have only proved it correct, not tried it.";
let vowelRegex = /[aeiou]/gi;
let result = quoteSample.match(vowelRegex);
//3.10 Match Letters of the Alphabet
let quoteSample = "The quick brown fox jumps over the lazy dog.";
let alphabetRegex = /[a-z]/gi;
let result = quoteSample.match(alphabetRegex);
//3.11 Match Numbers and Letters of the Alphabet
let quoteSample = "Blueberry 3.141592653s are delicious.";
let myRegex = /[h-s2-6]/ig;
let result = quoteSample.match(myRegex);
//3.12 Match Single Characters Specified
let quoteSample = "3 blind mice.";
let myRegex = /[^aeiou0-9]/gi;
let result = quoteSample.match(myRegex);
//3.13 Match Characters that Occur One or More Times
let difficultSpelling = "Mississippi";
let myRegex = /s+/g;
let result = difficultSpelling.match(myRegex);
//3.14 Match Characters that Occur Zero or More Times
let chewieRegex = /Aa*/;
let result = chewieQuote.match(chewieRegex);
//3.15 Find Characters with Lazy Matching
let text = "<h1>Winter is coming</h1>";
let myRegex = /<.*?>/;
let result = text.match(myRegex);
//3.16 Find One or More Criminals in a Hunt
let reCriminals = /C+/;
//3.17 Match Beginning String Patterns
let rickyAndCal = "Cal and Ricky both like racing.";
let calRegex = /^Cal/;
let result = calRegex.test(rickyAndCal);
//3.18 Match Ending String Patterns
let caboose = "The last car on a train is the caboose";
let lastRegex = /caboose$/;
let result = lastRegex.test(caboose);
//3.19 Match All Letters and Numbers
let quoteSample = "The five boxing wizards jump quickly.";
let alphabetRegexV2 = /\w/g;
let result = quoteSample.match(alphabetRegexV2).length;
//3.20 Match Everything But Letters and Numbers
let quoteSample = "The five boxing wizards jump quickly.";
let nonAlphabetRegex = /\W/g;
let result = quoteSample.match(nonAlphabetRegex).length;
//3.21 Match All Numbers
let movieName = "2001: A Space Odyssey";
let numRegex = /\d/g;
let result = movieName.match(numRegex).length;
//3.22 Match All Non-Numbers
let movieName = "2001: A Space Odyssey";
let noNumRegex = /\D/g;
let result = movieName.match(noNumRegex).length;
//3.23 Restrict Possible Usernames
let username = "JackOfAllTrades";
let userCheck = /^[a-z][a-z]+\d*$|^[a-z]\d\d+$/i;
let result = userCheck.test(username);
//3.24 Match Whitespace
let sample = "Whitespace is important in separating words";
let countWhiteSpace = /\s/g;
let result = sample.match(countWhiteSpace);
//3.25 Match Non-Whitespace Characters
let sample = "Whitespace is important in separating words";
let countNonWhiteSpace = /\S/g;
let result = sample.match(countNonWhiteSpace);
//3.26 Specify Upper and Lower Number of Matches
let ohStr = "Ohhh no";
let ohRegex = /Oh{3,6}\sno/;
let result = ohRegex.test(ohStr);
//3.27 Specify Only the Lower Number of Matches
let haStr = "Hazzzzah";
let haRegex = /Haz{4,}ah/;
let result = haRegex.test(haStr);
//3.28 Specify Exact Number of Matches
let timStr = "Timmmmber";
let timRegex = /Tim{4}ber/;
let result = timRegex.test(timStr);
//3.29 Check for All or None
let favWord = "favorite";
let favRegex = /favou?rite/;
let result = favRegex.test(favWord);
//3.30 Positive and Negative Lookahead
let sampleWord = "astronaut";
let pwRegex = /^\D(?=\w{5})(?=\w*\d{2})/;
let result = pwRegex.test(sampleWord);
//3.31 Check For Mixed Grouping of Characters
let myString = "Eleanor Roosevelt";
let myRegex = /(Franklin|Eleanor).*Roosevelt/;
let result = myRegex.test(myString);
//3.32 Reuse Patterns Using Capture Groups
let repeatNum = "42 42 42";
let reRegex = /^(\d+)\s\1\s\1$/;
let result = reRegex.test(repeatNum);
//3.33 Use Capture Groups to Search and Replace
let str = "one two three";
let fixRegex = /(\w+)\s(\w+)\s(\w+)/;
let replaceText = "$3 $2 $1";
let result = str.replace(fixRegex, replaceText);
//3.34 Remove Whitespace from Start and End
let hello = " Hello, World! ";
let wsRegex = /^\s+|\s+$/g;
let result = hello.replace(wsRegex, "");
//4.1 Introduction to the Debugging Challenges
//No Task
//4.2 Use the JavaScript Console to Check the Value of a Variable
let a = 5;
let b = 1;
a++;
console.log(a)
let sumAB = a + b;
console.log(sumAB);
//4.3 Understanding the Differences between the freeCodeCamp and Browser Console
let output = "Get this to log once in the freeCodeCamp console and twice in the browser console";
console.clear()
console.log(output)
//4.4 Use typeof to Check the Type of a Variable
let seven = 7;
let three = "3";
console.log(seven + three);
console.log(typeof(seven));
console.log(typeof(three));
//4.5 Catch Misspelled Variable and Function Names
let receivables = 10;
let payables = 8;
let netWorkingCapital = receivables - payables;
console.log(`Net working capital is: ${netWorkingCapital}`);
//4.6 Catch Unclosed Parentheses, Brackets, Braces and Quotes
let myArray = [1, 2, 3];
let arraySum = myArray.reduce((previous, current) => (previous + current));
console.log(`Sum of array values is: ${arraySum}`);
//4.7 Catch Mixed Usage of Single and Double Quotes
let innerHtml = "<p>Click here to <a href='#Home'>return home</a></p>";
console.log(innerHtml);
//4.8 Catch Use of Assignment Operator Instead of Equality Operator
let x = 7;
let y = 9;
let result = "to come";
if(x == y) {
result = "Equal!";
} else {
result = "Not equal!";
}
console.log(result);
//4.9 Catch Missing Open and Closing Parenthesis After a Function Call
function getNine() {
let x = 6;
let y = 3;
return x + y;
}
let result = getNine();
console.log(result);
//4.10 Catch Arguments in the Wrong Order When Calling a Function
function raiseToPower(b, e) {
return Math.pow(b, e);
}
let base = 2;
let exp = 3;
let power = raiseToPower(base, exp);
console.log(power);
//4.11 Catch Off By One Errors When Using Indexing
function countToFive() {
let firstFive = "12345";
let len = firstFive.length;
for (let i = 0; i < len; i++) {
console.log(firstFive[i]);
}
}
countToFive();
//4.12 Use Caution When Reinitializing Variables Inside a Loop
function zeroArray(m, n) {
let newArray = [];
for (let i = 0; i < m; i++) {
let row = [];
for (let j = 0; j < n; j++) {
row.push(0);
row.in
}
newArray.push(row);
}
return newArray;
}
let matrix = zeroArray(3, 2);
console.log(matrix);
//4.13 Prevent Infinite Loops with a Valid Terminal Condition
function myFunc() {
for (let i = 1; i <= 4; i += 2) {
console.log("Still going!");
}
}
//5.1 Introduction to the Basic Data Structure Challenges
//No Task
//5.2 Use an Array to Store a Collection of Data
let yourArray = ['one', 2, 'three', true, false, undefined, null];
//5.3 Access an Array's Contents Using Bracket Notation
let myArray = ["a", "b", "c", "d"];
myArray[1] = "not b anymore";
console.log(myArray);
//5.4 Add Items to an Array with push() and unshift()
function mixedNumbers(arr) {
arr.unshift('I', 2, 'three');
arr.push(7, 'VIII', 9 );
return arr;
}
console.log(mixedNumbers(['IV', 5, 'six']));
//5.5 Remove Items from an Array with pop() and shift()
function popShift(arr) {
let popped = arr.pop();
let shifted = arr.shift()
return [shifted, popped];
}
console.log(popShift(['challenge', 'is', 'not', 'complete']));
//5.6 Remove Items Using splice()
const arr = [2, 4, 5, 1, 7, 5, 2, 1];
arr.splice(1, 4);
console.log(arr);
//5.7 Add Items Using splice()
function htmlColorNames(arr) {
const startIndex = 0
const amountToDelete = 2
arr.splice(startIndex, amountToDelete, 'DarkSalmon', 'BlanchedAlmond');
return arr;
}
console.log(htmlColorNames(['DarkGoldenRod', 'WhiteSmoke', 'LavenderBlush', 'PaleTurquoise', 'FireBrick']));
//5.8 Copy Array Items Using slice()
function forecast(arr) {
return arr.slice(2,4);
}
console.log(forecast(['cold', 'rainy', 'warm', 'sunny', 'cool', 'thunderstorms']));
//5.9 Copy an Array with the Spread Operator
function copyMachine(arr, num) {
let newArr = [];
while (num >= 1) {
newArr.push([...arr]);
num--;
}
return newArr;
}
console.log(copyMachine([true, false, true], 2));
//5.10 Combine Arrays with the Spread Operator
function spreadOut() {
let fragment = ['to', 'code'];
let sentence = ['learning', ...fragment, 'is', 'fun'];
return sentence;
}
console.log(spreadOut());
//5.11 Check For The Presence of an Element With indexOf()
function quickCheck(arr, elem) {
let idx = arr.indexOf(elem);
if (idx >= 0) {
return true
}
return false
}
console.log(quickCheck(['squash', 'onions', 'shallots'], 'mushrooms'));
//5.12 Iterate Through All an Array's Items Using For Loops
function filteredArray(arr, elem) {
let newArr = [];
// Only change code below this line
for (let i = 0; i < arr.length; i++) {
if (arr[i].indexOf(elem) == -1) {
newArr.push(arr[i]);
}
}
// Only change code above this line
return newArr;
}
console.log(filteredArray([[3, 2, 3], [1, 6, 3], [3, 13, 26], [19, 3, 9]], 3));
//5.13 Create complex multi-dimensional arrays
let myNestedArray = [
["unshift", false, 1, 2, 3, "complex", "nested"],
["loop", "shift", 6, 7, 1000, "method"],
["concat", false, true, "spread", "array", ["deep"]],
["mutate", 1327.98, "splice", "slice", "push", [["deeper"]]],
["iterate", 1.3849, 7, "8.4876", "arbitrary", "depth", [[["deepest"]]]]
];
//5.14 Add Key-Value Pairs to JavaScript Objects
let foods = {
apples: 25,
oranges: 32,
plums: 28
};
foods['bananas'] = 13;
foods['grapes'] = 35;
foods['strawberries'] = 27;
console.log(foods);
//5.15 Modify an Object Nested Within an Object
let userActivity = {
id: 23894201352,
date: 'January 1, 2017',
data: {
totalUsers: 51,
online: 42
}
};
userActivity.data.online = 45;
console.log(userActivity);
//5.16 Access Property Names with Bracket Notation
let foods = {
apples: 25,
oranges: 32,
plums: 28,
bananas: 13,
grapes: 35,
strawberries: 27
};
function checkInventory(scannedItem) {
return foods[scannedItem]
}
console.log(checkInventory("apples"));
//5.17 Use the delete Keyword to Remove Object Properties
let foods = {
apples: 25,
oranges: 32,
plums: 28,
bananas: 13,
grapes: 35,
strawberries: 27
};
delete foods.oranges;
delete foods.plums;
delete foods.strawberries;
console.log(foods);
//5.18 Check if an Object has a Property
let users = {
Alan: {
age: 27,
online: true
},
Jeff: {
age: 32,
online: true
},
Sarah: {
age: 48,
online: true
},
Ryan: {
age: 19,
online: true
}
};
function isEveryoneHere(obj) {
if
(obj.hasOwnProperty('Alan') &&
obj.hasOwnProperty('Jeff') &&
obj.hasOwnProperty('Sarah') &&
obj.hasOwnProperty('Ryan'))
{
return true
}
return false
}
console.log(isEveryoneHere(users));
//5.19 Iterate Through the Keys of an Object with a for...in Statement
function countOnline(usersObj) {
let ctr = 0;
for (let user in usersObj) {
if (usersObj[user].online === true) {
ctr += 1;
}
}
return ctr;
}
//5.20 Generate an Array of All Object Keys with Object.keys()
let users = {
Alan: {
age: 27,
online: false
},
Jeff: {
age: 32,
online: true
},
Sarah: {
age: 48,
online: false
},
Ryan: {
age: 19,
online: true
}
};
function getArrayOfUsers(obj) {
return Object.keys(obj);
}
console.log(getArrayOfUsers(users));
//5.21 Modify an Array Stored in an Object
let user = {
name: 'Kenneth',
age: 28,
data: {
username: 'kennethCodesAllDay',
joinDate: 'March 26, 2016',
organization: 'freeCodeCamp',
friends: [
'Sam',
'Kira',
'Tomo'
],
location: {
city: 'San Francisco',
state: 'CA',
country: 'USA'
}
}
};
function addFriend(userObj, friend) {
userObj.data.friends.push(friend);
return userObj.data.friends;
}
console.log(addFriend(user, 'Pete'));
//6.1 Introduction to Basic Algorithm Scripting
//No task
//6.2 Convert Celsius to Fahrenheit
function convertToF(celsius) {
let fahrenheit;
fahrenheit = (celsius * 9/5) + 32
return fahrenheit;
}
convertToF(30);
//6.3 Reverse a String
function reverseString(str) {
var out = "";
for (var i = str.length - 1 ; i >= 0; i--) {
out += str[i];
}
return out;
}
reverseString("hello");
//6.4 Factorialize a Number
function factorialize(num) {
for (var factorial = 1; num > 0; num--) {
factorial *= num;
}
return factorial;
}
factorialize(5);
//6.5 Find the Longest Word in a String
function findLongestWordLength(str) {
var words = str.split(' ');
var maxLength = 0;
for (var i = 0; i < words.length; i++) {
if (words[i].length > maxLength) {
maxLength = words[i].length;
}
}
return maxLength;
}
console.log(findLongestWordLength("The quick brown jumps over the lazy dog"));
//6.6 Return Largest Numbers in Arrays
function largestOfFour(arr) {
var newArr = []
for (var i = 0; i < arr.length; i++) {
var maxValue = arr[i][0];
for (var j = 0; j < arr[i].length; j++) {
if (arr[i][j] > maxValue) {
maxValue = arr[i][j];
}
}
newArr.push(maxValue);
}
return newArr;
}
largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);
//6.7 Confirm the Ending
function confirmEnding(str, target) {
return str.slice(str.length - target.length) === target;
}
confirmEnding("Bastian", "n");
//6.8 Repeat a String Repeat a String
function repeatStringNumTimes(str, num) {
var repeatedString = "";
while (num > 0) {
repeatedString += str;
num--;
}
return repeatedString;
}
repeatStringNumTimes("abc", 3);
//6.9 Truncate a String
function truncateString(str, num) {
if (str.length > num) {
return str.slice(0,num) + "..."
}
return str;
}
truncateString("A-tisket a-tasket A green and yellow basket", 8);
//6.10 Finders Keepers
function findElement(arr, func) {
let num = 0;
for (var i = 0; i < arr.length; i++) {
num = arr[i];
if (func(num)) {
return num;
}
}
return undefined;
}
findElement([1, 2, 3, 4], num => num % 2 === 0);
//6.11 Boo who
function booWho(bool) {
return (typeof bool === "boolean")
}
booWho(null);
//6.12 Title Case a Sentence
function titleCase(str) {
var words = str.split(' ');
var newSentence = "";
for (var i = 0; i < words.length; i++) {
newSentence += words[i].charAt(0).toUpperCase() + words[i].slice(1).toLowerCase() + " ";
}
return newSentence.trim();
}
titleCase("I'm a little tea pot");
//6.13 Slice and Splice
function frankenSplice(arr1, arr2, n) {
var localArray = arr2.slice();
for (var i = 0; i < arr1.length; i++) {
localArray.splice(n, 0, arr1[i]);
n++;
}
return localArray;
}
frankenSplice([1, 2, 3], [4, 5, 6], 1);
//6.14 Falsy Bouncer
function bouncer(arr) {
var newArray = [];
for (var i = 0; i < arr.length; i++) {
if (Boolean(arr[i])) {
newArray.push(arr[i])
}
}
return newArray;
}
bouncer([7, "ate", "", false, 9]);
//6.15 Where do I Belong
function getIndexToIns(arr, num) {
arr.sort(function(a, b) {
return a - b;
});
for (var i = 0; i < arr.length; i++) {
if (arr[i] >= num){
return i;
}
}
return arr.length;
}
getIndexToIns([5, 3, 20, 3], 5)
//6.16 Mutations
function mutation(arr) {
var test = arr[1].toLowerCase();
var target = arr[0].toLowerCase();
for (var i = 0; i < test.length; i++) {
if (target.indexOf(test[i]) < 0) {
return false;
}
}
return true;
}
mutation(["hello", "Hello"]);
//6.17 Chunky Monkey
function chunkArrayInGroups(arr, size) {
var arr2 = [];
for (var i = 0; i < arr.length; i += size) {
arr2.push(arr.slice(i, i + size));
}
return arr2;
}
chunkArrayInGroups(["a", "b", "c", "d"], 3);
//7.1 Introduction to the Object Oriented Programming Challenges
//No tasks
//7.2 Create a Basic JavaScript Object
let dog = {
name: "Ashie",
numLegs: 4
};
//7.3 Use Dot Notation to Access the Properties of an Object
let dog = {
name: "Spot",
numLegs: 4
};
console.log(dog.name, dog.numLegs);
//7.4 Create a Method on an Object
let dog = {
name: "Spot",
numLegs: 4,
sayLegs: function() {return "This dog has "+ dog.numLegs + " legs.";}
};
dog.sayLegs();
//7.5 Make Code More Reusable with the this Keyword
let dog = {
name: "Spot",
numLegs: 4,
sayLegs: function() {return "This dog has " + this.numLegs + " legs.";}
};
dog.sayLegs();
//7.6 Define a Constructor Function
function Dog() {
this.name = "Ashie";
this.color = "white";
this.numLegs = 4;
}
//7.7 Use a Constructor to Create Objects
function Dog() {
this.name = "Rupert";
this.color = "brown";
this.numLegs = 4;
}
let hound = new Dog();
//7.8 Extend Constructors to Receive Arguments
function Dog(name, color) {
this.name = name;
this.color = color;
this.numLegs = 4;
}
let terrier = new Dog("Ashie","white");
//7.9 Verify an Object's Constructor with instanceof
function House(numBedrooms) {
this.numBedrooms = numBedrooms;
}
let myHouse = new House(3);
myHouse instanceof House;
//7.10 Understand Own Properties
function Bird(name) {
this.name = name;
this.numLegs = 2;
}
let canary = new Bird("Tweety");
let ownProps = [];
for (let property in canary) {
if(canary.hasOwnProperty(property)) {
ownProps.push(property);
}
}
//7.11 Use Prototype Properties to Reduce Duplicate Code
function Dog(name) {
this.name = name;
}
Dog.prototype.numLegs = 4;
let beagle = new Dog("Snoopy");
//7.12 Iterate Over All Properties
function Dog(name) {
this.name = name;
}
Dog.prototype.numLegs = 4;
let beagle = new Dog("Snoopy");
let ownProps = [];
let prototypeProps = [];\
for (let property in beagle) {
if(beagle.hasOwnProperty(property)) {
ownProps.push(property);
} else {
prototypeProps.push(property);
}
}
//7.13 Understand the Constructor Property
function Dog(name) {
this.name = name;
}
function joinDogFraternity(candidate) {
if (candidate.constructor === Dog) {
return true;
} else {
return false;
}
}
//7.14 Change the Prototype to a New Object
function Dog(name) {
this.name = name;
}
Dog.prototype = {
numLegs: 4,
eat: function() {
console.log("nom nom nom");
},
describe: function() {
console.log("My name is " + this.name);
}
};
//7.15 Remember to Set the Constructor Property when Changing the Prototype
function Dog(name) {
this.name = name;
}
// Only change code below this line
Dog.prototype = {
constructor: Dog,
numLegs: 4,
eat: function() {
console.log("nom nom nom");
},
describe: function() {
console.log("My name is " + this.name);
}
};
//7.16 Understand Where an Object’s Prototype Comes From
function Dog(name) {
this.name = name;
}
let beagle = new Dog("Snoopy");
Dog.prototype.isPrototypeOf(beagle);
//7.17 Understand the Prototype Chain
function Dog(name) {
this.name = name;
}
let beagle = new Dog("Snoopy");
Dog.prototype.isPrototypeOf(beagle);
Object.prototype.isPrototypeOf(Dog.prototype);
//7.18 Use Inheritance So You Don't Repeat Yourself
function Cat(name) {
this.name = name;
}
Cat.prototype = {
constructor: Cat,
};
function Bear(name) {
this.name = name;
}
Bear.prototype = {
constructor: Bear,
};
function Animal() { }
Animal.prototype = {
constructor: Animal,
eat: function() {
console.log("nom nom nom");
}
};
//7.19 Inherit Behaviors from a Supertype
function Animal() { }
Animal.prototype = {
constructor: Animal,
eat: function() {
console.log("nom nom nom");
}
};
// Only change code below this line
let duck = Object.create(Animal.prototype);
let beagle = Object.create(Animal.prototype);
//7.20 Set the Child's Prototype to an Instance of the Parent
function Animal() { }
Animal.prototype = {
constructor: Animal,
eat: function() {
console.log("nom nom nom");
}
};
function Dog() { }
Dog.prototype = Object.create(Animal.prototype);
let beagle = new Dog();
//7.21 Reset an Inherited Constructor Property
function Animal() { }
function Bird() { }
function Dog() { }
Bird.prototype = Object.create(Animal.prototype);
Dog.prototype = Object.create(Animal.prototype);
Bird.prototype.constructor = Bird;
Dog.prototype.constructor = Dog;
let duck = new Bird();
let beagle = new Dog();
//7.22 Add Methods After Inheritance
function Animal() { }
Animal.prototype.eat = function() { console.log("nom nom nom"); };
function Dog() { }
Dog.prototype = Object.create(Animal.prototype);
Dog.prototype.constructor = Dog;
Dog.prototype.bark = function() {
console.log("Woof!");
};
let beagle = new Dog();
//7.23 Override Inherited Methods
function Bird() { }
Bird.prototype.fly = function() { return "I am flying!"; };
function Penguin() { }
Penguin.prototype = Object.create(Bird.prototype);
Penguin.prototype.constructor = Penguin;
Penguin.prototype.fly = function() {
return "Alas, this is a flightless bird.";
};
let penguin = new Penguin();
console.log(penguin.fly());
//7.24 Use a Mixin to Add Common Behavior Between Unrelated Objects
let bird = {
name: "Donald",
numLegs: 2
};
let boat = {
name: "Warrior",
type: "race-boat"
};
let glideMixin = function(obj) {
obj.glide = function() {
}
};
glideMixin(bird);
glideMixin(boat);
//7.25 Use Closure to Protect Properties Within an Object from Being Modified Externally
function Bird() {
let weight = 15;
this.getWeight = function() {
return weight;
};
}
//7.26 Understand the Immediately Invoked Function Expression (IIFE)
(function () {
console.log("A cozy nest is ready");
})();
//7.27 Use an IIFE to Create a Module
let isCuteMixin = function(obj) {
obj.isCute = function() {
return true;
};
};
let singMixin = function(obj) {
obj.sing = function() {
console.log("Singing to an awesome tune");
};
};
let funModule = (function () {
return {
isCuteMixin: function(obj) {
obj.isCute = function() {
return true;
};
},
singMixin: function(obj) {
obj.sing = function() {
console.log("Singing to an awesome tune");
};
}
}
})();
//8.1 Introduction to the Functional Programming Challenges
//No tasks
//8.2 Learn About Functional Programming
// Function that returns a string representing a cup of green tea
const prepareTea = () => 'greenTea';
/*
Given a function (representing the tea type) and number of cups needed, the
following function returns an array of strings (each representing a cup of
a specific type of tea).
*/
const getTea = (numOfCups) => {
const teaCups = [];
for(let cups = 1; cups <= numOfCups; cups += 1) {
const teaCup = prepareTea();
teaCups.push(teaCup);
}
return teaCups;
};
const tea4TeamFCC = getTea(40);
//8.3 Understand Functional Programming Terminology
// Function that returns a string representing a cup of green tea
const prepareGreenTea = () => 'greenTea';
// Function that returns a string representing a cup of black tea
const prepareBlackTea = () => 'blackTea';
/*
Given a function (representing the tea type) and number of cups needed, the
following function returns an array of strings (each representing a cup of
a specific type of tea).
*/
const getTea = (prepareTea, numOfCups) => {
const teaCups = [];
for(let cups = 1; cups <= numOfCups; cups += 1) {
const teaCup = prepareTea;
teaCups.push(teaCup);
}
return teaCups;
};
const tea4GreenTeamFCC = getTea(prepareGreenTea(), 27);
const tea4BlackTeamFCC = getTea(prepareBlackTea(), 13);
console.log(
tea4GreenTeamFCC,
tea4BlackTeamFCC
);
//8.4 Understand the Hazards of Using Imperative Code
// tabs is an array of titles of each site open within the window
var Window = function(tabs) {
this.tabs = tabs; // We keep a record of the array inside the object
};
// When you join two windows into one window
Window.prototype.join = function (otherWindow) {
this.tabs = this.tabs.concat(otherWindow.tabs);
return this;
};
// When you open a new tab at the end
Window.prototype.tabOpen = function (tab) {
this.tabs.push('new tab'); // Let's open a new tab for now
return this;
};
// When you close a tab
Window.prototype.tabClose = function (index) {
// Only change code below this line
var tabsBeforeIndex = this.tabs.splice(0, index); // Get the tabs before the tab
var tabsAfterIndex = this.tabs.splice(1); // Get the tabs after the tab
this.tabs = tabsBeforeIndex.concat(tabsAfterIndex); // Join them together
// Only change code above this line
return this;
};
// Let's create three browser windows
var workWindow = new Window(['GMail', 'Inbox', 'Work mail', 'Docs', 'freeCodeCamp']); // Your mailbox, drive, and other work sites
var socialWindow = new Window(['FB', 'Gitter', 'Reddit', 'Twitter', 'Medium']); // Social sites
var videoWindow = new Window(['Netflix', 'YouTube', 'Vimeo', 'Vine']); // Entertainment sites
// Now perform the tab opening, closing, and other operations
var finalTabs = socialWindow
.tabOpen() // Open a new tab for cat memes
.join(videoWindow.tabClose(2)) // Close third tab in video window, and join
.join(workWindow.tabClose(1).tabOpen());
console.log(finalTabs.tabs);
//8.5 Avoid Mutations and Side Effects Using Functional Programming
// The global variable
var fixedValue = 4;
function incrementer () {
return fixedValue + 1;
}
//8.6 Pass Arguments to Avoid External Dependence in a Function
// The global variable
var fixedValue = 4;
function incrementer (fixedValue) {
return fixedValue + 1;
}
//8.7 Refactor Global Variables Out of Functions
// The global variable
var bookList = ["The Hound of the Baskervilles", "On The Electrodynamics of Moving Bodies", "Philosophiæ Naturalis Principia Mathematica", "Disquisitiones Arithmeticae"];
function add(arr, bookName) {
let newArr = [...arr];
newArr.push(bookName);
return newArr;
}
function remove (arr, bookName) {
let newArr = [...arr];
var book_index = newArr.indexOf(bookName);
if (book_index >= 0) {
newArr.splice(book_index, 1);
return newArr;
}
}
var newBookList = add(bookList, 'A Brief History of Time');
var newerBookList = remove(bookList, 'On The Electrodynamics of Moving Bodies');
var newestBookList = remove(add(bookList, 'A Brief History of Time'), 'On The Electrodynamics of Moving Bodies');
console.log(bookList);
//8.8 Use the map Method to Extract Data from an Array
// The global variable
var watchList = [
{
"Title": "Inception",
"Year": "2010",
"Rated": "PG-13",
"Released": "16 Jul 2010",
"Runtime": "148 min",
"Genre": "Action, Adventure, Crime",
"Director": "Christopher Nolan",
"Writer": "Christopher Nolan",
"Actors": "Leonardo DiCaprio, Joseph Gordon-Levitt, Ellen Page, Tom Hardy",
"Plot": "A thief, who steals corporate secrets through use of dream-sharing technology, is given the inverse task of planting an idea into the mind of a CEO.",
"Language": "English, Japanese, French",
"Country": "USA, UK",
"Awards": "Won 4 Oscars. Another 143 wins & 198 nominations.",
"Poster": "http://ia.media-imdb.com/images/M/MV5BMjAxMzY3NjcxNF5BMl5BanBnXkFtZTcwNTI5OTM0Mw@@._V1_SX300.jpg",
"Metascore": "74",
"imdbRating": "8.8",
"imdbVotes": "1,446,708",
"imdbID": "tt1375666",
"Type": "movie",
"Response": "True"
},
{
"Title": "Interstellar",
"Year": "2014",
"Rated": "PG-13",
"Released": "07 Nov 2014",
"Runtime": "169 min",
"Genre": "Adventure, Drama, Sci-Fi",
"Director": "Christopher Nolan",
"Writer": "Jonathan Nolan, Christopher Nolan",
"Actors": "Ellen Burstyn, Matthew McConaughey, Mackenzie Foy, John Lithgow",
"Plot": "A team of explorers travel through a wormhole in space in an attempt to ensure humanity's survival.",
"Language": "English",
"Country": "USA, UK",
"Awards": "Won 1 Oscar. Another 39 wins & 132 nominations.",
"Poster": "http://ia.media-imdb.com/images/M/MV5BMjIxNTU4MzY4MF5BMl5BanBnXkFtZTgwMzM4ODI3MjE@._V1_SX300.jpg",
"Metascore": "74",
"imdbRating": "8.6",
"imdbVotes": "910,366",
"imdbID": "tt0816692",
"Type": "movie",
"Response": "True"
},
{
"Title": "The Dark Knight",
"Year": "2008",
"Rated": "PG-13",
"Released": "18 Jul 2008",
"Runtime": "152 min",
"Genre": "Action, Adventure, Crime",
"Director": "Christopher Nolan",
"Writer": "Jonathan Nolan (screenplay), Christopher Nolan (screenplay), Christopher Nolan (story), David S. Goyer (story), Bob Kane (characters)",
"Actors": "Christian Bale, Heath Ledger, Aaron Eckhart, Michael Caine",
"Plot": "When the menace known as the Joker wreaks havoc and chaos on the people of Gotham, the caped crusader must come to terms with one of the greatest psychological tests of his ability to fight injustice.",
"Language": "English, Mandarin",
"Country": "USA, UK",
"Awards": "Won 2 Oscars. Another 146 wins & 142 nominations.",
"Poster": "http://ia.media-imdb.com/images/M/MV5BMTMxNTMwODM0NF5BMl5BanBnXkFtZTcwODAyMTk2Mw@@._V1_SX300.jpg",
"Metascore": "82",
"imdbRating": "9.0",
"imdbVotes": "1,652,832",
"imdbID": "tt0468569",
"Type": "movie",
"Response": "True"
},
{
"Title": "Batman Begins",
"Year": "2005",
"Rated": "PG-13",
"Released": "15 Jun 2005",
"Runtime": "140 min",
"Genre": "Action, Adventure",
"Director": "Christopher Nolan",
"Writer": "Bob Kane (characters), David S. Goyer (story), Christopher Nolan (screenplay), David S. Goyer (screenplay)",
"Actors": "Christian Bale, Michael Caine, Liam Neeson, Katie Holmes",
"Plot": "After training with his mentor, Batman begins his fight to free crime-ridden Gotham City from the corruption that Scarecrow and the League of Shadows have cast upon it.",
"Language": "English, Urdu, Mandarin",
"Country": "USA, UK",
"Awards": "Nominated for 1 Oscar. Another 15 wins & 66 nominations.",
"Poster": "http://ia.media-imdb.com/images/M/MV5BNTM3OTc0MzM2OV5BMl5BanBnXkFtZTYwNzUwMTI3._V1_SX300.jpg",
"Metascore": "70",
"imdbRating": "8.3",
"imdbVotes": "972,584",
"imdbID": "tt0372784",
"Type": "movie",
"Response": "True"
},
{
"Title": "Avatar",
"Year": "2009",
"Rated": "PG-13",
"Released": "18 Dec 2009",
"Runtime": "162 min",
"Genre": "Action, Adventure, Fantasy",
"Director": "James Cameron",
"Writer": "James Cameron",
"Actors": "Sam Worthington, Zoe Saldana, Sigourney Weaver, Stephen Lang",
"Plot": "A paraplegic marine dispatched to the moon Pandora on a unique mission becomes torn between following his orders and protecting the world he feels is his home.",
"Language": "English, Spanish",
"Country": "USA, UK",
"Awards": "Won 3 Oscars. Another 80 wins & 121 nominations.",
"Poster": "http://ia.media-imdb.com/images/M/MV5BMTYwOTEwNjAzMl5BMl5BanBnXkFtZTcwODc5MTUwMw@@._V1_SX300.jpg",
"Metascore": "83",
"imdbRating": "7.9",
"imdbVotes": "876,575",
"imdbID": "tt0499549",
"Type": "movie",
"Response": "True"
}
];
var ratings = watchList
.map(movie => {
return {
title: movie.Title,
rating: movie.imdbRating
};
});
console.log(JSON.stringify(ratings));
//8.9 Implement map on a Prototype
var s = [23, 65, 98, 5];
Array.prototype.myMap = function(callback) {
var newArray = [];
for (let i = 0; i < this.length; i++) {
newArray.push(callback(this[i]));
}
return newArray;
};
var new_s = s.myMap(function(item) {
return item * 2;
});
//8.10 Use the filter Method to Extract Data from an Array
// The global variable
var watchList = [
{
"Title": "Inception",
"Year": "2010",
"Rated": "PG-13",
"Released": "16 Jul 2010",
"Runtime": "148 min",
"Genre": "Action, Adventure, Crime",
"Director": "Christopher Nolan",
"Writer": "Christopher Nolan",
"Actors": "Leonardo DiCaprio, Joseph Gordon-Levitt, Ellen Page, Tom Hardy",
"Plot": "A thief, who steals corporate secrets through use of dream-sharing technology, is given the inverse task of planting an idea into the mind of a CEO.",
"Language": "English, Japanese, French",
"Country": "USA, UK",
"Awards": "Won 4 Oscars. Another 143 wins & 198 nominations.",
"Poster": "http://ia.media-imdb.com/images/M/MV5BMjAxMzY3NjcxNF5BMl5BanBnXkFtZTcwNTI5OTM0Mw@@._V1_SX300.jpg",
"Metascore": "74",
"imdbRating": "8.8",
"imdbVotes": "1,446,708",
"imdbID": "tt1375666",
"Type": "movie",
"Response": "True"
},
{
"Title": "Interstellar",
"Year": "2014",
"Rated": "PG-13",
"Released": "07 Nov 2014",
"Runtime": "169 min",
"Genre": "Adventure, Drama, Sci-Fi",
"Director": "Christopher Nolan",
"Writer": "Jonathan Nolan, Christopher Nolan",
"Actors": "Ellen Burstyn, Matthew McConaughey, Mackenzie Foy, John Lithgow",
"Plot": "A team of explorers travel through a wormhole in space in an attempt to ensure humanity's survival.",
"Language": "English",
"Country": "USA, UK",
"Awards": "Won 1 Oscar. Another 39 wins & 132 nominations.",
"Poster": "http://ia.media-imdb.com/images/M/MV5BMjIxNTU4MzY4MF5BMl5BanBnXkFtZTgwMzM4ODI3MjE@._V1_SX300.jpg",
"Metascore": "74",
"imdbRating": "8.6",
"imdbVotes": "910,366",
"imdbID": "tt0816692",
"Type": "movie",
"Response": "True"
},
{
"Title": "The Dark Knight",
"Year": "2008",
"Rated": "PG-13",
"Released": "18 Jul 2008",
"Runtime": "152 min",
"Genre": "Action, Adventure, Crime",
"Director": "Christopher Nolan",
"Writer": "Jonathan Nolan (screenplay), Christopher Nolan (screenplay), Christopher Nolan (story), David S. Goyer (story), Bob Kane (characters)",
"Actors": "Christian Bale, Heath Ledger, Aaron Eckhart, Michael Caine",
"Plot": "When the menace known as the Joker wreaks havoc and chaos on the people of Gotham, the caped crusader must come to terms with one of the greatest psychological tests of his ability to fight injustice.",
"Language": "English, Mandarin",
"Country": "USA, UK",
"Awards": "Won 2 Oscars. Another 146 wins & 142 nominations.",
"Poster": "http://ia.media-imdb.com/images/M/MV5BMTMxNTMwODM0NF5BMl5BanBnXkFtZTcwODAyMTk2Mw@@._V1_SX300.jpg",
"Metascore": "82",
"imdbRating": "9.0",
"imdbVotes": "1,652,832",
"imdbID": "tt0468569",
"Type": "movie",
"Response": "True"
},
{
"Title": "Batman Begins",
"Year": "2005",
"Rated": "PG-13",
"Released": "15 Jun 2005",
"Runtime": "140 min",
"Genre": "Action, Adventure",
"Director": "Christopher Nolan",
"Writer": "Bob Kane (characters), David S. Goyer (story), Christopher Nolan (screenplay), David S. Goyer (screenplay)",
"Actors": "Christian Bale, Michael Caine, Liam Neeson, Katie Holmes",
"Plot": "After training with his mentor, Batman begins his fight to free crime-ridden Gotham City from the corruption that Scarecrow and the League of Shadows have cast upon it.",
"Language": "English, Urdu, Mandarin",
"Country": "USA, UK",
"Awards": "Nominated for 1 Oscar. Another 15 wins & 66 nominations.",
"Poster": "http://ia.media-imdb.com/images/M/MV5BNTM3OTc0MzM2OV5BMl5BanBnXkFtZTYwNzUwMTI3._V1_SX300.jpg",
"Metascore": "70",
"imdbRating": "8.3",
"imdbVotes": "972,584",
"imdbID": "tt0372784",
"Type": "movie",
"Response": "True"
},
{
"Title": "Avatar",
"Year": "2009",
"Rated": "PG-13",
"Released": "18 Dec 2009",
"Runtime": "162 min",
"Genre": "Action, Adventure, Fantasy",
"Director": "James Cameron",
"Writer": "James Cameron",
"Actors": "Sam Worthington, Zoe Saldana, Sigourney Weaver, Stephen Lang",
"Plot": "A paraplegic marine dispatched to the moon Pandora on a unique mission becomes torn between following his orders and protecting the world he feels is his home.",
"Language": "English, Spanish",
"Country": "USA, UK",
"Awards": "Won 3 Oscars. Another 80 wins & 121 nominations.",
"Poster": "http://ia.media-imdb.com/images/M/MV5BMTYwOTEwNjAzMl5BMl5BanBnXkFtZTcwODc5MTUwMw@@._V1_SX300.jpg",
"Metascore": "83",
"imdbRating": "7.9",
"imdbVotes": "876,575",
"imdbID": "tt0499549",
"Type": "movie",
"Response": "True"
}
];
var filteredList = watchList
.map(movie => {
return {
title: movie.Title,
rating: movie.imdbRating
};
})
.filter(movie => {
return parseFloat(movie.rating) >= 8.0;
});
console.log(filteredList);
//8.11 Implement the filter Method on a Prototype
// The global variable
var s = [23, 65, 98, 5];
Array.prototype.myFilter = function(callback) {
var newArray = [];
for (let i = 0; i < this.length; i++) {
if (callback(this[i]) === true) {
newArray.push(this[i]);
}
}
return newArray;
};
var new_s = s.myFilter(function(item) {
return item % 2 === 1;
});
//8.12 Return Part of an Array Using the slice Method
function sliceArray(anim, beginSlice, endSlice) {
var newArray = anim.slice(beginSlice, endSlice);
return newArray;
}
var inputAnim = ["Cat", "Dog", "Tiger", "Zebra", "Ant"];
sliceArray(inputAnim, 1, 3);
//8.13 Remove Elements from an Array Using slice Instead of splice
function nonMutatingSplice(cities) {
var newArray = cities.slice(0, 3);
return newArray;
}
var inputCities = ["Chicago", "Delhi", "Islamabad", "London", "Berlin"];
nonMutatingSplice(inputCities);
//8.14 Combine Two Arrays Using the concat Method
function nonMutatingConcat(original, attach) {
return original.concat(attach)
}
var first = [1, 2, 3];
var second = [4, 5];
nonMutatingConcat(first, second);
//8.15 Add Elements to the End of an Array Using concat Instead of push
function nonMutatingPush(original, newItem) {
return original.concat(newItem);
}
var first = [1, 2, 3];
var second = [4, 5];
nonMutatingPush(first, second);
//8.16 Use the reduce Method to Analyze Data
// The global variable
var watchList = [
{
"Title": "Inception",
"Year": "2010",
"Rated": "PG-13",
"Released": "16 Jul 2010",
"Runtime": "148 min",
"Genre": "Action, Adventure, Crime",
"Director": "Christopher Nolan",
"Writer": "Christopher Nolan",
"Actors": "Leonardo DiCaprio, Joseph Gordon-Levitt, Ellen Page, Tom Hardy",
"Plot": "A thief, who steals corporate secrets through use of dream-sharing technology, is given the inverse task of planting an idea into the mind of a CEO.",
"Language": "English, Japanese, French",
"Country": "USA, UK",
"Awards": "Won 4 Oscars. Another 143 wins & 198 nominations.",
"Poster": "http://ia.media-imdb.com/images/M/MV5BMjAxMzY3NjcxNF5BMl5BanBnXkFtZTcwNTI5OTM0Mw@@._V1_SX300.jpg",
"Metascore": "74",
"imdbRating": "8.8",
"imdbVotes": "1,446,708",
"imdbID": "tt1375666",
"Type": "movie",
"Response": "True"
},
{
"Title": "Interstellar",
"Year": "2014",
"Rated": "PG-13",
"Released": "07 Nov 2014",
"Runtime": "169 min",
"Genre": "Adventure, Drama, Sci-Fi",
"Director": "Christopher Nolan",
"Writer": "Jonathan Nolan, Christopher Nolan",
"Actors": "Ellen Burstyn, Matthew McConaughey, Mackenzie Foy, John Lithgow",
"Plot": "A team of explorers travel through a wormhole in space in an attempt to ensure humanity's survival.",
"Language": "English",
"Country": "USA, UK",
"Awards": "Won 1 Oscar. Another 39 wins & 132 nominations.",
"Poster": "http://ia.media-imdb.com/images/M/MV5BMjIxNTU4MzY4MF5BMl5BanBnXkFtZTgwMzM4ODI3MjE@._V1_SX300.jpg",
"Metascore": "74",
"imdbRating": "8.6",
"imdbVotes": "910,366",
"imdbID": "tt0816692",