JS Cohort Class 5 Notes & Exercises - tinuola/gdi-classes Wiki

Original URL: https://github.com/tinuola/gdi-classes/wiki/JS-Cohort-Class-5-Notes-&-Exercises

JS Cohort Class 5 Notes & Exercises

One more class to go!

We made it through Functions! 👏🏽 👏🏽 👏🏽 Thank you for a great Class 5, everyone!

We'll wrap up with Arrays and Objects in our final class and explore built-in JavaScript methods that let us work with some of the data types we've learned in this series.

My apologies again for forgetting to start the class 5 recording well into the lesson! 😳 🤦🏽‍♀️ I hope the notes and reference exercises will make up for the lapse. I'll be sure to hit record for our last class! ✔️

Have fun with the exercises if you have the time to go through them. But most of all, enjoy your weekend! ☀️

See you all in Class 6!

Check-in survey for Class 5 - https://forms.gle/rbxtYsca6kwFdJLbA

Functions

Declaring a Function

A function is a block of code or instructions for a program or browser to perform a particular task.

Functions are reusable--they can be called multiple times to perform the same task.

Functions can make our code organized and more efficient.

In JavaScript, we write a function by declaring it with the function keyword, giving the function a name, adding a pair of parentheses (), and a pair of curly braces {}. In between the curly braces, we add our code or instruction.

// The syntax of a function declaration:

function funtionName(){
  // your code
  // what the function should do 
}

Calling a Function

But declaring a function is not enough. It then needs to be invoked or called or run. These are all ways of saying we want to use or execute the function.

// The syntax of a function call:

functionName()

Example:

/* 
Declare a function called `parrotFacts`.

The console statement in the function body is 
the action we want the function to execute.

Then we invoke or call the function.
*/

function parrotFacts(){
  console.log('Parrots are very intelligent birds.');
} 

parrotFacts()

Example:

/* 
Declare a function called `sayHello` that prints 
the greeting "Hello Everyone" to the console or 
to an HTML page.

Run or invoke the function.
*/

function sayHello(){
  document.write('Hello Everyone')
}

sayHello()

Example:

/* 
Declare a function called `repeatName` that prints out your name 20 times.

Run or invoke the function.
*/

function repeatName(){
  for( i = 0; i < 20; i++ ){
    console.log(`Nada ${i}` )
  }
}

repeatName()

Naming Functions

Naming a function is similiar to how we name variables. Start with a lowercase alphabeth; make the name descriptive; make the name unique, etc.

The other best practice with naming a function is that the name should reflect what the function is meant to do.

// Poor function names

car()

username()

multiply()

// Better function names

multiplyByFour()

getUsername()

displayCarBrand()

disableButtonOnClick()

It's better to have a wordy or long function name than a short and vague function name.

Parameters and Arguments

Parameters

Functions are meant to be reusable. But the repeatName() function we've just written only does one thing: it prints the name 'Nada'. We can make this function more efficient or useful by having it print any name whenever we want.

Functions can take input values known as Parameters.

Think of a parameter as a placeholder for a yet-unknown-value that the function will use when it's called.

// Syntax of using or passing a parameter:

function repeatName( anyName ){
  console.log(`Hi ${anyName}`)
}

repeatName()

/* 
`anyName` in the function declaration above is 
a parameter. It has no value yet; but if and 
when it does, the function will console.log that value.

Try running the function. 

The console should display `Hi undefined`, because the parameter `anyName` has no value--yet.
*/

Arguments

To make the repeatName function display a real name, we have to call it with an Argument.

An argument is the actual value we're passing to the function to use (when invoked) instead of the placeholder.

Arguments can be any data type: Strings, Numbers, Boolean, Arrays, etc.

// Syntax of using or passing an argument:

repeatName('Danielle')

// The string 'Danielle' is an argument.

// Now run the code entire again.

function repeatName( anyName ){
  console.log(`Hi ${anyName}`)
}

repeatName('Danielle')

We can now run the repeatName function multiple times with any argument (or name).

repeatName('Julie')
repeatName('Dre')
repeatName('Nada')

Example:

/* 
Declare a function called `displayName` that takes 
two parameters `firstName` and `lastName`, and displays
them to the console or to an HTML page.

Run or invoke the function. (Remember we need two 
arguments to replace the parameters.)
*/

function displayName (firstName, lastName){
  console.log(firstName, lastName)
}

displayName('Julie', 'DeLoach')
displayName('Danielle', 'Cooper')

Example:

/* 
Declare a function called `addNumbers` that takes 
three parameters and outputs the sum of the three 
parameters to the console.

Run or invoke the function.
*/

function addNumbersTwo(num1, num2, num3){
  console.log(num1 + num2 + num3)
}

addNumbersTwo(5, 9, 1)
addNumbersTwo(7, 7, 7)
addNumbersTwo(2, 3, 4)

NOTE: Remembering the difference between a parameter and an argument can seem confusing at first. Some developers feel the terms mean the same thing and therefore use them interchangably.

Sticking to one term or using both? The points to remember are that we declare a function with a placeholder value, and run the function with an actual value.

Variables as Arguments

We've learned previously that variables store value. Therefore, we can also pass variables as arguments for functions.

let numThree = 3
let numSeven = 7
let numEight = 8

function addNumbers(a, b, c){
  console.log(a + b + c)
}

addNumbers(numThree, numSeven, numEight)

/*
We declared three variables `numThree`, `numSeven`, 
`numEight` and assigned them values. 

Then we used the  variables (not the actual integer 
values) in the function call.
*/

Example:

function addOne(anyNum){
  let newNumber = anyNum + 1;
  console.log(`Your original number ${anyNum} has now been increased by 1. Your new number is now ${newNumber}.`)
}

