You are on page 1of 23

Useful links.

https://developer.mozilla.org/en-US/docs/Web/JavaScript
https://replit.com/
https://caniuse.com/
https://stackoverflow.com/
https://dev.to/
https://css-tricks.com/
https://www.w3.org/TR/CSS2/selector.html
https://developer.mozilla.org/en-US/

Console refers to an object. console.log() whatever is inside the parentheses will get printed or logged to
the console.

Semicolon ends lines like other languages ;

// is a single line comment. can also use after a line of code.

/* */ is a multi line comment.

7 fundamental data types in JS.

Number - Any Decimal.


String: Any grouping of characters.
Boolean - true or false.
null.
Undefined.
Symbol. used in more complex coding
Object - collections of data

+ - % / %remainder.

you can also concatenate strings together using function signs.

. dot operator, example console.log('Hello'.length);

Var- short for variable.

Let variable will set a variable that can later be changed.


Let can be used in blocks for temporary changes.

Const = constant variable cant change


a template literal is wrapped by back ticks ` aka tilde key but not tilde.
var myName = 'Luke';

var myCity = 'Wildomar';

console.log(`My name is ${myName}. My favorite city is ${myCity}`);

typeof can be used to check the type of variables.

string interpolation uses the $ equation. String concenation is the math symbols.

// Kelvin forecast is 293 and will be converted into celsius.

const kelvin = 0;

// Creating a variable for celsius and implementing its type.

var celsius = kelvin - 273;

var newtwon = celsius *(33/100);

newton = Math.floor(celsius);

// Setting farenheit.

var fahrenheit = celsius * (9/5) + 32;

fahrenheit = Math.floor(fahrenheit);

console.log(`The temperature is ${newton} degrees Fahrenheit.`);

----------------------------------------------

var myAge = 28; // This is my age.

let earlyYears = 2; // Setting the value of the early years.

earlyYears *= 10.5;

let laterYears = myAge - 2; // setting = to my age - 2

laterYears *= 4; // accounting for dog years.

var myAgeInDogYears = earlyYears + laterYears; // setting a variable = to my age in dog years.

var myName = 'Luke Lippincott'.toLowerCase(); // setting my name.

console.log(`My name is ${myName}. I am ${myAge} years old in human years which is $


