This Is All Commented Console - Log (10) None of This Is Going To Run! Console - Log (99)
This Is All Commented Console - Log (10) None of This Is Going To Run! Console - Log (99)
Comment:
/*This is all commented console.log(10);None of this is going to run!
console.log(99);*/
//for single line comment
console.log(22+3.5);
console.log(2020-1969);
console.log(65/240);
console.log(0.2708*100);
console.log('Hello' + 'World');
console.log('Hello'+ ' ' + 'World');
console.log('Teaching the world how to code'.length);
console.log('Codecademy'.toUpperCase());
console.log(' Remove whitespace '.trim());
console.log(Math.floor(Math.random() * 100));
console.log(Math.ceil(43.8));//returns the smallest integer greater tha
n or equal to a decimal number
console.log(Number.isInteger(2017));//if it is integer or not
var favoriteFood ='pizza';
var numOfSlices=8;
console.log(favoriteFood);
console.log(numOfSlices);
const entree='Enchiladas';
console.log(entree);
entree = 'Tacos';
let levelUp = 10;
levelUp+=5;
let powerLevel = 9001;
powerLevel-=100;
let multiplyMe = 32;
multiplyMe*=11;
let quarterMe = 1152;
quarterMe/=4;
let gainedDollar = 3;
gainedDollar++;
let lostDollar = 50;
lostDollar--;
let favoriteAnimal = "giraffe";
console.log("My favorite animal: " + favoriteAnimal);
String Interpolation
let myName = 'Natalia';
let myCity = 'Mexico City';
console.log(`My name is ${myName}. My favorite city is ${myCity}.`)
let newVariable = 'Playing around with typeof.';
console.log(typeof(newVariable));
newVariable=1;
console.log(typeof(newVariable));
let sale = true;
sale = false;
if(sale) {
console.log('Time to buy!');
}
else{
console.log('Time to wait for a sale.');
}
let mood = 'sleepy';
let tirednessLevel = 6;
if(mood==='sleepy' && tirednessLevel>8){
console.log('time to sleep');
}
else{
console.log('not bed time yet');
}
if (wordCount) {
console.log("Great! You've started your work!");
} else {
console.log('Better get to work!');
}
let favoritePhrase = '';
if (favoritePhrase) {
console.log("This string doesn't seem to be empty.");
} else {
console.log('This string is definitely empty.');
}
Example 2:
let tool = 'marker';
// Use short circuit evaluation to assign writingUtensil variable belo
w:
let writingUtensil=tool || 'pen';
console.log(`The ${writingUtensil} is mightier than the sword.`);
let tool = 'marker';
// Use short circuit evaluation to assign writingUtensil variable belo
w:
let writingUtensil=tool || 'pen';
console.log(`The ${writingUtensil} is mightier than the sword.`);
Ternary operator:
let isNightTime = true; isNightTime ? console.log('Turn
if (isNightTime) { on the lights!') :
console.log('Turn on the console.log('Turn off the
lights!'); lights!');
} else {
console.log('Turn off the
lights!');
}
let season = 'summer';
if (season === 'spring') {
console.log('It\'s spring! The trees are budding!');
}
else if(season === 'winter'){
console.log('It\'s winter! Everything is covered in snow.');
}
else if(season === 'fall'){
console.log('It\'s fall! Leaves are falling!');
}
else if(season==='summer'){
console.log('It\'s sunny and warm because it\'s summer!');
}
else {
console.log('Invalid season.');
}
Switch statement;
et athleteFinalPosition = 'first place';
switch(athleteFinalPosition){
case 'first place':
console.log('You get the gold medal!');
break;
case 'second place':
console.log('You get the silver medal!');
break;
case 'third place':
console.log('You get the bronze medal!');
break;
default:
console.log('No medal awarded.');
break;
}
Function:
function getReminder(){
console.log('Water the plants.');
}
function greetInSpanish(){
console.log('Buenas Tardes.');
}
Call function:
function sayThanks(){
console.log('Thank you for your purchase! We appreciate your business
.');
}
sayThanks();
sayThanks();
sayThanks();
Using a parameter;
function sayThanks(name) {
console.log('Thank you for your purchase '+name+'! We appreciate your
business.');
}
Default parameters;
function makeShoppingList(item1 = 'milk', item2 = 'bread', item3 = 'egg
s'){
console.log(`Remember to buy ${item1}`);
console.log(`Remember to buy ${item2}`);
console.log(`Remember to buy ${item3}`);
}
Return :
function monitorCount(rows,columns){
return rows*columns;
}
const numOfMonitors=monitorCount(5,4);
console.log(numOfMonitors);
Helper function
function monitorCount(rows, columns) {
return rows * columns;
}
function costOfMonitors(rows,columns){
return monitorCount(rows, columns) *200;
}
const totalCost=costOfMonitors(5,4);
Function expression;
const plantNeedsWater = function(day) {
if(day === 'Wednesday'){
return true;
} else {
return false;
}
};
plantNeedsWater('Tuesday');
console.log(plantNeedsWater('Tuesday'));
Arrow functions remove the need to type out the keyword function every time you
need to create a function. Instead, you first include the parameters inside the ( )
and then add an arrow => that points to the function body surrounded in { } like
this:
1.
Functions that take only a single parameter do not need that parameter to be
enclosed in parentheses. However, if a function takes zero or multiple
parameters, parentheses are required.
2.
const hobbies=['sleep','eat','play
'];
console.log(hobbies);
const famousSayings = ['Fortune favors the brave.', 'A joke is a very s
erious thing.', 'Where there is love there is life.'];
let listItem=famousSayings[0];
console.log(listItem);
console.log(famousSayings[2]);
console.log(famousSayings[3]);
famousSayings[0]=’sleep tight’;
Concise body arrow unctions:
The most condensed form of the function is known as concise body.
Functions that const greaterThanFive = (num) => {
take only a return num > 5 ? true : false;
single parameter };
do not need that const greaterThanFive = num => num > 5 ? true :
parameter to be false;
enclosed in
parentheses.
However, if a
function takes
zero or multiple
parameters,
parentheses are
required.
A function body const plantNeedsWater = day => day === 'Wednesday'
composed of a ? true : false;
single-line block
;
does not need
curly braces.
Without the curly
braces, whatever
that line
evaluates will be
automatically
returned. The
contents of the
block should
immediately
follow the arrow
=> and the return
keyword can be
removed. This is
referred to as
implicit return
const logCitySkyline = () => {
let skyscraper = 'Empire State Building';
return 'The stars over the ' + skyscraper + ' in ' + city;
};
console.log(logCitySkyline());
console.log(color);
// blue
};
logSkyColor(); //
blue
console.log(color);
// ReferenceError
const chores = ['wash dishes', 'do laundry', 'take out trash'];
chores.push('buy medicines','take a nap');
console.log(chores);
const chores = ['wash dishes', 'do laundry', 'take out trash', 'cook di
nner', 'mop floor'];
chores.pop(4);
console.log(chores.pop(4));
Some arrays methods that are available to JavaScript developers
include: .join(), .slice(), .splice(), .shift(), .unshift(), and
.concat()
const groceryList = ['orange juice', 'bananas', 'coffee beans', 'brown
rice', 'pasta', 'coconut oil', 'plantains'];
groceryList.shift();//remove first item from array
console.log(groceryList);
groceryList.unshift('popcorn');//begining of grocery list
console.log(groceryList);
console.log(groceryList.slice(1, 4));//add few more
console.log(groceryList);
const pastaIndex = groceryList.indexOf('pasta');
console.log(pastaIndex);
//function and array
const concept = ['arrays', 'can', 'be', 'mutated'];
function changeArr(arr){
arr[3] = 'MUTATED';
}
changeArr(concept);
console.log(concept);
function removeElement(newArr){
newArr.pop();
}
removeElement(concept);
console.log(concept);
const numberClusters = [[1, 2], [3, 4], [5, 6]];
For loop;
// Write your code below
for(let counter=5;counter<11;counter++) {
console.log(counter);
}
// The loop below loops from 0 to 3. Edit it to loop backwards from 3 t
o 0
for (let counter = 3; counter >= 0; counter--){
console.log(counter);
}
const vacationSpots = ['Bali', 'Paris', 'Tulum'];
// Write your code below
for(let i=0;i < vacationSpots.length;i++){
console.log('I would love to visit '+vacationSpots[i]);
}
for (let i = 0; i < bobsFollowers.length; i++) {
for (let j = 0; j < tinasFollowers.length; j++) {
if (bobsFollowers[i] === tinasFollowers[j]) {
mutualFollowers.push(bobsFollowers[i]);
}
}
};
While loop:
const cards = ['diamond', 'spade', 'heart', 'club'];
// Write your code below
let currentCard;
while(currentCard!='spade'){
currentCard = cards[Math.floor(Math.random() * 4)];
console.log(currentCard);
}
Do-while:
// Write your code below
let cupsOfSugarNeeded=2;
let cupsAdded=0;
do{
cupsAdded++
}
while(cupsAdded<cupsOfSugarNeeded);
const rapperArray = ["Lil' Kim", "Jay-Z", "Notorious B.I.G.", "Tupac"];
What if we wanted to rename this function without sacrificing the source code? We
can re-assign the function to a variable with a suitably short name:
busy is a variable that holds a reference to our original function. If we could look up
the address in memory of busy and the address in memory of
announceThatIAmDoingImportantWork they would point to the same place. Our
new busy() function can be invoked with parentheses as if that was the name we
originally gave our function.
Function as a DATA:
const checkThatTwoPlusTwoEqualsFourAMillionTimes = () => {
for(let i = 1; i <= 1000000; i++) {
if ( (2 + 2) != 4) {
console.log('Something has gone very wrong :( ');
}
}
};
// Write your code below
const is2p2 = checkThatTwoPlusTwoEqualsFourAMillionTimes;
is2p2();
console.log(is2p2.name);
const checkThatTwoPlusTwoEqualsFourAMillionTimes = () => {
for(let i = 1; i <= 1000000; i++) {
if ( (2 + 2) != 4) {
console.log('Something has gone very wrong :( ');
}
}
};
const addTwo = num => num + 2;
const timeFuncRuntime = funcParameter => {
let t1 = Date.now();
funcParameter();
let t2 = Date.now();
return t2 - t1;
};
// Write your code below
const time2p2 = timeFuncRuntime(checkThatTwoPlusTwoEqualsFourAMillionTi
mes);
//Save a variable, time2p2. Assign as its value the result of invoking
the timeFuncRuntime() function with the checkThatTwoPlusTwoEqualsFourAM
illionTimes() function.
const checkConsistentOutput = (func, val) => {
let firstTry = func(val);
let secondTry = func(val);
if (firstTry === secondTry) {
return firstTry
} else {
return 'This function returned inconsistent results'
}
};
checkConsistentOutput(addTwo, 10);
Abstraction allows us to write complicated code in a way that’s easy
to reuse, debug, and understand for human readers
We can work with functions the same way we would any other type of
data including reassigning them to new variables
JavaScript functions are first-class objects, so they have properties
and methods like any object
Functions can be passed into other functions as parameters
A higher-order function is a function that either accepts functions
as parameters, returns a function, or both
1. .forEach()
· .forEach() loops through the array and executes the callback function for each element.
During each execution, the current element is passed as an argument to the callback function.
· The return value for .forEach() will always be undefined.
const fruits = ['mango', 'papaya', 'pineapple', 'apple'];
// Iterate over fruits array to log I want to eat a plus the name of ea
ch fruit to the console. For example, I want to eat a mango.
fruits.forEach(fruit => console.log(`I want to eat a ${fruit}.`))
2. .map():
le', 'octopus', 'rabbit', 'lion', 'dog'];
// Use .map() to create a new array that contains the first character o
f each string in the animals array. Save the new array to a const varia
ble named secretMessage.
const secretMessage=animals.map(animal => {
return animal[0];
});
console.log(secretMessage.join(''));
const bigNumbers = [100, 200, 300, 400, 500];
// Create the smallNumbers array below to divide all the numbers in big
Numbers by 100
const smallNumbers=bigNumbers.map(num =>{
return num/100;
});
3. Filter()
Returns an array of elements after filtering out certain elements from original
array..filter() method should return true or false depending on the
element that is passed to it.
const randomNumbers = [375, 200, 3.14, 7, 13, 852];
// Call .filter() on randomNumbers below
const smallNumbers=randomNumbers.filter(num => {
return num < 250;
});
const favoriteWords = ['nostalgia', 'hyperbole', 'fervent', 'esoteric',
'serene'];
// Call .filter() on favoriteWords below
const longFavoriteWords=favoriteWords.filter(num2 =>{
return num2.length>7;
})
const foundAnimal = animals.findIndex(animal => {
return animal === 'elephant';
});
const startsWithS = animals.findIndex(animal => {
return animal[0] === 's' ? true : false;
});
5. Reduce():
const newNumbers = [1, 3, 5, 7];
const newSum = newNumbers.reduce((accumulator, currentValue) => {
console.log('The value of accumulator: ', accumulator);
console.log('The value of currentValue: ', currentValue);
return accumulator + currentValue;
}, 10);
console.log(newSum);
Iterator documenatation;
const words = ['unique', 'uncanny', 'pique', 'oxymoron', 'guise'];
// Something is missing in the method call below
console.log(words.some(word => {
return word.length < 6;
}));
// Use filter to create a new array
const interestingWords = words.filter((word) => {return word.length > 5
});
// Make sure to uncomment the code below and fix the incorrect code bef
ore running it
console.log(interestingWords.every((word) => {return word.length > 5}))
;
const cities = ['Orlando', 'Dubai', 'Edinburgh', 'Chennai', 'Accra', 'D
enver', 'Eskisehir', 'Medellin', 'Yokohama'];
const nums = [1, 50, 75, 200, 350, 525, 1000];
// Choose a method that will return undefined
cities.forEach(city => console.log('Have you visited ' + city + '?'));
// Choose a method that will return a new array
const longCities = cities.filter(city => city.length > 7);
// Choose a method that will return a single value
const word = cities.reduce((acc, currVal) => {
return acc + currVal[0]
}, "C");
console.log(word)
// Choose a method that will return a new array
const smallerNums = nums.map(num => num - 5);
// Choose a method that will return a boolean value
nums.every(num => num < 0);
// OR nums.some(num => num < 0);
· .forEach() is used to execute the same code on every element in an array but does not
change the array and returns undefined.
· .map() executes the same code on every element in an array and returns a new array with the
updated elements.
· .filter() checks every element in an array to see if it meets certain criteria and returns a
new array with the elements that return truthy for the criteria.
· .findIndex() returns the index of the first element of an array which satisfies a condition in
the callback function. It returns -1 if none of the elements in the array satisfies the condition.
· .reduce() iterates through an array and takes the values of the elements and returns a single
value.
· All iterator methods takes a callback function that can be pre-defined, or a function expression,
or an arrow function.
Introduction to objects:
7 fundamental datatypes in javascript; string,number,boolean,null,undefind and
symbol and seventh type objects.
let spaceship = {}; // spaceship is an empty object has key and value
let spaceship = {
'Fuel Type': 'diesel',
color: 'silver'
};
Accessing properties: examples
With the property of dot notation, we let spaceship = {
write the object’s name, followed by dot
operator and then property name(key): homePlanet: 'Earth',
color: 'silver',
'Fuel Type': 'Turbo Fuel',
numCrew: 5,
let spaceship = {
homePlanet: 'Earth', flightPath: ['Venus', 'Mars', 'Saturn'
color: 'silver' ]
};spaceship.homePlanet; // };
Returns
'Earth',spaceship.color; //
Returns 'silver', // Write your code below
let crewCount=spaceship.numCrew;
let planetArray=spaceship.flightPath;
let returnAnyProp =
(objectName, propName) =>
objectName[propName];
returnAnyProp(spaceship,
'homePlanet'); // Returns
'Earth'
// Write your code below
spaceship.color='glorious gold';
spaceship.numEngines=8;
delete spaceship['Secret Mission'];
Methods: let retreatMessage = 'We no longer wish
When the data stored on an object is a
function we call that a method. to conquer your planet. It is full of do
A property is what an object gs, which we do not care for.';
has, while a method is what
an object does. let alienShip = {
retreat() {
console.log(retreatMessage)
},
takeOff() {
console.log('Spim... Borp... Glix...
Blastoff!')
}
};
//invoke methods
alienShip.retreat();
alienShip.takeOff();
Nested object let spaceship = {
:Create a variablecapFave
passengers: [{name: 'Space Dog'}],
and assign the captain‘s
telescope: {
favorite food (the element
in the 0th index of her yearBuilt: 2018,
'favorite foods' array) to model: "91031-XLT",
it. Make sure to use bracket focalLength: 2032
and dot notation to get the },
value of the food through
crew: {
nested access (don’t just
copy the value into the captain: {
variable!) name: 'Sandra',
degree: 'Computer Engineering',
encourageTeam() { console.log('We
got this!') },
'favorite foods': ['cookies', 'cake
s', 'candy', 'spinach'] }
},
engine: {
model: "Nimbus2000"
},
nanoelectronics: {
computer: {
terabytes: 100,
monitors: "HD"
},
'back-up': {
battery: "Lithium",
terabytes: 50
}
}
};
let capFave = spaceship.crew.captain['fa
vorite foods'][0];
let firstPassenger = spaceship.passenger
s[0];
remotelyDisable(spaceship);
console.log(spaceship)
// Using for...in, iterate through the s
paceship.crew object in the code editor
and console.log() a list of crew roles a
nd names in the following format: '[crew
member's role]: [crew member's name]', e
.g.,'chief officer: Dan
for (let crewMember in spaceship.crew) {
console.log(`${crewMember}: $
{spaceship.crew[crewMember].name}`)
};
for (let crewMember in spaceship.crew) {
console.log(`$
{spaceship.crew[crewMember].name}: $
{spaceship.crew[crewMember].degree}`)
};