notes:
- every method is a function , but not every function is a method.
- functions are objects
- scope: variable "visibility", the location where a variable is defined dictates where we have access to that variable.
- function scope
-
let msg = "I am so happy today"; function help{ let msg = "I'am on fire"; msg; //" I am on fire", local variable } msg; //"I am so happy today" , global variable
-
- block scope
-
let radius = 8; if(radius > 0){ const PI = 3.14; let circ = 2 * PI * radius; } console.log(radius); // 8 console.log(PI); // not defined console.log(circ); //not defined
-
lexical scope
-
function outer() { let hero = "balck"; function inner() { let cry = `${hero}, please save me!`; console.log(cry); } inner(); } outer(); // balck, please save me!
- function expressions
-
const square = function (num){ return num * num; } square(7); //49
- higher order functions
- functions that operate on/with other functions, they can
- accept other functions as arguments
- return a function
-
function callTwice(func){ func(); func(); } function laugh(){ console.log("HAHAHA"); } call(laugh); //pass a function as an arg; //HAHAHA //HAHAHA
- returning functions
-
function rangeFunc(min, max){ return function(val){ return val >= min && val <= max; } } const AgeRange = rangeFunc(18, 100); AgeRange(17); // false AgeRange(68)//true
- Methods
- we can add functions as properies on objects
- we can call them methods
-
const math = { multiply: function(x,y){ return x*y; }, divide: function(x,y){ return x/y; }, square: function(x){ return x*x; } };
shorthand
-
const math = { multiply(x,y){ return x*y; }, divide(x,y){ return x/y; }, square(x){ return x*x; } } math.multiply(3,2) //6
- this in methods, use the keyword this to access other properties on the same object
-
const person = { first: 'Lily', last: 'Li', fullName(){ return `${this.first} ${this.last}` } } person.fullName(); // "Lily Li" person.last = "Lyee"; person.fullName(); //"Lily Lyee"
-