Udemy - The web developer camp

JavaScript Callback and Array Methods

Hanachoi 2022. 10. 25. 14:08

#forEach

  • It accepts a callback function. It calls the function once per element in the array. 
  • This used more often before for..of was made. 
  • It allows run a function, run some code once per item in some array. So whatever function we pass in that function will be called once per item, where each item will be passed into the function automatically. 
const numbers = [1,2,3,4,5,6,7,8,9,10];

function print(element){
	console.log(element)
}

// we need to put callback in parentheses. Defind a function ahead of this.

numbers.forEach(print) //1,2,3,4,5,...
  • forEach is going to do it one time per element, but it's passing in the element. But this way is not the most common way. We most commonly see is defining a function in parentheses.
numbers.forEach(function(el){
	console.log(el)
})
  • This function is one-time running function, so it is not something we plan on calling again. 
  • We learned about for..of loop and it also prints out each element, which is easier to read. 
for(let el of numbers){
	console.log(el);
} //It prints the same result out.
  • You can print out only even numbers like this
number.forEach(function (el){
	if(el%2 ===0){
    	console.log(el)
    }
})
  • For example, you have an array about movies and rate. You can print each title with rate 
const movies = [
	{
    	title : 'Amadeus',
        score : 99
    },
	{
    	title : 'Stand by me',
        score :85
    },
    {
    	title : 'Eternal Sunshine',
        score : 99
    },
    {
    	title : 'Parasite',
        score : 95
    }
]

movies.forEach(function(movie){ //movie will be each element. 
	console.log(`${movie.title}` - ${movie.score} /100)

})

 

# Map

  • Map creates a new array with the results of calling a callback on every element in the array.
  • It is similar to forEach in the sense that it accepts a callback function and it runs that function once per element in the array. But what's very different is that it then generates a new array using the result, using the return value of that callback.
  • Whatever the return value is, map take that and make a new array to add values. 
const numbers = [1,2,3,4,5,6,7,8,9,10]

const doubles = numbers.map(function(numb){
	return num*2;
}) 

//[2,4,6,8,...]

//It is going to make new array, and Map pass this elements to the function
  • You can get new array with all of these movie titles and also make it print uppercase out. 
const movies = [
	{
    	title : 'Amadeus',
        score : 99
    },
	{
    	title : 'Stand by me',
        score :85
    },
    {
    	title : 'Eternal Sunshine',
        score : 99
    },
    {
    	title : 'Parasite',
        score : 95
    }
]

const movieTitles = movies.map(function(movie){
	return movies.title.toUpperCase()
})
  • You need Map when you need to have a portion of data or double them. 

 

#Arrow functions 

  • It is new function syntax and more compact to a regualr function expression. You can write a function without function keyword. 
  • It is very useful especially where we are passing a function in that it only exists to be passed into this other function called map. It is just an augument that we're never reusing it. 
const title = movies.map(function(movie){
	return movie.title.toUpperCase();
})

// we are not going to reuse this map function agian. In this situation, arrow function is very useful
  • When you create a function, you can use this arrow function. It cannot exist itself. need to be saved in a variable. 
const square = (x) =>{
	return x * x ;
}
  • You can make a arrow function without an arguement. But you still need parenthese and that space even though you don't need any parameter. 
const rollDie = ()=>{
	return Math.floor(Math.random()*6)+1
}
  • Also If you just need only single parameter, you don't need parentheses. But if you need more than two parameters, you have to have parentheses. 
const square = x =>{
	return x*x;
}

 

#  Implicit return of arrow function.

  • There is a way to make it way more compact. This is only working with arrow function, not other function expression.
  • Basically we can get rid of return keyword in certain situation. If you replace the curly braces with parenthese, this is new syntax with arrow function to make it implicit return. 
const rollDie = ()=> (
	Math.floor(Math.random ()* 6) + 1 
)
  • Implicit returns are useful to make code short. Also when this function is really simple and short, you can skip parentheses and make it on one line.
  • This way cannot take more than one expression. If there are two expression, it doesn't know what to return. Implicit return only work when it has one value which is very clear. 
const add = (x,y) = > x+y

 

#Summary of arrow function. 

