Functions Flashcards

1
Q

calling a function defined with arguments with empty braces or fewer arguments

A

will not cause any error
ex.: function greet(person1, person2) {…}

it’s ok to call it greet(); and greet(“Max”); and greet(“Max”, “Kate”);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

nested functions

A
function outer(){
  let movie = "Some";
  function inner(){
    console.log(movie.toUpperCase());
  }

inner();
}

  1. we call outer(), we can’t call inner() directly
  2. inner() is only called if it is not only declared but also invoked insided outer()
  3. the variables of outer() are visible in inner()
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

function expressions (anonymous)

A
const sum = function (x, y){
  return x + y;
}

in order to call it:

sum(1, 2);

functions are OBJECTS!!!

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

function expressions (named)

A
const sum = function add (x, y){
  return x + y;
}

in order to call it:

sum(1, 2);

functions are OBJECTS!!!

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

functions are OBJECTS!!! we can store them in an array

A
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
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

functions are OBJECTS!!! we can define values of object attributes as functions

A
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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

high order functions

A
  1. can accept other functions as arguments
function somefun(func){
  func();
  func();
}
  1. 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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

callback function

A

function passed into another function as an argument and then invoked!!! inside this another function

function somefun(func){ //func is a callback!!!
  func();
  func();
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

callback function can be anonymous

A

example.
setTimeout(func, 5000) is a built-in browser function that executes the function passed as argument after the specified number of milliseconds

  1. we can define func separately and name it
function myFunc(){
  alert("yes");
}

setTimeout(myFunc, 50000)

  1. OR ANONYMOUS function directly:

setTimeout(function(){ alert(“yes”);}, 50000);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

hoisting

A
  1. this will work without error (hoisting, the interpreter finds the function definiton although it is below)

howl();

function howl(){ console.log(“…”);}

  1. 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

  1. 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
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

forEach

A

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);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

map

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

arrow functions

A
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 = () => {…;}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

arrow functions with implicit returns

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

find

A

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; ) )

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

filter

A

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);

17
Q

every

A

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

18
Q

some

A

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

19
Q

sort

A

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

20
Q

sort mutation

A

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);

21
Q

reduce

A

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

22
Q

reducing arrays to objects

A

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
}
23
Q

default parameters

A
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

24
Q

default parameters - other options

A
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;
}
25
Q

spread for function calls

A

Math.min and Math.max only accept a list of numbers, not an array

Math.min(1,2,3) // works
const nums = [1,2,3];
Math.min(nums) // error that number is expected

but we can spread the array, then it will work
Math.min(…nums);

if we pass a string with … - it will be spread into characters

26
Q

spread in array literals

A

combine arrays

const newar = […arr1, …arr2];

the same can be done with arr1.concat(arr2)

when we do const newar = arr1 –> they point to the same array object, whereas newar = […arr1] –> a clone

(object references inside those arrays will still point to the same objects of course)

spreading string into array

const arr = […‘abc’, …‘def’, …‘fg’]; // will result in an array of separate characters

27
Q

spread in object literals

A
const canine = {
  family: 'Canine',
  furry: true
}
const dog = {
  ...canine,
  isPet: true,
  adorable: true
} // will result in dog object with all the properties from canine, and its own properties isPet and adorable

if they have the same properties, the last one overwrites the value of the previous ones

spreading objects does not work in the context of an array!!!

const arr = […dog]; //error

but the oppositve works (spreading array inside an object)

{…[1,2,3]} // results in {0:1, 1:2, 2:3}
{…‘abcdf’} // results in {0:’a’, 1:’b’, and so on}

28
Q

arguments object

A

array-like object, but not array, does not support array’s methods, but using spread we can turn it into array

we use the word arguments to represent the object. For ex., we want to sum all the arguments, but we don’t know how many there could be

functions sum(){
  console.log(arguments);
}

sum(1, 2, 3); // will print these numbers

To actually sum these numbers we need reduce(), but it works on arrays, and an arguments object is not an array. So we need to turn it into array

function sum(){
  const args = [...arguments];
  return args.reduce((total, curVal) => {
    return total + curVal;
  })
}
29
Q

