C4: Session 9

JS Conditional Logic, Loops, and Functions

REVIEW

String Represents textual data 'hello', "hello", `hello`
Number An integer or floating-point number 3, -3, 0.1234, 3e-9
Boolean Either true or false true or false
null value is empty or nothing
undefined uninitialized value

JavaScript Data Types (Primitive)

Concept:
Conditional Logic

Conditional Logic

Algorithms

  • An algorithm is a set of instructions that we can use to make decisions, ultimately to solve a problem or complete a task
  • We actually use algorithms in our day-to-day lives to make decisions:
    • If it is 50ºF outside, should I wear a light or heavy jacket?
    • If I'm wearing a blue shirt, which pair of pants will match?
    • If the stadium is on the east side, should I go left or right?
    • If I have $5 in my account, an I afford this new computer?

Conditional Logic

If Statements

We can use if statements in JavaScript to make decisions based on certain conditions.

if (condition is true) {
  // run this code
} 

Conditional Logic

Example

Conditional Logic

Comparison Operators

When working with conditionals, we utilize comparison operators that either returns true or false.

== equality 
=== strict equality
!= inequality
!== strict inequality
greater than
>= greater than or equal to
< less than
<= less than or equal to

Conditional Logic

Equality Operator (==)

Compares the value on the left to the right and returns true if the values are equivalent or false if they are not. 

console.log(10 == 10); // returns true

console.log('hello' == 'bye') // returns false

console.log('10' == 10); // returns true

Note: The == operator does not care about types when comparing data. JavaScript will convert one type to another. This is called Type Coercion.

Conditional Logic

Strict Equality Operator (===)

Compares the value on the left to the right and returns true if the data types AND values are equivalent or false if they are not. 

console.log(10 === 10); // returns true

console.log('hello' === 'bye') // returns false

console.log('10' === 10); // returns false

Conditional Logic

Inequality Operator (!=)

Compares the value on the left to the right and returns true if the values are NOT equivalent or false if they are. 

console.log(10 != 10); // returns false

console.log('hello' != 'bye') // returns true

console.log('10' != 10); // returns false

Conditional Logic

Strict Inequality Operator (!==)

Compares the value on the left to the right and returns true if the data types AND values are NOT equivalent or false if they are. 

console.log(10 !== 10); // returns false

console.log('hello' !== 'bye') // returns true

console.log('10' !== 10); // returns true

Conditional Logic

Greater Than Operator (>)

Compares two numbers. It returns true if the number on the left is greater than the number on the right. Otherwise, it returns false

console.log(10 > 2); // returns true

console.log(2 > 3) // returns false

console.log(10 > 10); // returns false

console.log('10' > 8); // returns true

console.log('hello' > 1) // return false

Conditional Logic

Greater Than or Equal To Operator (>=)

Compares two numbers. It returns true if the number on the left is greater than or equal to the number on the right. Otherwise, it returns false

console.log(10 >= 2); // returns true

console.log(2 >= 3) // returns false

console.log(10 >= 10); // returns true

console.log('10' >= 8); // returns true

Conditional Logic

Less Than Operator (<)

Compares two numbers. It returns true if the number on the left is less than the number on the right. Otherwise, it returns false

console.log(10 < 2); // returns false

console.log(2 < 3) // returns true

console.log(10 < 10); // returns false

console.log('10' < 8); // returns false

Conditional Logic

Less Than or Equal To Operator (<=)

Compares two numbers. It returns true if the number on the left is less than or equal to the number on the right. Otherwise, it returns false

console.log(10 <= 2); // returns false

console.log(2 <= 3) // returns true

console.log(10 <= 10); // returns true

console.log('10' <= 8); // returns false

Conditional Logic

Logical Operators

When working with conditionals, we can use logical operators to check multiple conditions at the same time. 

&& logical AND operator 
|| logical OR operator

Conditional Logic

Logical AND Operator (&&)

Returns true if and only if the left and right operands are true. Otherwise, returns false

// Instead of this
if (age >= 13) {
  if (age < 18) {
    console.log('teenager')
  }
}

// Use the && operator
if (age >= 13 && age < 18) {
  console.log('teenager')
}

