General Assembly

Conditionals & Functions

Wilson Espina

Review

What did we do last lesson?

Conditionals & Functions

Learning Objective

Learning Objectives

At the end of this class, you will be able to:

  • Differentiate between true, false, 'truth-y', and 'false-y'
  • Use if/else conditionals to control program flow based on boolean conditions
  • Use comparison operators to evaluate and compare statements
  • Describe how parameters and arguments relate to functions
  • Create and call a function that accepts parameters to solve a problem
  • Return a value from a function using the return keyword

Conditionals & Functions

Agenda

  • Conditionals
  • Logical operators
  • Truthy & Falsy
  • Functions

Conditionals & Functions

Exit Ticket Suggestions

  1. Code exercises were HARD, requiring a lot more understanding of concepts than is provided during explanation.
  2. The pre-course Codecademy tutorials + all the EloquentJS reading homework = information overload.
  3. The lesson was quite tough, lots of new concepts being introduced.

Conditionals & Functions

Classroom Resources

  1. Pull changes from the wilson-espina/jsd-9-resources repo to your computer:
    • Open the Terminal
    • cd to the Documents/JSD/jsd-9-resources directory
    • Type git pull origin master and press return
  2. In your editor, open the following folder: Documents/JSD/jsd-9-resources/04-conditionals-functions

Conditionals & Functions

Conditionals

Conditionals & Functions

Conditional Statements

  • Conditional statements are a way of essentially skipping over a block of code if it does not pass a boolean expression.
  • Known as control flow statements, because they let the program make decisions about which statement should be executed next, rather than just going in order.
Control flow diagram

Conditionals & Functions

Philosophical JavaScript

Pensive statue

JavaScript always tries to look for truth

Conditionals & Functions

Block Statements

  • Statements meant to be executed after a control flow operation will be grouped into what is called a block statement.
  • These statements are wrapped into a pair of curly braces:

{
  console.log("hello");
  console.log("good bye");
}
					

Conditionals & Functions

If Statement


if (expression) {
  code
}
					

if (expression) { code }

					
  • Both versions will still be be interpreted as valid JavaScript.
  • The correct version is best practice for code readability.

Conditionals & Functions

Comparison Operators

>

greater than

>=

greater than or equal to

<

less than

===

strict equal, type and value

==

coercive equal (AVOID)

!==

strict not equal, type and value

!=

coercive not equal (AVOID)


-1 > 2
//=> false

123 < 6;
//=> false

0.12 >= 0.0023;
//=> true
							
  • Always returns a Boolean value

Conditionals & Functions

Type coercion


12 > '12';
//=> false

12 >= '12';
//=> true

'A' > 'a'
//=> false

'b' > 'a';
//=> true

'Glow' > 'Glee';
//=> true
						
  • JavaScript assumes you mean something else when data types don't match with non-strict comparison.
  • This can be the source of frustration for some developers, since most languages do not implicitly convert strings to numbers.
  • JavaScript uses the so-called dictionary or lexicographical order.

Conditionals & Functions

If statement


let weather = "sunny";

if (weather === "sunny") {
  console.log("Grab your sunglasses");
}
						

Conditionals & Functions

If / else statement


let weather = "sunny";

if (weather === "sunny") {
  console.log("Grab your sunglasses");
} else {
  console.log("Grab a coat");
}
						

Conditionals & Functions

Else if Statement


let weather = "sunny";

if (weather === "sunny") {
  console.log("Grab your sunglasses");
} else if (weather === "rainy") {
  console.log("Take an umbrella");
} else {
  console.log("Grab a coat");
}
						

Conditionals & Functions

Ternary Operator

  • You can think about the ternary operator as a concise "if-else in one line"

(expression) ? trueCode : falseCode;
						

Conditionals & Functions

Ternary Operator

  • Can produce one of two values, which can be assigned to a variable in the same statement

let drink = (expression) ? trueCode : falseCode;

let sunny = true;
let drink = sunny ? 'beer' : 'coffee';
console.log(drink) // beer
						

Conditionals & Functions