{myAgeInDogYears} years old in dog years.`) // saying my name, age, and age in dog years.
----------------------------------------------------------------

If statements.

if (true) {

console.log('This message will print!');

// Prints: This message will print!

Instead of using true or false you can use a variable name which is set to true or false.

if (false) {

console.log('The code in this block will not run.');

} else {

console.log('But the code in this block will!');

// Prints: But the code in this block will!

Less than: <

Greater than: >

Less than or equal to: <=

Greater than or equal to: >=

Is equal to: === also checks type.

Is not equal to: !== also check types.

the and operator (&&)

the or operator (||)

the not operator, otherwise known as the bang operator (!)

truthy values exist, falsy values are empty strings, nulls, 0s,
let defaultName;

if (username) {

defaultName = username;

} else {

defaultName = 'Stranger';

let isNightTime = true;

if (isNightTime) {

console.log('Turn on the lights!');

} else {

console.log('Turn off the lights!');

We can use a ternary operator to perform the same functionality:

isNightTime ? console.log('Turn on the lights!') : console.log('Turn off the lights!');

let favoritePhrase = 'Love That!';

favoritePhrase ==="Love That!" ? console.log('I love that!')

: console.log("I don't love that!");

let groceryItem = 'papaya';

switch (groceryItem) {

case 'tomato':
console.log('Tomatoes are $0.49');

break;

case 'lime':

console.log('Limes are $1.49');

break;

case 'papaya':

console.log('Papayas are $1.29');

break;

default:

console.log('Invalid item');

break;

--------------------------------------

let 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;

}}------------------------------------

----------------------------------------------------------------------------------------------------------------

Eightball project....

var userName = "Luke";

userName ? console.log(`Hello, ${userName}!`) : console.log('Hello!');

const userQuestion = 'Will I finish this course?';

console.log(`${userName} You asked "${userQuestion}"`);

var randomNumber = Math.floor(Math.random() * 8);

var eightBall ="";

switch (randomNumber) {

case 0:

eightBall='It is certain'

break;

case 1:

eightBall='It is decidedly so'

break;

case 2:

eightBall='Reply hazy try again'

break;

case 3:

eightBall='Cannot predict now'

break;
case 4:

eightBall='Do not count on it'

break;

case 5:

eightBall='My sources say no'

break;

case 6:

eightBall='Outlook not so good'

break;

case 7:

eightBall='Signs point to yes'

break;

default:

console.log('Most Definately')

break;

console.log(eightBall)

---------------------------------------------------------------------------------------------------------

Race day project.......

let raceNumber = Math.floor(Math.random() * 1000);

var runnerEarly = false;

var runnerAge = 18;

if (runnerAge > 18 && runnerEarly === true)

raceNumber += 1000;

if (runnerAge > 18 && runnerEarly === true) {


console.log(`You will race at 9:30 am ${raceNumber}`);

} else if (runnerAge > 18 && runnerEarly === false) {

console.log(`Late adults run at 11:00 am ${raceNumber}`);

} else if (runnerAge < 18) {

console.log(`Youth registrants run at 12:30 pm (regardless of registration) ${raceNumber}`);

} else {

console.log('You are exactly 18, please see the registration desk.');

---------------------------------------------------------------------------------------------------

Functions.

When first learning how to calculate the area of a rectangle, there’s a sequence of steps to calculate the
correct answer:

Measure the width of the rectangle.

Measure the height of the rectangle.

Multiply the width and height of the rectangle.

A function declaration consists of:

The function keyword.

The name of the function, or its identifier, followed by parentheses.

A function body, or the block of statements required to perform a specific task, enclosed in the
function’s curly brackets, { }.

greetWorld(); // Output: Hello, World!

function greetWorld() {

console.log('Hello, World!');
}

Hoisting is the act of calling the function before it is declared as shwon above ^.

To call a function in your code, you type the function name followed by parentheses.

greetWorld();

string concatnetation is combining strings, string interpolation is adding the $

function makeShoppingList(item1 = 'milk', item2 = 'bread', item3 = 'eggs'){

console.log(`Remember to buy ${item1}`);

console.log(`Remember to buy ${item2}`);

console.log(`Remember to buy ${item3}`);

}
Assigning default values to function parameters. in this case it will default item 1 to milk, 2 to bread, and
so on.

return keyword is how we get data back out of functions.

function monitorCount(rows, columns){

return rows * columns;

const numOfMonitors = monitorCount(5, 4);

console.log(numOfMonitors);

In this example we set the constant of numOfMonitors using the monitorCount function and passing it
an equation.

Helper Functions

We can also use the return value of a function inside another function. These functions being called
within another function are often referred to as helper functions. Since each function is carrying out a
specific task, it makes our code easier to read and debug if necessary.
function multiplyByNineFifths(number) {

return number * (9/5);


};

function getFahrenheit(celsius) {

return multiplyByNineFifths(celsius) + 32;

};

getFahrenheit(15); // Returns 59

function monitorCount(rows, columns) {

return rows * columns;

function costOfMonitors(rows, columns){

return monitorCount(rows, columns) * 200;

const totalCost = costOfMonitors(5, 4);

console.log(totalCost);

const plantNeedsWater = function(day){ // setting a anonymous function.

if (day === 'Wednesday') // simple if else check for a single day

return true;

else {

return false;

console.log(plantNeedsWater('Tuesday')); // checking to make sure the if else statement functions


properly.
Arrow Functions
ES6 introduced arrow function syntax, a shorter way to write functions by using the special “fat arrow” ()
=> notation.

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:

const rectangleArea = (width, height) => {

let area = width * height;

return area;

};
-------------------------------------------------------

So if we have a function:

const squareNum = (num) => {

return num * num;

};

We can refactor the function to:

const squareNum = num => num * num;

-----------------------------------------------------------

const plantNeedsWater = day) => {

return day === 'Wednesday' ? true : false;

};
would then become

const plantNeedsWater = day => day === 'Wednesday' ? true : false;


---------------------------------------------------------------------------------------------------

Rock paper scissors project.

const getUserChoice = (userInput) => {

userInput = userInput.toLowerCase();

if (userInput === 'rock' || userInput === 'paper' || userInput === 'scissors') {

return userInput;

} else if (userInput === 'bomb') {

return userInput;

else {

console.log('Error!');

const getComputerChoice = () => {

randomNumber = Math.floor(Math.random() * 3);

switch (randomNumber) {

case 0:

return 'rock';

case 1:

return 'paper';

case 2:

return 'scissors';

}
}

const determineWinner = (userChoice, computerChoice) => {

if (userChoice === computerChoice) {

return 'The game is a tie!'

if (userChoice === 'rock') {

if (computerChoice === 'paper') {

return 'The computer won!'

} else {

return 'You won!';

if (userChoice === 'paper') {

if(computerChoice === 'scissors') {

return 'The computer won!'

} else {

return 'You won!';

if (userChoice === 'scissors') {

if (computerChoice === 'rock'){

return 'The computer won!'

} else {

return 'You won!';

}
}

if (userChoice === 'bomb') {

return "You've activated my trap card! You win!";

const playGame = () => {

const userChoice = getUserChoice('bomb');

const computerChoice = getComputerChoice();

console.log('You threw: ' + userChoice);

console.log('The computer threw:' + computerChoice);

console.log(determineWinner(userChoice, computerChoice));

playGame();

-------------------------------------------------------------------------------------------------------------------

Sleep debt calculator project.

const getSleepHours = day => {

if (day === 'monday') {

return 8;

} else if (day === 'tuesday') {

return 8;

} else if (day === 'wednesday') {

return 7;

} else if (day === 'thursday') {

return 7;
} else if (day === 'friday') {

return 6;

} else if (day === 'saturday') {

return 6;

} else if (day === 'sunday') {

return 9;

const getActualSleepHours = () => getSleepHours('monday') + getSleepHours('tuesday') +


getSleepHours('wednesday') + getSleepHours('thursday') + getSleepHours('friday') +
getSleepHours('saturday') + getSleepHours('sunday');

const getIdealSleepHours = () => {

var idealHours = 7;

return idealHours * 7;

const calculateSleepDebt = () => {

var actualSleepHours = getActualSleepHours();

var idealSleepHours = getIdealSleepHours();

if (actualSleepHours === idealSleepHours) {

console.log('User got the perfect amount of sleep.')

} else if(actualSleepHours > idealSleepHours) {

console.log(`The user got more sleep than needed by ${actualSleepHours - idealSleepHours} hours`)

} else if(actualSleepHours < idealSleepHours) {

console.log(`The user should get some rest, they are behind ${idealSleepHours - actualSleepHours}
hours`)

}
calculateSleepDebt();

-------------------------------------------------------------------------------------------------------------------

// Write your function here:

const lifePhase = age => {

if (age < 0 || age > 140) {

return 'This is not a valid age'

} else if (age < 4) {

return 'baby'

} else if (age < 13) {

return 'child'

} else if (age < 20) {

return 'teen'

} else if (age < 65) {

return 'adult'

} else {

return 'senior citizen'

// Write your function here:

const finalGrade = (num1, num2, num3) => {

if((num1 < 0 || num1 > 100) || (num2 < 0 || num2 > 100) || (num3 < 0 || num3 > 100)){

return 'You have entered an invalid grade.';

let average = (num1 + num2 +num3) / 3;


if (average < 60) {

return 'F';

} else if (average < 70) {

return 'D';

} else if (average < 80) {

return 'C';

} else if (average < 90) {

return 'B';

} else if (average < 101) {

return 'A';

// Write your function here:

const calculateWeight = (earthWeight, planet) => {

switch (planet) {

case 'Mercury':

return earthWeight * 0.378;

break;

case 'Venus':

return earthWeight * 0.907;

break;

case 'Mars':

return earthWeight * 0.377;

break;

case 'Jupiter':
return earthWeight * 2.36;

break;

case 'Saturn':

return earthWeight * 0.916;

break;

default:

return 'Invalid Planet Entry. Try: Mercury, Venus, Mars, Jupiter, or Saturn.';

const truthyOrFalsy = value => {

if (value) {

return true

return false

3 string paramters and string interpolation const sillySentence = (string1, string2, string3) => {

return `I am so ${string1} because I ${string2} coding! Time to write some more awesome ${string3}!`;

age calculator.

/*

Our solution is written as a function expression and uses string interpolation, but it would be equally
acceptable to use a function declaration and/or string concatenation

*/

const howOld = (age, year) => {


// The following two lines make it so that our function always knows the current year.

let dateToday = new Date();

let thisYear = dateToday.getFullYear();

// It is totally ok if your function used the current year directly!

const yearDifference = year - thisYear

const newAge = age + yearDifference

if (newAge > age) {

return `You will be ${newAge} in the year ${year}`

} else if (newAge < 0) {

return `The year ${year} was ${-newAge} years before you were born`

} else {

return `You were ${newAge} in the year ${year}`

tip calculator.
// Write your function here:

const tipCalculator = (quality, total) => {

switch(quality) {

case 'bad':

return total * .05;

case 'ok':

return total * .15;

case 'good':

return total * .20;


case'excellent':

return total * .30;

default:

return total * .18;

// Uncomment the line below when you're ready to try out your function

console.log(tipCalculator('ok', 100)) //should return 20

// We encourage you to add more function calls of your own to test your code!

// Write your function here:

const toEmoticon = (string) => {

switch(string) {

case 'shrug':

return '|_{"}_|';

case 'smiley face':

return ':)';

case 'frowny face':

return ':(';
case 'winky face':

return ';)';

case 'heart':

return '<3';

default:

return '|_(* ~ *)_|'

if(value) checks the truthyness of the expression.

create a function that returns true if number is even and false if odd.
// Write function below

const isEven = (num1) => {

if (num1 % 2 === 0) {

return true;

} else {

return false;

console.log(isEven(6));

// Create function here

const numberDigits = (x) => {

if (x < 0 || x > 99) {

return `The number is: ${x}`

} else if ( x < 10 && x > 0 || x === 0) {


return `One digit: ${x}`;

} else if (x < 100) {

return `Two digits: ${x}`;

console.log(numberDigits(0))

number guesser project.- -----------------------------------------------

let humanScore = 0;

let computerScore = 0;

let currentRoundNumber = 1;

var targetNumber;

// Write your code below:

const generateTarget = () => {

return targetNumber = Math.floor(Math.random() * 10);

const compareGuesses = (humanGuess, pcGuess, targetNumber) => {

if (Math.abs(targetNumber - humanGuess) < Math.abs(targetNumber - pcGuess)) {

return true;

} else {

return false;

const updateScore = (string1) => {


if (string1 === 'human') {

humanScore + 1;

} else if (string1 === 'computer') {

computerScore + 1;

const advanceRound = () => {

currentRoundNumber + 1;

console.log(compareGuesses(9, 2, generateTarget()));

console.log(targetNumber);

You might also like