Conditional Logic

Logical OR Operator (||)

Returns true if either the left or right operands is true. Otherwise, returns false

const role = 'mom';

// Instead of this
if (role === 'mom') {
  console.log('parent');
}

if (role === 'dad') {
  console.log('parent');
}

// Use the || operator
if (role === 'mom' || role === 'dad') {
  console.log('parent')
}

Conditional Logic

Else If and Else Statements

We can chain else if and else statements after an if statement to check for alternate conditions.

if (num > 15) {
  console.log("Bigger than 15");
} else if (num < 5) {
  console.log("Smaller than 5");
} else if (num === NaN) {
  console.log('num is not a number!')
} else {
  console.log("Between 5 and 15");
}

Conditional Logic

Order Matters!

Code is executed from top to bottom so you must be careful of which statement comes first!

if (num < 1) {
  console.log('Less than one');
} else if (num < 2) {
  console.log('Less than two');
} else {
  console.log('Greater than or equal to 2');
}
if (num < 2) {
  console.log('Less than two');
} else if (num < 1) {
  console.log('Less than one');
} else {
  console.log('Greater than or equal to 2');
}

Concept:
Loops

Loops

Loops

Loops are used in JavaScript to execute the same piece of code over and over again until a condition is met to stop it.

There are three key parts of a loop:

  1. When to start the loop
  2. When to stop the loop
  3. How to get to the next iteration of the loop

If your loop is missing any of these, you will run into an infinite loop which can cause your browser to crash or freeze.

Loops

Automate repetitive tasks

For example, if you want to print the numbers 0-5:

console.log(0);
console.log(1);
console.log(2);
console.log(3);
console.log(4);
console.log(5);

Loops

Automate repetitive tasks

...but what if you want to print the numbers 0-100?

console.log(0);
console.log(1);
console.log(2);
console.log(3);
console.log(4);
console.log(5);

// yeah no

Loops

Automate repetitive tasks

We can use a for loop to run a block of code a specific number of times.

for (start index; stop condition; index count) {
  // code to be executed at each iteration
}
  • The start index is executed only once before the loop starts. 
  • The stop condition is evaluated at the beginning of each iteration. The loop will stop when this condition returns false.
  • The index count is evaluated at the end of each iteration and is used to increment or decrement your loop counter.

Loops

Automate repetitive tasks

We can use a for loop to run a block of code a specific number of times.

for (let i = 0; i <= 100; i++) {
  console.log(i);
}

Loops

Automate repetitive tasks

We don't have to iterate one at a time. We can change the index counter statement to any expression.

for (let i = 0; i <= 100; i += 2) {
  console.log(i);
}

Concept Practice: Loops

Iterate Odd Numbers

Print all odd numbers between 1 to 99 to the console. 

Concept Practice: Loops

Iterate Odd Numbers

Print all odd numbers between 1 to 99 to the console. 

for (let i = 1; i <= 99; i += 2) {
  console.log(i);
}

Concept Practice: Loops

Counting Backwards

Print the numbers 1 to 9 backwards. 

Concept Practice: Loops

Counting Backwards

Print the numbers 1 to 9 backwards. 

for (let i = 9; i > 0; i--) {
  console.log(i);
}

Concept Practice: Loops

Summation

Print out the sum of all numbers between 0 to 100.

Concept Practice: Loops

Summation

Print out the sum of all numbers between 0 to 100.

let sum = 0;

for (let i = 0; i <= 100; i++) {
  sum += i;
}

console.log(sum);

Concept Practice: Loops

FizzBuzz

For numbers between 1 to 100, print "Fizz" if the number is divisible by 3; print "Buzz" if the number is divisible by 5; print "FizzBuzz" if the number is divisible by 3 and 5; and print the number if not of the above applies.

Concept Practice: Loops

FizzBuzz

For numbers between 1 to 100, print "Fizz" if the number is divisible by 3; print "Buzz" if the number is divisible by 5; print "FizzBuzz" if the number is divisible by 3 and 5; and print the number if not of the above applies.

