
function add(num1, num2) {
return num1 + num2
}
add(1, 2) // 3
const sub = function (num1, num2) {
return num1 - num2
}
sub(2, 1) //1
const greeting = function (name= 'Anonymous') {
return `Hi ${name}`
}
greeting() // Hi Anonymous
const myFunc = function (param1, param2, ...restParams) {
return [param1, param2, restParams]
}
myFunc(1, 2, 3, 4, 5) //[1,2, [3, 4, 5]]
myFunc(1, 2) // [1, 2, []]
const threeArgs = function (param1, param2, param3) {
return [param1, param2, param3]
}
threeArgs() // [undefined, undefined, undefined]
threeArgs(1) // [1, undefined, undefined]
threeArgs(2, 3) // [2, 3, undefined]
const noArgs = function () {
return 0
}
noArgs(1, 2, 3) // 0
const twoArgs = function (param1, param2) {
return [param1, param2]
}
threeArgs(1, 2, 3) // [1, 2]
const arrow1 = function (name) {
return `hello, ${name}`
}
// 1. function 키워드 삭제 후 화살표 작성
const arrow2 = (name) => { return `hello, ${name}` }
// 2. 인자가 1개일 경우에만 () 생략 가능
const arrow3 = name => { return `hello, ${name}` }
// 3. 함수 본문이 return을 포함한 표현식 1개일 경우에 {} & return 삭제 가능
const arrow4 = name => `hello, ${name}`
console.log(user.greeting()) // hello
const person = {
name: 'Alice',
greeting: function () {
return `Hello my name is ${this.name}`
},
}
console.log(person.greeting())
// Hello my name is Alice
const myFunc = function () {
return this
}
console.log(myFunc()) // window
const myObj = {
data: 1,
myFunc: function () {
return this
}
}
console.log(myObj.myFunc()) // myObj
const myObj2 = {
numbers: [1, 2, 3],
myFunc: function () {
this.numbers.forEach(function (number) {
console.log(this) // window
})
}
}
console.log(myObj2.myFunc())
const myObj3 = {
numbers: [1, 2, 3],
myFunc: function () {
this.numbers.forEach((number) => {
console.log(this) // myObj3
})
}
}
console.log(myObj3.myFunc())
const userInfo = {
firstName: 'Alice',
userId: 'alice123',
email: 'alice123@gmail.com'
// const firstName = userInfo.name
// const userId = userInfo.userId
// const email = userInfo.emai
// const { firstName } = userInfo
// const { firstName, userId } = userInfo
const { firstName, userId, email } = userInfo
console.log(firstName, userId, emai)
// Alice alice123 alice123@gmail.com
}
function printInfo({ name, age, city }) {
console.log(`이름: ${name}, 나이: ${age}, 도시: ${city}`)
}
const person = {
name: 'Bob',
age: 35,
city: 'London',
}
// 함수 호출 시 객체를 구조 분해하여 함수의 매개변수로 전달
printInfo(person)
// '이름: Bob, 나이: 35, 도시: London'
const obj = { b: 2, c: 3, d: 4 }
const newObj = { a: 1, ...obj, e: 5 }
console.log(newObj)
// {a: 1, b: 2, c: 3, d: 4, e: 5}
const profile = {
name: 'Alice',
age: 30,
}
console.log(Object.keys(profile))
// ['name', 'age']
console.log(Object.values(profile))
// ['Alice', 30]
const user = {
name: 'Alice',
greeting: function () {
return 'hello'
}
}
console.log(user.address.street)
// Uncaught TypeError: Cannot read properties of undefined (reading 'street')
console.log(user.address?.street) // undefined
console.log(user.nonMethod())
// Uncaught TypeError: user.nonMethod is not a function
console.log(user.nonMethod?.()) // undefined
const user = {
name: 'Alice',
greeting: function () {
return 'hello'
}
}
console.log(user.address && user.address.street) // undefined
// Bad
user?.address?.street
// Good
user.address?.street
// 위 예시 코드 논리상 user는 반드시 있어야 하지만 address는 필수 값이 아님
// user에 값을 할당하지 않은 문제가 있을 때 바로 알아낼 수 있어야 하기 때문에
console.log(myObj?.address)
// Uncaught ReferenceError: myObj is not defined
const jsObject = {
coffee: 'Americano',
iceCream: 'Cookie and cream',
}
// Object -> JSON
const objToJson = JSON.stringify(jsObject)
console.log(objToJson) // {"coffee":"Americano","iceCream":"Cookie and cream"}
console.log(typeof objToJson) // string
// JSON -> Object
const jsonToObj = JSON.parse(objToJson)
console.log(jsonToObj) // { coffee: 'Americano', iceCream: 'Cookie and cream' }
console.log(typeof jsonToObj) // object
JS에서 객체를 하나 생성한다고 한다면?
동일한 형태의 객체를 또 만든다면?
new constructor[([arguments])]
function Member(name, age, sId) {
this.name = name
this.age = age
this.sId = sId
}
const member3 = new Member('Bella', 21, 20226543)
console.log(member3) // Member { name: 'Bella', age: 21, sId: 20226543 }
console.log(member3.name) // Bella
push / pop
unshift / shift
arr.forEach(callback(item[, index[, array]]))
arr.forEach(function(item, index, array) {
// do something
})
콜백함수는 3가지 매개변수로 구성
반환값 : undefined
const names = ['Alice', 'Bella', 'Cathy',]
// 일반 함수
names.forEach(function (item, index, array) {
console.log(`${item} / ${index} / ${array}`)
})
// 화살표 함수
names.forEach((item, index, array) => {
console.log(`${item} / ${index} / ${array}`)
})
// 1번
const numbers1 = [1, 2, 3,]
numbers.forEach(function (num) {
console.log(num ** 2)
})
// 1
// 4
// 9
// 2번
const numbers2 = [1, 2, 3,]
const callBackFunction = function (num) {
console.log(num ** 2)
}
// 1
// 4
// 9
numbers.forEach(callBackFunction)
arr.map(callback(item[, index[, array]]))
const newArr = array.map(function(item, index, array) {
// do something
})
map 구조
반환값 : 배열의 각 요소에 대해 실행한 callback의 결과를 모든 새로운 배열
기본적으로 forEach 동작 원리와 같지만 forEach와 달리 새로운 배열을 반환함
// 1번
const names = ['Alice', 'Bella', 'Cathy',]
const result1 = names.map(function (name) {
return name.length
})
const result2 = names.map((name) => {
return name.length
})
console.log(result1) // [5, 5, 5]
console.log(result2) // [5, 5, 5]
// 2번
const numbers = [1, 2, 3,]
const doubleNumber = numbers.map((number) => {
return number * 2
})
console.log(doubleNumber) // [2, 4, 6]
const names = ['Alice', 'Bella', 'Cathy',]
// for loop
for (let idx = 0; idx < names.length; idx++) {
console.log(idx, names[idx])
}
// for...of
for (const name of names) {
console.log(name)
}
// forEach
names.forEach((name, idx) => {
console.log(idx, name)
})
let parts = ['어깨', '무릎']
let lyrics = ['머리', ...parts, '발']
console.log(lyrics)
// ['머리', '어깨', '무릎', '발']
filter
find
some
every