arguments object together with defined arguments

A

suppose, we have not only first and last name, but also a number of titles, middle names etc

function fullName(firstName, lastName){
  console.log(arguments); //this will print ALL arguments including firstName and lastName
}

so when using arguments object together with defined arguments, we need to remember that these separate arguments are also part of the arguments object. So we need to adjust indexing

30
Q

arguments object and arrow functions

A

don’t work together

const sum = () => {
  console.log(arguments); /// ERROR
}
31
Q

rest params

A

the same as spread, only used as argument to function. Use it instead of arguments object when you don’t know how many parameters you are going to pass to function

This time nums is an actual array!

function sum(...nums){
  return nums.reduce((total, curVal) => {
    return total + curVal;
  })
}

and we can also mix it with separate arguments! cool

function fullName(firstName, lastName, …titles){
console.log(firstName);
console.log(titles);
}

you can’t have multiple rests!!

and rests should go last!

can be used in arrow function

const mult = (...nums) => {
  return nums.reduce((total, cur) => total*cur)
}
32
Q

Destructuring arrays

A

const race = [“FirstRunner”, “SecondRunner”, “ThirdRunner”, “FourthRunner”, “Fifth”];

to address the first three elements we could use the normal syntax

const first = race[0];
const second = race[1];

or with destructuring in one line:

const [first, second, third] = race

now we have three separate variables (first, second, third) - each holding a value under the corresponding index in the array

so

const first = “FirstRunner” and so on

Moreover. You can skip some elements

const [first, , , fourth] = race
now fourth holds the value “FourthRunner”

33
Q

Destructuring arrays + rest

A

const race = [“FirstRunner”, “SecondRunner”, “ThirdRunner”, “FourthRunner”, “Fifth”];

const [winner, …others] = race

others is now an array with “SecondRunner”, “ThirdRunner”, “FourthRunner”, “Fifth”

and we can also skip
const [winner, ,…others] = race

now others holds “ThirdRunner”, “FourthRunner”, “Fifth”

34
Q

Destructuring objects

A
const runner = {
  name: "Tata",
  last: "N",
  country: "Russia"
}

const {name, country} = runner;

now we have two variables name and country with the values from the object.

if we specify a non-existing property, the var will be created as undefined

const {name, country, religion} = runner;

religion is undefined

if we want to have different names for variables, we can do this:
const {last: surname, country: nation} = runner;
now we have variables surname and nation holding the values of properties last and country

35
Q

Destructuring objects + rest

A
const runner = {
  name: "Tata",
  last: "N",
  country: "Russia",
  age: 36
}

const {name, last, …other} = runner;

now we have one var for name, one for last, and the rest of the properties is collected in the object named other
{ country: “Russia”,
age: 36
}

36
Q

Nested destructuring

A
const runners =[ {
  name: "Tata",
  last: "N",
  country: "Russia",
  age: 36
},
{
  name: "Tatatata",
  last: "ttt",
  country: "Russia",
  age: 45
}
]

const [, {country: nation}] = runners;

will skip the first element and store the property country of the second element in the variable nation

37
Q

destructuring params

A
const runner = {
  name: "Tata",
  last: "N",
  country: "Russia",
  age: 36
}
let's say, I have a function that only needs name and last from the runner. We could pass the whole object as param and use destructuring object inside
function print(runner){
  const{
    name,
    last
  }
 console.log(`${name} ${last}`)
}

OR we could pass as parameters only certain properties of a desctructured object

function print({name, last}){
 console.log(`${name} ${last}`)
}
========================
we can also pass a destructured array

const nums = [1, 2, 3, 4];

function showNums([first, second]){
  console.log(`${first} ${second}`);
} //will print 1 and 2
38
Q

getters and setters

A

if we use methods with get or set key word in front of the name - this name can be used as property

class Timer {

  get remainingTime() {
        return parseFloat(this.durationField.value);
    }
    set remainingTime(time) {
        this.durationField.value = time;
    }
    tick = () => {
    //here we are using get and set at the same time
         this.remainingTime = this.remainingTime - 1;
    }
}