for (let i = 1; i <= 100; i++) {
  if (i % 3 === 0 && i % 5 === 0) {
    console.log('FizzBuzz');
  } else if (i % 3 == 0) {
    console.log('Fizz');
  } else if (i % 5 == 0) {
    console.log('Buzz');
  } else {
    console.log(i);
  }
}

Concept Practice: Loops

More Practice Problems

More practice sets to test your algorithm and problem-solving skills. Some of these are common interview questions!

https://www.freecodecamp.org/learn/project-euler/

Loops

Loops and Arrays

Loops are very commonly used with arrays. We'll learn about arrays next session so stay tuned!

Concept:
Functions

Functions

Functions

  • A function is a block of code that allows you to perform a particular task - like a shortcut.
  • We've used functions before:
    • alert('some string')
    • prompt('some string')
    • console.log('some string')

Functions

Function Definition

function name() {
  // code to be executed
}

A function is defined using the function keyword followed by:

  • The name of the function
  • The function body wrapped in {}, which contains code statements that are to be executed when the function is called

Functions

Examples

function sayHelloWorld() {
  console.log("Hello World!");
}

function getTodaysDate() {
  const date = new Date();
  return date;
}

Functions

Function Call (Invocation)

Once the function is defined, we can invoke the function anywhere in our code by calling its name with the pair of parentheses, for example:

function sayHelloWorld() {
  console.log("Hello World!");
}


// call the function
sayHelloWorld();

Functions

Returning a value from a function

function getTodaysDate() {
  const date = new Date();
  return date;
}

const today = getTodaysDate();
console.log(today);

Functions can have a return statement that sends a value back out of a function. We can store this value in another variable or use it as a value in another function. 

Functions

Passing values to functions

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


testFn('hello', 'world', 99);
testFn('abc', 99, false)

Parameters are variables that act as placeholders for the values that are to be input to a function when it is called. The actual values that are passed are called arguments.

Functions

Example

function sayHelloTo(personName) {
  const greeting = "Hello " + personName;
  console.log(greeting);
}

function sayHelloToFrom(personName, fromPerson) {
  const greeting = "Hello " + personName + " from " + fromPerson;
  console.log(greeting);
}

sayHelloTo('Bob');
sayHelloToFrom('Bob', 'Jane');

Functions

Naming Functions

A function's name should describe what the function does and its name typically consists an action, for example

  • get... to get and return a value
  • calc... to calculate values
  • create... to create something
  • check... to check something and return a boolean
  • on... to describe an interaction on a target element

Functions

Naming Functions

A function's name should describe what the function does and its name typically consists an action, for example

  • getPhoneNumber(); 
  • calcAverage(); 
  • createLogin();
  • checkPermission(); 
  • onClick(); 

Concept Practice: Functions

Sum of Two Numbers

Write a function that returns the sum of two numbers. Print the result to the console.

Concept Practice: Functions

Sum of Two Numbers

Write a function that returns the sum of two numbers. Print the result to the console.

function getSum(numA, numB) {
  return numA + numB;
}

let sum = getSum(4, 7);
console.log(sum);

Concept Practice: Functions

Check Odd or Even

Write a function that checks if a number is odd or even. If odd, print "odd" to the console. Otherwise, print "even".

Concept Practice: Functions

Check Odd or Even

Write a function that checks if a number is odd or even. If odd, print "odd" to the console. Otherwise, print "even".

function checkEvenOrOdd(num) {
  if (num % 2 === 0) {
    console.log("even");
  } else {
    console.log("odd");
  }
}

checkEvenOrOdd(2);

Concept Practice: Functions

Sum Between Two Numbers

Write a function that takes in two numbers. Return the sum of all numbers between the two given numbers and print the result to the console.

Concept Practice: Functions

Sum Between Two Numbers

Write a function that takes in two numbers. Return the sum of all numbers between the two given numbers and print the result to the console.

function sum(numA, numB) {
  let sum = 0;
  
  for (let i = numA; i <= numB; i++) {
    sum += i;
  }
  
  return sum;
}

console.log(sum(1, 3));
console.log(sum(1, 100));

Next Session

Arrays

Objects

C4-Session9

By Sharynne Azhar

C4-Session9

  • 11