let numFive = 5
addOne(numFive)

let numTen = 10
addOne(numTen)

Return Statements

Up till now, we've primarily used the console.log method to output our JavaScript code. But remember that the console is a temporary environment. We use the console to verify that our code works or to troubleshoot/debug our code.

In actuality, we want JavaScript to store the output of our code so we can use it at any time.

Instead of a console statement, we want to start using a return statement.

Functions, for the most part, return a value that can be used later.

// We're using a `return` statement in this function:

function doubleNumbers(num){
  return num*num;
}

// We assign the function call (with its argument)
// to a variable.

let result = doubleNumbers(4)

// Now we can use the return value however we want.

console.log(result)

console.log(`I would like ${result} veggie tacos, please.`)

// We can even use the return value in another function!

function printNumber(num){
  return num * 4
}

// Using the variable `result` as an argument in the
// printNumber function:

console.log( printNumber(result) )

// Run all the lines of code above in sequence.

// You should get 64.
/* 
Declare a function called `tellFortune` that takes 
four arguments: a name, a number, title, location. 

The function RETURNS a statement: 'Hi A, in B years 
you will be a C living in D.' 

Declare a variable that calls this function and
passes it four arguments.

Display the output to the console.
*/

function tellFortune(anyName, anyNumber, anyTitle, anyLocation){
  return (`Hi ${anyName}, in ${anyNumber} years you will be a ${anyTitle} living in ${anyLocation}.`)
}

let result = tellFortune('Lauren', 3, 'millionaire', 'somewhere warm')

console.log(result)

NOTE: If a function uses a return statement and you run the function in the console, the console will display the value of the return statement.

However, if you run a Javascript file that holds the function, the value of that function will not be visible in the console.

/*
Copy and paste this function into your console.

function showName(){
  return 'Tinu'
}

showName()

// The console will display the name 'Tinu'


Now create a script file: show-name.js.

Save the showName function to this file. 

Make sure the script file is linked to an HTML page.

Open the HTML page and check the console.

The console will be empty.

The value of the return statement is stored in memory 
but not visible because we're not using it yet.
*/

NOTE: JavaScript will stop executing a function after the return statement. That is, any code that comes after that statement will not run.

function product(a, b){
  return a*b
  console.log('Will this print?...')
}

product (3,4)

// The console statement after the return statement
// will not display.

Scope

Scope in programming (not just JavaScript) means how accessible a variable or value is to other functions or parts of the code.

There are two primary types: Global Scope and Local Scope.

Global Scope

A variable or value that is globally scoped can be used by any function in the code.

let myName1 = 'Tinu'

function writeName(){
  console.log(myName1)
}

writeName();

function sayName(){
  console.log(myName1)
}

sayName()

/* 
The variable `myName` can be used by any function; 
it has no restrictions. It is globally scoped. 
*/

Local Scope

A locally scoped variable or value is usable only in the function where it has been declared. Any code outside of that function's environment cannot use that variable.

function writeName(){
  let myName2 = 'Tinu'
  console.log(myName2)
}

writeName()

console.log(myName2)

// or 

function sayName(){
  console.log(myName2)
}

sayName()

/*
When we run the code above, the second console.log 
statement and the `sayName` function will throw errors 
in the console. 

They're both trying to use `myName2`, a variable that's 
only accessible or locally scoped to the `writeName` 
function.
*/

Exercises

Debugging

Debug the following functions:

function (num) {
  console.log(num * 2)
}
function smooshWords (word1, wor2) {
  console.log(word2 + word3)
}

smooshWord("break", "fast", "pizza")
getHalf () {
  return num / 2
}

let newNum = getHalf(84)

console.log(newNum)

Functions

/*
Declare a function `isIttrueOrFalse` that takes a boolean value 
and returns 'Yes' if the value is true, or 'No' if the value is 
false, or 'This is not a boolean.' if it's any other value.
*/
/*
Declare a function called `lovesMeLovesMeNot` that takes 
the number of petals on a flower and returns "Loves Me!"
if the number is even and returns "Loves me not..." if 
the number is odd.

Add emojis? 😀

//====

Up for an extra challenge?

Use a ternary statement.
*/
/*
Declare a function `areYouMyFriend` that takes two 
parameters `name` and `bestFriend`.

If name is the same as bestFriend, console.log
'Hey BFF!' FIVE times, otherwise console.log
'Hey, potential new friend!' just once.

//====

Puzzle:

What would happen if return statements
are used in this function?

Extra Challenge:

Can you think of an alternate solution to 
return `Hey BFF` 5 times?
*/
/*
Declare a function called `sillyMadLib` that takes four 
parameters: famousName, verbING, nouns, adjective.

Return a statement: 

"The ancient art of (verbING) was popularized by (famousName) in 1200BC. It is a very (adjective) form of creative expression, especially when combined with (nouns)."

//====

Up for an extra challenge?

Version 2:

Remember our taco truck application? Try using some 
what we did there to make this function more interactive:

Prompt a user for the necessary input values and 
display the result to the HTML page.

Hint: 

Version 2 does not need to have parameters or arguments declared.

But it does need four variables INSIDE the function,
and these variables will store the user's input.
*/
/*
Declare a function called `celsiusConverter` that 
takes a number in Celcius and converts it to 
Fahrenheit.

Use the calculation method referenced on this site:
https://www.mathsisfun.com/temperature-conversion.html

//====

Up for an extra challenge?

Version 2:

Make this function interactive:

Prompt a user for the temperature and return the 
value in Fahrenheit to the HTML page.

The hints from the `sillyMadLib` version 2 exercise 
should help here.
*/

Solutions