Switch Statement

  • The switch statement can be used for multiple branches based on a number or string:

const food = 'apple';

switch(food) {
	case 'pear':
	  console.log('I like pears');
	  break;
	case 'apple':
	  console.log('I like apples');
	  break;
	default:
	  console.log('No favourite');
}
//=> I like apples
						

Conditionals & Functions

Logical Operators

  • Operators that let you chain conditional expressions
&& AND

Returns true when both left and right values are true

|| OR

Returns true when at least one of the left or right values is true

! NOT

Takes a single value and returns the opposite Boolean value

Conditionals & Functions

&& (AND)

  • The && operator requires both left and right values to be true in order to return true:

true && true
//=> true
							
  • Any other combination is false

true && false
//=> false

false && false
//=> false
							

Conditionals & Functions

|| (OR)

  • The || operator requires just one of the left or right values to be true in order to return true

true || false
//=> true

false || true
//=> true

false || false
//=> false
							

Conditionals & Functions

Strict Mode


								'use strict';
							
  • Goes at the top of the file.
  • Tells browsers to be unforgiving in interpreting our code
  • Helps us write good code by ensuring that even little mistakes trigger errors.

Code along

Code Along

Open up: 1-conditionals-codealong

Conditionals & Functions

Truthy & Falsy

Conditionals & Functions

Falsy Values

All of the following become false when converted to a Boolean:


false
0
'' // (empty string)
NaN
null
undefined
					
  • These are known as falsy values because they are equivalent to false

Conditionals & Functions

Truthy Values

  • All values other than false, 0, "", NaN, null, and undefined become true when converted to a Boolean.
  • All values besides these six are known as truthy values because they are equivalent to true.

17193
true
'0'
'false'
					

Conditionals & Functions

Converting to Boolean

  • Adding ! before a value returns the inverse of the value as a Boolean
  • Adding !! before a value gives you the original value as a Boolean:

!!1
//=> true

!!0
//=> false

!![]
//=> true

!!{}
//=> true

!!null
//=> false

!!""
//=> false
					

Lab - Ages exercise

Exercise

Type of Exercise

  • Pairs

Location

  • starter-code > 2-ages-lab

Timing

15 mins

  1. Write a program that outputs results based on users’ age. Use the list of conditions in the app.js file.
  2. BONUS 1: Rewrite your code to allow a user to enter the exponent value, rather than hard-coding it into your program. (Hint: Read up on the window.prompt method).
  3. BONUS 2: Rewrite your code to use a switch statement rather than if and else statements).

Conditionals & Functions

Functions

Conditionals & Functions

Developers should be lazy

Lazy dog

Code should be written with DRY principals:

  • Don't
  • Repeat
  • Yourself

Conditionals & Functions

Functions

Modular

Allow us to group a series of statements together to perform a specific task

Reusable

We can use the same function multiple times

Efficient

Not always executed when a page loads. Provide us with a way to 'store' the steps needed to achieve a task

Conditionals & Functions

Function Declaration Syntax


function name(parameters) {
  // do something
}
						

Conditionals & Functions

Function Declaration example


function sayHello() {
  console.log(“Hello!”);
}
						

Conditionals & Functions

Function Expression syntax


let name = function(parameters) {
  // do something
}
						

Conditionals & Functions

Function Expression example


let sayHello = function(parameters) {
  console.log("Hello!");
}
						

Conditionals & Functions

Arrow Function syntax


let name = (parameters) => {
  // do something
}
						

Conditionals & Functions

Arrow Function syntax


let sayHello = (parameters) => {
  console.log("Hello!");
}
						

Conditionals & Functions

Invoking a Function

  • When we want to execute the function (make it run), we use the function name followed by parentheses ( )
  • We can say:
    • Call the function
    • Invoke the function
    • Execute the function
    
    function sayGoodbye(){
      console.log('good bye');
    }
    
    sayGoodbye();
    => good bye
    										

Code along

Code Along

Open up: 3-functions-codealong

Lab - Using Functions

Exercise

Key Objective

  • Practice defining and executing functions

Type of Exercise

  • Individual