const newMovies = movies.map(function(movie){
	return `${movie.title} - ${movie.score / 10}`
}
  • You can use arrow function to make it shorter.  even more you can make it  on one line and can remove parentheses.
const newMovies = movies.map((movie) => (
	 `${movies.title} - ${movies.score / 10 }` 
))

 

#setTimeout and setInterval

  • These are not array methods and they delay, wait or pausing excusion and postpone excusion. 
  • In other programming languages, You can write 'sleep' or 'pause' to pause your function between, but in JS, you need to have callback function 
  • setTimeout needs two things, one of them is call back, and second one is a number of mmsecond to delay
//In other language, working like this
print"HELLO"
pause(3000)
print"are you still there?"


//In Js, other way to work
setTimeout(() =>{
	console.log("Hello!")
}, 300)
//You need ( handler, seconds)
  • It is not working without callback function. 
  • setInterval is a way to call a function  and callback every mm seconds. We repeat something in interval 
setInterval(()=>{
	console.log(Math.random())
},2000)

//It continues this interval over and over
  • clearInterval is to stop Interval and you can stop it during page is open. You need id when you run clearInterval
const id = setInterval(()=>{
	console.log(Math.random())
},2000);

 

#Filter 

  • Filter is used when we have some array of elements where we want to filter out or make a subset in a new array.
  • Filter creates a new array with all elements that pass the test implemented by the provided function. 
  •  We need a callback function and it should be a boolean value and if it returns true of any element, it will be added in filtered array, otherwise it is ignored.
const numbers = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]

numbers.filter((n)=>{
	return n === 4 
})

//You will have new array when it gets 4
  • It just forming new array and no effect to original array. 
  • You can combine map and filter together.
const goodMovies = movies.filter(m => movies.score > 80)
const goodTitles = movies.map (m =>movies.title)

// you can combine these two.

movies.filter(m => m.score > 80).map(m => m.title);

 

#Some and  Every methods

  • They are boolean method, so they always return true or false value. They are ways to test. 
  • every : it tests wether all elements in the array pass the provided function. It returns a Boolean value. 
  • Every element in array passed some test and it tests every elements wheter it is true or not and it returns every function true. 
  • Each element in array will be passed into callback and this callback returns if it is true or false. 
const exams = [80, 90, 92, 82,78,77,90,81]

exams.every(score => score >= 70)
//Every element is higher than 70, so it reutnrs true.


const exams = [80, 90, 92, 82,60,77,90,81]
exams.every(score => score >= 70) // false cuz one of the elements is less than 70.
  • some : it is similar to every ,but returns true if ANY of the array elements pass the test function.  It only cares if only one or more is true.

 

#Reduce.

  • It takes some array and reduce it down to single value in array at the end of the day.  
  • 배열이 있으면 각각의 요소들을 순서대로 지나가면서 연산을 할 수 있음. 
[3, 5, 7, 9,11].reduce ((accumulator, currentValue) =>{
	return accumulator + currentValue;
});
  • The first parameter named accumulator is basically the thing we need to reduce it
  • currentValue represents each individual element. 
const prices = [9.99 , 1.50, 19.99, 49.99, 30.50];

let total = 0;
for(price of prices ){
	total += price
}
console.log (total)

//This for statement is similar with Reduce function.


const total = prices.reduce((total,price) =>{
	return total + price 
})


const total = prices.reduce((total,price) => total + price)
  • It calculate each element of the array, in order, passing in the return value form the calculation on the preceding element. 
  • You can do adding, dividing or multiplication etc.
  • You can also find minimum value or maximum value in array.
const minPrice = prices.reduce((min,price)=> {
	if(price < min ){
    	return price;
    }
    return min;
})
  • You can find a highest rated movie when you have an array of movies
const bestMovies = movies.reduce((bestMovie,currMovie)=>{
	if(currMovie.score > bestMovie.score){
    	return currMovie;
    }
    return bestMovie;
})
  • It is not just about reducing things down to a single value via math. It could be via comparison like we are doing here. It could be addition or multiplication. 
  • The point of produce is to just boil things down, to somehow end up with a single value. it is up to us how we get there. 
  • We can also initailize the accumulator as starting point. 
const evens - [2,4,6,8];

evens.reduce((sum,num)=> sum + num, 100 )
// It will start at 100 and then add things
  • The second value will be initail value. 

 

# Arrow function and 'this'

  • Arrow function works in a different way with a regular function when you use 'this' keyword.
const person = {
	firstName : 'Viggo',
    lastName : 'Mortensen',
    fullName : function (){
    	`${this.firstName} ${this.lastName}`
    }
}

person.fullName() //'Viggo Mortensen' this is working well

const person = {
	firstName : 'Viggo',
    lastName : 'Mortensen',
    fullName :  () => {
    	`${this.firstName} ${this.lastName}`
    }
} // But when you change it into arrow function, it will return undefined undefiend
  • Inside of arrow function, keyword 'this' just refers to that scope that it is created. In this case, this is just refer to window object. 
  • In a regular function, this is not related to the scope where the function is created. It just related to how the function is  exactuated. 
  •