reading-notes

Class 7 - Programming with JavaScript

Control Flow


Functions

function myFunction(p1, p2) {
  return p1 * p2;   // The function returns the product of p1 and p2
}

Function Syntax

function name(parameter1, parameter2, parameter3) {
  // code to be executed
}

Function Return

let x = myFunction(4, 3);   // Function is called, return value will end up in x

function myFunction(a, b) {
  return a * b;             // Function returns the product of a and b
}

The result in x will be 12


Invoking (Calling) a Function

function toCelsius(fahrenheit) {
  return (5/9) * (fahrenheit-32);
}
document.getElementById("demo").innerHTML = toCelsius;

Variables

Using a Function as a Variable

let text = "The temperature is " + toCelsius(77) + " Celsius";

Local Variables

// code here can NOT use carName

function myFunction() {
  let carName = "Volvo";
  // code here CAN use carName
}

// code here can NOT use carName

Why Functions?


JavaScript Operators

let x = 10;
let x = 5;
let y = 2;
let z = x + y;
let x = 5;
let y = 2;
let z = x * y;

Types of JavaScript Operators

There are different types of JavaScript operators:


Arithmetic Operators

+      Addition
-      Subtraction
*      Multiplication
**     Exponentiation (ES2016)
/       Division
%       Modulus (Division Remainder)
++     Increment
--     Decrement


Assignment Operators

Operator     Example     Same As
=               x = y               x = y
+=               x += y               x = x + y
-=               x -= y               x = x - y
*=               x *= y               x = x * y
/=               x /= y               x = x / y
%=               x %= y               x = x % y
**=               x **= y               x = x ** y


Comparison Operators

Operator     Description
==               equal to
===               equal value and equal type
!=               not equal
!==               not equal value or not equal type
>               greater than
<               less than
>=               greater than or equal to
<=               less than or equal to
?               ternary operator


Logical Operators

Operator      Description
&&                 logical and
||                logical or
!                 logical not