Functions Flashcards
calling a function defined with arguments with empty braces or fewer arguments
will not cause any error
ex.: function greet(person1, person2) {…}
it’s ok to call it greet(); and greet(“Max”); and greet(“Max”, “Kate”);
nested functions
function outer(){ let movie = "Some";
function inner(){ console.log(movie.toUpperCase()); }
inner();
}
- we call outer(), we can’t call inner() directly
- inner() is only called if it is not only declared but also invoked insided outer()
- the variables of outer() are visible in inner()
function expressions (anonymous)
const sum = function (x, y){ return x + y; }
in order to call it:
sum(1, 2);
functions are OBJECTS!!!
function expressions (named)
const sum = function add (x, y){ return x + y; }
in order to call it:
sum(1, 2);
functions are OBJECTS!!!
functions are OBJECTS!!! we can store them in an array
const sum = function (x, y){ return x + y; }
const subtract = function (x, y){ return x - y; }
const ops = [sum, subtract];
if we print it to console - it will just print the descriptions of functions as objects, but we can also call them
ops0 // 3
for(let func of ops){ let result = func(1, 3); } //this will call each function in ops with the same parameters
functions are OBJECTS!!! we can define values of object attributes as functions
const sum = function (x, y){ return x + y; }
const thing = { doSmth: sum }
thing. doSmth(); will execute the sum function
thing. doSmth will just print it
high order functions
- can accept other functions as arguments
function somefun(func){ func(); func(); }
- can return functions
function somefun(min, max){ return function(val){ return val >= min && val <= max; } }
const inRange = somefun(10, 90);
inRange(13); //true
inRange(100); //false
callback function
function passed into another function as an argument and then invoked!!! inside this another function
function somefun(func){ //func is a callback!!! func(); func(); }
callback function can be anonymous
example.
setTimeout(func, 5000) is a built-in browser function that executes the function passed as argument after the specified number of milliseconds
- we can define func separately and name it
function myFunc(){ alert("yes"); }
setTimeout(myFunc, 50000)
- OR ANONYMOUS function directly:
setTimeout(function(){ alert(“yes”);}, 50000);
hoisting
- this will work without error (hoisting, the interpreter finds the function definiton although it is below)
howl();
function howl(){ console.log(“…”);}
- if we assign to var (function expression), then it will follow the rules of hoisting for var
howl();
var howl = function { console.log(“…”);}
this will throw Uncaught TypeError: howl is not a function, because according to the rules of hoisting for var - in this case, howl is undefined. The interpreter rearranges the code like this. So it can not call something undefined
var howl; //undefined var
howl();
howl = function { console.log(“…”);}
BUT. If we do console.log(howl) - it will show undefined. (no error thrown). Because this var is undefined due to hoisting
- If we use in case 2. let or const instead of var - there will be exceptions thrown, also according to the hoisting rules for let and const
Uncaught ReferenceError
forEach
accepts a callback and performs it on every element of the given array
nums.forEach(function(n){ //n represents the element
console.log(n*n);
})
you can also use index of the element in the array as second parameter
nums.forEach(function(num, index){ //n represents the element
console.log(index, num);
})
OR with a separate named function
function triple(num){ console.log(3 * num); }
nums.forEach(triple);
map
creates a new array with the results of calling a callback on every element in the array
const texts = [“text1”, “text2”];
const caps = texts.map(function(text){ return text.toUpperCase(); });
now caps is an array and it has values of texts in upper case
in the function you MUST RETURN value that represents what to do with the original value. Otherwise, map will not work
arrow functions
const square = function(num){ return num*num; }
const square = (num) => { return num*num; }
if you have just one param:
const square = num => { return num*num;}
with zero params:
const square = () => {…;}
arrow functions with implicit returns
if you return something in the function and this is a one liner, no other logic instead of this
const square = num => { return num*num;}
you can say this:
const square = num => ( num*num )
OR EVEN
const square = num => num*num
find
finds and retrieves element from array. Only one! stops after the first one
needs to return true or false
let movies = [“m1 film”, “m2 film”]
const movie = movies.find(movie => { return movie.includes('m1'); } )
const movie = movies.find(movie => (movie.indexOf(‘m1’) === 0; ) )
filter
we pass in a test function that returns true or false. If for an element it returns true, the element is returned in the resulting array. We are not removing elements, just creating a copy
const nums = [2, 3, 6, 7]
const odd = nums.filter(num => n % 2 === 1);
every
returns true if all elements in the array pass the provided function
const words = [“abc”, “cde”, “dfg”];
const allLengthThree = words.every(word => word.length === 3) // true
some
returns true if any element in the array passes the provided function
const words = [“abc”, “cde”, “dfg”];
const anyStartsWithd = words.some(word => word[0] === ‘d’) // true
sort
if we have an array of numbers, the default behavior of sort without arguments is to sort them like strings
[12, 3000, 35.99, 400.5, 9500, 99.99]
in order to change this behavior - we need to pass the function
const sort = prices.sort((a, b) => a - b);
[12, 35.99, 3000, 400.5, 9500, 99.99]
if function returns a negative - it sorts a before b
if a positive - b before a
if 0 - nothing changes
sort mutation
sort mutates the original array!!!!
const sort = prices.sort((a, b) => a - b);
now we have two array names pointing to the same array object, which is sorted by prices.sort!!!
to avoid this - use slice()
const sort = prices.slice().sort((a, b) => a - b);
reduce
is called on an array ([1, 2,3].reduce(callback)), takes a callback and reduces the array to a single value according to the callback, returns this value
- sum every element in array
- product of all elements
- find the max value
the callback has two arguments:
- accumulator will store the end result of reduce - starts as the first value of the array
- currentValue represents each individual element in array - starts as the second value of the array
[4, 2, 3].reduce((accumulator, currentValue) =>{
return accumulator + currentValue;
});
First call:
acc = 4, cur = 2, return = 6
Second call:
acc = 6, cur = 3, return = 9
we can also pass as a second argument, after callback, our own initial value of accumulator
[4, 2, 3].reduce((accumulator, currentValue) =>{
return accumulator + currentValue;
}, 100); //109
reducing arrays to objects
const answers = [‘y’, ‘n’, ‘n’, ‘n’, ‘y’]
return object that has the number of yeses and the number of no-s
const stats = answers.reduce((answersStats, answer) => { answersStats[answer] = (answersStats[answer] || 0) + 1; return answersStats; }, {});
/////// { 'y' : 2, 'n' : 3 }
default parameters
function multiply(x, y = 3){ return x*y; } multiply(2); // 6
important is that all default parameters are gathered towards the end of the list, because this will not work
function multiply(x = 3, y){ return x*y; }
multiply(2) //NAN. x is assigned 3, y is NAN
default parameters - other options
function multiply(x, y){ if (typeof x === 'undefined'){ x = 1;} return x*y; }
function multiply(x, y){ x = typeof x === 'undefined' ? 1 : x; return x*y; }