Udemy - The web developer camp

JavaScript new syntax

Hanachoi 2022. 11. 12. 11:33

# Default params

  • It is optional to use parameter when you use a function. If you don't have any parameter to use, it will take defalut parameter. 
const rollDie(numSides){
	return Math.floor(Math.random() * numSides) + 1 
}

rollDie(20) // It will retern random numbers between 1 and 20. 20 is a parameter.
  • If you don't put any number in parentheses as a parameter, it will return 'NaN' because it is not defined.
  • We can check if we defined parameters with If statements. If there is no number in parentheses, It will take 6 as a parameter, and still works with any numbers you put in parentheses. 
  • But it is not really good way when you have more than one parameter. 
function rollDie(numSides){
	if(numSides === undefined){
    	numSides = 6
    }
}

rollDie() // You will get random numbers btw 1-6
  • New way is that you put equal sign and default directly in parameter parenthese.
function multiply(a,b=1){
	return a * b;
}

multiply (4) // 4
multiply (4,5) //20

// a doesn't have default parameter, so whatever argument you put, it will be the first one
  • So you can change it with a new way. It is way more easy to read. 
function rollDie(numSides = 6){
	return Math.floor(Math.random() * numSides) + 1
}
  • You can use multiple default parameters but the order matters.
function greet(msg, person){
	console.log(`${mag}, ${person}!`)
}

greet('HI', 'James') // HI, James!


function greet(msg ='Hi there', person){
	console.log(`${mag}, ${person}!`)
}

greet('James') // James, undefined
  • When you just put name of the person, it will not notice if it is name. So you should always put defalut value on second or third spot. Parameter without default  should be the first one. 
function greet(person , msg = 'Hey there',puc = '!!!'){
	console.log(`${mag}, ${person} $ {puc}`)
}

greet(James,'Hi there', '!!!') // 'Hi there, James!!!'

 

 

# Spread (function calls )

  • Spread syntax allows an iterable such as an array to be expanded in places where zero or more arguements (for function calls ) or elements (for array literals) are expected, or an object expression to be expanded in palces where zero or more key- value pairs (for object literals) are expected.
  • The key word in this definition is 'expanded'. It is the idea of taking something and spead it out. 
  • Maht.max lets us know what is the biggest argument. But Math.max itself cannnot distinguish what to do. 
Math.max(13,4,5,21,3,3,1,2,7,6,565234) //565234
Math.min(1,2,5) // 1

const nums = [13,4,5,21,3,3,1,2,7,6,565234] 
Math.max(nums) // NaN. It doesn't know what to do


//If you have this array and want to know what is the largest number in this array, you can use spread
Math.max(...nums) // 565234
  • You can spead this arguements with three dots. ex > Math.max(...nums)
  • Here is another example.
  • When you put some strings with comma between them, it will print them with spaces. You can make it with spread as well. You can make arguemnts seperate with spaces.
console.log('asd','ad','asdasd','asdsa') // asd as asdasd asdsa
console.log(nums)// (13)[13,4,5,21,3,3,1,2,7]
console.log(...nums) // 13 4 5 21 3 3 1 2 7 6 ..
console.log(...'hello')// h e l l o
console.log('h','e','l') // h e l

 

 

# Spread(in Array Literals)

  • Spread in array literals create a new array using an existing array. Spread the elements from one array into a new array. 
const cats = ['Blue','Scout','Rocket'];
const dogs = ['Rusty','Wyatt'];

const allPets = [...cats, ...dogs] // ['Blue','Scout','Rocket','Rusty','Wyatt']
  • Spread just copy these two arrays and made a new array. The original cats and dogs arrays are not changed. It is very easily combined two arrays. 
  • The orders affect the result. When you change the order like [...dogs , ... cats], the order is going to be changed. 
  • You can also add new arguements in it.
[...dogs,...cats, 'speedy'] // ['Rusty','Wyatt','Blue','Scout','Rocket','Speedy']
  • You can also spread strings as well. 
['hello'] //'hello'
[...'hello'] // (5)['h','e','l','l','o']

 

 

# Spread (in Object literals)

  • Spread in Object Literals copies properties from one object into antoher object literal.
  • We can combine objects, make new object, copy it or tweak it .
const feline = {legs : 4, family : 'felidae'};
const canine = {isFurry : true, family : 'Caninae'}

{...feline} // you can copy this object
{...feline, color : 'black'} // you can add new argument and put it into new copied array. 

const catDog = {...feline, ...canine} // {legs : 4, family : 'caninae' , isFurry : true} 
// If they both have the same property, the second one wins and cover it. canine is the second one so catDog has 'caninae'
  • You can add new property with copying it with spread. Also when two objects have the same properties, the second one wins and cover it.  The order is important when they have the same property.
  • You can spread array and strings.
{...[2,4,6,8]} // {0: 2, 1:4, 2:6, 3:8}
{..."HIII"} // {0:'H', 1:'I',2 : 'I', 3: 'I'}
  • Then What do we use this for? Why do we spread the object? A lot of time, we copy objects with spread, especially  working with library toolsor React. Se we learn how to copy objects rather than mutating them.
  • Anther situation. Let's say you got a data of user. User needs to do enter email, password and username. You want to combine them and make a new object and add some new information. 