Location

  • starter-code > 4-functions-exercise (part 1)

Timing

4 mins

  1. Open up js > main.js
  2. Follow the instructions under Part 1.

Conditionals & Functions

Parameters

Conditionals & Functions

Parameters make functions reusable


function newFunc(parameter1, parameter2, parameter3){
	console.log(parameter1 + parameter2 + parameter3);
}
						

The values in the parentheses are placeholders for the data that we pass to our functions and are known as parameters:

  • Parameters are variables listed as a part of the function definition.
  • When we invoke a function, the values we pass to the function are called arguments.

Conditionals & Functions

Using Parameters


function sayHello(name) {
  console.log('Hello! ' + name);
}

sayHello('Wilson'); // 'Wilson' is an argument
=> 'Hello Wilson'
						

Conditionals & Functions

Using Multiple Parameters


function sum(num1, num2) {
  console.log(num1 + num2);
}

sum(1, 2); // 1 and 2 are arguments
=> 3
						

Conditionals & Functions

Default Parameters


function multiply(num1, num2 = 2) {
  console.log(num1 * num2);
}

multiply(4,5);
=> 20

multiply(3);
=> 6 // (argument) * 2 (default value)
						

Lab - Reading Functions

Exercise

Type of Exercise

  • Individual

Location

  • starter-code > 4-functions-exercise (part 2)
  • Add you answer to the Slack polls

Timing

3 mins

  1. Look at Part 2A and 2B. Predict what will happen when each function is called.

Lab - Creating Functions

Exercise

Type of Exercise

  • Individual / Pairs

Location

  • starter-code > 4-functions-exercise (part 3)

Timing

8 mins

  1. See if you can write one function that takes some parameters and combines the functionality of the makeAPizza and makeAVeggiePizza functions
  2. BONUS: Create your own function with parameters. This function could do anything!

Conditionals & Functions

Return Statements

Conditionals & Functions

Return Statement

  • Ends function’s execution.
  • Returns a value — the result of running the function.
  • console.log() is only useful for the developer.

Conditionals & Functions

Returning values


function subtract(num1, num2) {
  return num1 - num2;
}

subtract(10,5);
=> 5
						

Conditionals & Functions

Return stops a functions's execution


function speak(words) {
  return words;

  // The following code will not run:
  let x = 1;
  let y = 2;
  console.log(x + y)
}

speak('Hey!');
// "Hey!"
						

Lab - Using parameters

Exercise

Key Objective

  • Create and call a function that accepts parameters to solve a problem

Type of Exercise

  • Individual / Pairs

Location

  • starter-code > 5-price-calculator

Timing

10 mins

  1. Write code to to calculate a customer's total cost in pounds based on product price, tax rate, shipping cost, and the currency they're using for the purchase (pounds or euros).
  2. BONUS 1: Convert your function to assume a currency of "pounds" by default.
  3. BONUS 2: Convert your function to an arrow function.

Conditionals & Functions

Learning Objectives - Review

  • Differentiate between true, false, 'truth-y', and 'false-y'
  • Use if/else conditionals to control program flow based on boolean conditions
  • Use comparison operators to evaluate and compare statements
  • Describe how parameters and arguments relate to functions
  • Create and call a function that accepts parameters to solve a problem
  • Return a value from a function using the return keyword

Conditionals & Functions

Lookahead to Next Lesson (27/05/20)

Scope & Variables

  • Understand what is scope
  • Understand how scope works
  • Determine the scope of local and global variables
  • Describe what hoisting does

Conditionals & Functions

Q&A

Conditionals & Functions

Homework

Conditionals & Functions

Homework Repo

Forking instructions
  1. Head to https://git.generalassemb.ly/wilson-espina/jsd-9-homework
  2. Click 'Fork' and following instruction on how to fork the repo.
  3. Click 'Clone or Download' and copy git link (Make sure it says Clone with HTTPS).
  4. cd to your Documents/JSD directory.
  5. Type git clone and paste the URL and hit return.

Conditionals & Functions

Exit Ticket

(Lesson 04)