Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

JavaScript Functions

Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1of 6

Sets and weak sets, similar to array but can't have duplicate values, each value

can only be use once


-const animals = new Set(); animals.add('lion'); animals.add('bear'); or
animals.add('lion').add('bear');
console.log(animals); // {'lion', 'bear'} animals.add('lion') add lion again,
the set will guard against duplicate values
-delete value, animals.delete('bear'); console.log(animals); // {'lion'}
-check values, let check = animals.has('lion') console.log(check); // true
-animals.size, check how many values console.log(animals.size); // 2
-animals.clear, delete all values in set (animals.clear); // Set(0)
-2 methods to iterate through sets for...of loop or .forEach
const mk = new Set(); mk.add('Scorpion').add('Sub-Zero').add('Liu Kang');
for (character of mk) mk.forEach( function (value)
{ console.log(character); } { console.log(value); } // Scorpion
Sub-Zero Liu Kang

turn array into set, let arrayAnimals = ['lion', 'horse', 'snake', 'mouse'];
const animals = new Set(arrayanimals);

Weak set, only use object data types, use same method types like add and delete
let nums = [1, 2, 3, 4]; let weakSet = new WeakSet(nums); console.log(weakSet);
// {Array(4)}, no value output

Maps(perform better involving adding and removing key value pairs, as object is not
optimal), allow keys of any types, object covert keys to strings as map will not
-let gameMap = new Map(); .set to add value pairs, gameMap.set('Name',
'Mario').set(2, 'number two').set(true, 'boolean');
-returns the relevant value .get, let getInfo = gameMap.get('Name');
console.log(getInfo); // Mario
-returns boolean whether element exists .has, let hasInfo = gameMap.has('Name');
console.log(hasInfo); // true
-delete info inside map, let deleteInfo = gameMap.delete(true);
console.log(deleteInfo); // 'Name' => 'Mario', 2 => 'number two' true,
'boolean is deleted
-check how many values, gameMap.size // Map(2) {'Name' => 'Mario', 2 =>
'number two'}
-3 methods to iterate though maps, keys(), values(), entries()
keys() loop over the key/name in key value pairs, for (let key of gameMap.keys())
{ console.log(key); } // Name 2 true
values() loop over the value in key value pairs, for (let value of
gameMap.values()) { console.log(value); } // Mario number two boolean
entries() loop over both key and value in key value pairs, for (let [key, value]
of gameMap.entries() { console.log(`${key} has the value of ${value}); }
// Name has the value of Mario 2 has the value of number two...

Weak map, use object data, the keys most be objects, do not support iteration,
rarely used
let weakMap = new WeakMap(); output error when using non-object values

function is given to the array


both ways
let fruits = ['apple', 'orange']
function upperCase (fruit) {return fruit.toUpperCase(); }
let fruitsCap = fruits.map(upperCase); console.log(fruitsCap); // ['APPLE',
'ORANGE']

let fruits3 = fruits.every(


function (v) { return v.length > 3 }
); console.log(fruits3); // true

let fruitsCap = fruits.map(


function (fruit) { return fruit.toUpperCase(); }
); console.log(fruitsCap);

FUNCTION, can be treated as objects, divide our code into reusable parts, all the
code between the curly braces will be executed every time the function is called
invoke/excute functionName(); can add variables inside the function
name() { let title = 'Valorant'; }
4 ways to create function, 1. function declaration and expression(most common) 2.
arrow functions 3. function constructors(rarely used) 4. generator functions
function name is mandatory

-Parameters, variables that act as placeholders for the values that are to be input
to a function when called
Parameters
-function declaration, function area(width, height) {
console.log(width * height);
} Arguments, actual values that are inputed/passed into a function when called
area(5, 3); // 15

-function, don't check the number of arguments recieved


function ninja (color, weapon) { console.log(`${color} ninja uses the $
{weapon}`); } ninja('Black') // Black ninja uses the undefined
function add (num1, num2) { console.log(num1 + num2); } add(2); // NaN
(because 2 + undefined);
add(2, 3, 4, 5) // 5 more arguments than parameters, function will ignore the
extra arguments
arguments object keyword, access extra arguments, array like object
{ console.log(arguments); }
Arguments(4) [2, 3, 4, 5] 0:2 1:3 2:4 3:5 arguments.length // 4;
arguments[1] // 3;

-Anonymous Function, only works with an event handler


btn.addEventListener('click', function () { console.log('Good Morning'); });

-Function Expressions, assign anonymous function to a variable and using the


variable we are able to invoke the function, function name is optional
let games = function() { console.log('Valorant'); console.log('LOL'); } add
function name and invoke it will cause error in function expression
games(); // Valorant LOL let
games = function functName () {} functName(); // error
Can assign function value to another variable and can use new variable to invoke
the function
let anotherVar = games(); anotherVar(); // Valorant LOL

Function declaration can be invoked earlier than they are created, unlike
expression, Javascript store in memory any global scope that is why it have
access it anywhere myFunct(); // Hi myFunct(); // error,
because function expression is created once we get to the line it's on
function myFunct() { console.log('Hi'); } let myFunct = function()
{ console.log('Hi'); }
-Default parameters, allow parameter to have a predetermined value in case no
argument is passed into the function or the argument is undefined,
is always at the end of the parameter list, in order to counteract any missing
arguments that turn into undefined
function favFood (response = "empty, please add your answer") {
console.log(`Your favourite food is ${response}`); }
favFood(); // Your favourite food is empty, please add your answer
favFood('pizza') // Your favourite food is pizza

-Default Error
function favGame (game) { if (game === undefined) { console.log('Please enter your
fav game!');
} else { console.log(`Your fav game is ${game}`); } } favGame(); // Please
provide yout fav game!

-Return, evaluates and ends the execution of the function immediately, specifies a
value to be returned to the function caller,
return statement send a value back out of a function, can have only 1 return per
code block { }
most commonly assign the function call to another variable
monitorCount takes argument for rows and columns and returns a value equal
to rows * columns
function monitorCount(rows, columns) {
return rows * columns; }
*const numOfMonitors = monitorCount(4, 5);
console.log(numOfMonitors); // 20 need to assign a new variable if return is
present inside the function

function favNum (num) {


return num; }
*let myfavNum = favNum(3);
console.log(`my fav num is ${myfavNum}`);
// my fav num is 3

-Helper Function, return value of a function can be used inside another function
function multiplyByNineFifths(number) {
return number * (9/5);
};
function getFahrenheit(celsius) {
return multiplyByNineFifths(celsius) + 32;
};
const temperture = getFahrenheit(15); longer code
console.log(temperture) // 59

-Another way to define a function (Function Expressions)


const plantNeedsWater = function(day) {
if(day === "Monday") return true;
else { return false; } };
console.log(plantNeedsWater("Tuesday")); // false

-Arrow function
const plantNeedsWater = (day) => {
if (day === "Monday") {
return true;
} else {
return false; } };
console.log(plantNeedsWater("Wednesday")); // Wednesday shorter code
all comparison operators ===, <, >, <=, >= returns boolean true or false value
function isEqual(a, b) { return a === b; } console.log(isEqual(10, 15)) //
false

-const canIVote = age => { const canIVote = (age) => age >= 18 ? true :
false
if (age >= 18) { console.log(canIVote(19))
return true;
} else {
return false;
}
};

function, also works const agreeOrDisagree =


(first, second) => (first === second)
const agreeOrDisagree = (first, second) => { ? "You agree!" : "You
disagree!"
if (first === second)
{ console.log(agreeOrDisagree("yep", "yep")) //
You agree!
return "You agree!"
} else {
return "You disagree!"
}
}; console.log(agreeOrDisagree("yep", "yep")) // You agree!

-const lifePhase = age => {


if (age < 0 || age > 140) {
return "This is not a valid age";
} else if (age < 4) {
return "baby";
} else if(age < 13) {
return "child";
} else if(age < 20) {
return "teen";
} else if(age < 65) {
return "adult";
} else {
return "senior citizen";
}
}; console.log(lifePhase(21)) // adult

-const finalGrade = (midterm, final, homework) => {


if ((midterm < 0 || midterm > 100) || (final < 0 || final > 100) || (homework <
0 || homework > 100)) {
return "You have entered an invalid grade."
}
let average = (midterm + final + homework) / 3
if (average < 60) {
return 'F'
}
else if (average < 70) {
return 'D'
}
else if (average < 80) {
return 'C'
}
else if (average < 90) {
return 'B'
} else {
return 'A'
}
}; console.log(finalGrade(50, 75, 75)) // D

-const names = ["Hole-in-one!", "Eagle", "Birdie", "Par", "Bogey", "Double Bogey",


"Go Home!"];
function golfScore(par, strokes) {
if (strokes == 1) {
return names[0]
} else if (strokes <= par - 2) {
return names[1]
} else if (strokes == par - 1) {
return names[2]
} else if (strokes == par) {
return names[3]
} else if (strokes == par + 1) {
return names[4]
} else if (strokes == par + 2) {
return names[5]
} else if (strokes >= par + 3) {
return names[6]
}
}
console.log(golfScore(4, 6)) // ouput Double Bogey

function caseInSwitch(val) {
let answer = "";
switch (val) {
case 1:
answer = "alpha";
break;
case 2:
answer = "beta";
break;
case 3:
answer = "gamma";
break;
case 4:
answer = "delta";
break;
}
return answer;
}; console.log(caseInSwitch(4)); // output delta

-Multiple Identical Options Switch Statement


function sequential(val) {
let answer = "";
switch (val) {
case 1:
case 2:
case 3:
answer = 'Low';
break;
case 4:
case 5:
case 6:
answer = 'Mid';
break;
case 7:
case 8:
case 9:
answer = 'High';
break; } return answer; } console.log(sequential(7)) // High

When using === else if is faster, but switch is more readable when making more than
3 comparisons
-Switch, else if, case values are tested with strict equality(===)
if (val == 1) { switch (val) { case is the value in if/else if
statements
answer = "a"; case 1: case 2:
} else if (val == 2) { answer = 'a'; answer = 'b';
answer = "b"; break; break;
} else { default:
answer = ""; answer = ''; }
}

Zero Parameters Single-Line Block


const functionName = () => {}; const sumNum = number => number
+ number; don't need parentheses, curly braces, or return key #

One Parameter Multi-Line Block


const functionName = paramOne => {}; # const sumNum = number => {
const sum = number + number;
return sum; };
Two or More Parameters
const functionName = (paramOne, paramTwo) => {};

Const plantNeedsWater = (day) => (day === "Monday" ? true : false);


console.log(plantNeedsWater("Monday")); // true even shorter code

You might also like