const dataFromForm = {
	email: 'blueman@gmail.com',
    password : 'tobias123!',
    username : 'tfunke'
}

const newUSer = {...dataFromForm, id:2345, isAdmin: false} // copy with spread and add some new information of user.
  • At the end of the day, it has to do with spreading one source of information into some destination.

 

# Rest

  • It looks like spread beacuse it also uses three dots, but something is entirely different.
  •  Whenever we write a function so far, we have access to this thing created for us automatically called arguments.It kinda of looks and acts like an array. It's what we call an array like object we can use in the indices to access elements out. 
  • It works exactly like an array, except we don't have access to array methods like push, pop and reduce.
  • It automatically will hold all of the arguments past to our function. But not available inside of arrow functions.
function sum (){
	console.log(arguments)
}

Math.min (1,2,3,4,5) // we can pass in a thousand arguments.
  • There's not way to specify that we want one, two or a thousand arguements insdie of the parameter list. But this arguments object is going to automatically collect all arguments.
  • But still cannot use array methods.
sum() // Arguments is empty. 

sum (34,65,77) // Arguments will contaion all of those values in an order
  • arguments object is not enough, so that's why Rest comes in. 
  • Rest params collects all remaining arguments into an actual array. 
// if just put nums, In sum(3,5) 5 will be ignored cuz it only has one parameter.
//with three dots, all arguements will be passed and saved in nums

function sum(...nums){ 
	console.log(nums)
}
sum(2,3,4,5,6) // you can add however you want

 

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

//It will add rest of the nums
function raceResults(gold,silver, ...everyoneElse){
	console.log(`Gold medal goes to : ${gold}`)
    console.log(`silver medal goes to : ${silver}`)
    console.log(`Thanks to everyone else : ${everyoneElse}`)
}

raceResults('Tammy','Todd','Tina','baily','james') 
//'Tina','baily','james' goes to everyoneElse

 

 

#  Array Destructuring

  • A short, clean syntax to 'unpack'. Values from arrays / Properties form objects into distinct variables.
  • It is a nice way to unpack it or extracting from array or object. We can unpack them and put them into distint variable.
  • You can take first and second one form the array and seprerate variable.
const scores = [929321,899341,888336,772739,543671,243567,111934];

// You can sperate them individually like const highScore = scores[0], but we have better way

const [gold,silver] = scores

gold // 929321
silver // 899341
  • The origianl scores array is not changed cuz it just copy the values into a seperate variable.
  • you can add more variables into this new array.
  • You have to have squre brackets and it indicates destructuring form array. 
const [gold,silver,bronze, ...everyoneElse ] = scores;

//gold will have the first value and silver will have the second value. 
//The rest of them will be in everyoneElse

 

# Object Destructuring

  • It is more usefule than array destructuring because the order doesn't matter
  • When you have sereval properties you want to single out and do something with it, you can destructure them using similar syntax.
  • The order doesn't matter. What's important here is the name of properties
const user = {
	email : 'harvey@gmail.com',
    password : '00123',
    firstName :'harvey',
    lastName : 'Milk',
    born : 1930,
    died : 1978,
    city: 'Sna Francisco'
}


const {email, password, firstName, lastName, city} =user;
  • You can make 5 seperated variables.  We just pull them out from the original user object. We just single them out into the variables.  It didn't change the original object.
  • Also you can extract them and rename them.
const {born : birthYear, died : deathYear } = user;
  • You put original property name with : and put the new name on the right side. born and died will be changed into birthYear and deathYear.
  • You can also add default value in the object. You need new property name and = , value. 
  • But like previous example, if that had died property already, it is not going to be changed. 
const user2 = {
	name : 'hannah',
    email : 'hannah@gmail.com',
    born : 1990
}

const{died = 'N/A'} = user2;

 

# Param Destructuring

  • When you define a function, we're writing out parameters between those parentheses, we can destructure the value that are being passed in. This is the most commly use in object.
function fullName(user){
	return `${user.firstName} ${user.lastName}`
} 

function fullName(user){
	const{fistName, lastName} = user;
    return `${fistName} &{lastName}`
}

// we can destructure this one 

function fullName({firstName, lastName}){
	return `${firstName} ${lastName}`
}
  • You can also give default to this parameter with = .
movies.filter((movie)=> movie.score>=90)
movies.filter({score} => score >=90)

movies.map(movie =>{
	return `${movie.title}(${movie.yeat}) is rated ${movie.score}`
})
// the same function 
movies.map({title,score,year}=>{
	return `${title} (${year}) is rated ${score}`
})
  • We don't need to make another variable, so it is better to use