함수
function name([parm[,parm,[...,parm]]]){
statements
return value
}
function funcName(){
statements
}
function add(num1, num2){
return numl1 + num2
}
add(1, 2)
const funcName = function (){
statements
}
function sub(num1, num2){
return numl1 - num2
}
sub(2, 1)
| () | 선언식 | 표현식 |
|---|---|---|
| 특징 | 익명 함수 사용 불가능 호이스팅 있음 | 익명함수 사용가능 호이스팅 없음 |
| 기타 | 사용권장 |
const greeting = function (name = 'Anonymous'){
return `Hi ${name}`
}
greeting() // Hi Anonymous
const myFunc = function (parm1, parm2, ....restPrams) {
return [param1, param2, restPrams]
}
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]
}
twoArgs(1,2,3) // [1,2]
함수와의 사용
함수 호출 시 인자 확장
function myFunc(x,y,z){
return x + y + z
}
let numbers = [1, 2, 3]
console.log(myFunc(...numbers)) // 6
나머지 매개변수 (압축)
function myFunc2(x, y, ...restArgs){
return [x, y, restArgs]
}
console.log(myFunc2(1,2,3,4,5)) // [1,2,[3,4,5]]
console.log(myFunc2(1,2)) // [1,2,[]]
const arrow = function (name){
return `hello, ${name}`
}
const arrow = name => `hello, ${name}`
function 키워드 제거 후 매개변수와 중괄호 사이에 화살표 작성
const arrow1 = function (name){
return `hello, ${name}`
}
const arrow2 = (name) => {return `hello, ${name}`}
함수의 매개변수가 하나 뿐이라면, 매개변수의 '()'제거 가능
const arrow1 = function (name){
return `hello, ${name}`
}
// 1. function 키워드 삭제 후 화살표 작성
const arrow2 = (name) => {return `hello, ${name}`}
// 2. 인자가 1개일 경우에만 () 생략 가능
const arrow3 = name => {return `hello, ${name}`}
함수 본문의 표현식이 한 줄이라면, '{}'와 'return' 제거 가능
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}`
// 1. 인자가 없다면 () or _로 표시 가능
const noArgs = () => 'No args'
const noArgs = _ => 'No args'
// 2-1. object를 return 한다면 return을 명시적으로 작성
const returnobject1 = () => (return {key:'value'})
// 2-2. return을 작성하지 않으려면 객체를 소괄호로 감싸야한다
const returnobject2 = () => ({key:'value'})
객체
const user = {
name :'Alice',
'key with space' : true,
greeting: function(){
return 'hello'
}
}점('.') 또는 대괄호('[]')로 객체 요소 접근
key 이름에 띄어쓰기 같은 구분자가 있으면 대괄호 접근만 가능
// 조회
console.log(user.name) // Alice
console.log(user['key with space']) // true
// 추가
user.address = 'korea'
console.log(user) // {name:'Alice', key with space : true, address:'korea', greeting:f}
// 수정
user.name = 'Bella' // Bella
console.log(user.name) // Bella
// 삭제
delete user.name
console.log(user) // {key with space : true, address:'korea', greeting:f}
console.log('greeting' in user) // true
console.log('country' in user) // false객체와 함수
const person = {
name : 'Alice',
greeting: function(){
return 'Hello ny name is ${this.name}'
},
}
console.log(person.greeting()) // Hello my name is Alice
| 호출 방법 | 대상 |
|---|---|
| 단순호출 | 전역 객체 |
| 메서드 호출 | 메서드를 호출한 객체 |
const myFunc = function(){
return this
}
console.log(myFunc()) // windowconst myObj = {
data : 1,
myFunc : function(){
return this
}
}
console.log(myObj.myFunc()) // myObj
// 사용 전
const name = 'Alice'
const age = 30
const user = {
name: name,
age: age,
}
const myObj1 = {
myFunc:function(){
return 'Hello'
}
}
// 사용 후
const name = 'Alice'
const age = 30
const user = {
name,
age,
}
const myObj1 = {
myFunc(){
return 'Hello'
}
}
const product = prompt('물건 이름을 입력해주세요')
const prefix = 'my'
const suffix = 'property'
const bag = {
[product] : 5,
[prefix + suffix]: 'value',
}
console.log(bag) // {연필 : 5, myproperty: 'value'}
// 적용 전
const userInfo = {
firstname:'Alice',
userId : 'alice123',
email : 'alice@gmail.com'
}
const firstName = userInfo.name
const userId = userInfo.userId
const email = userInfo.email
// 적용 후
const userInfo = {
firstname:'Alice',
userId : 'alice123',
email : 'alice@gmail.com'
}
const {firstName} = userInfo
const {firstName, userId} = userInfo
const {firstName, userId, email} = userInfo
console.log(firstName, userId, email)
const person = {
name:'Bob',
age: 35,
city:'London',
}
function printInfo({name, age, city}){
console.log('이름:${name}, 나이:${age}, 도시:${city}')
}
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
console.log(user.address?.street) // Undefined
console.log(user.nonMethod()) // Uncaught TypeError
console.log(user.nonMethod?.()) // Undefined
const user = {
name : 'Alice',
greeting: function (){
return 'hello'
}
}
console.log(user.address && user.address.street) // undefined
// 이전 예씨 코드에서 user 객체는 논리상 반드시 있어야 하지만 address는 필수 값이 아님
// user에 값을 할당하지 않은 문제가 있을 때 바로 알아낼 수 있어야 하기 때문
// Bad
user?.address?.street
// Good
user.address?.street
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
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
배열
const names = ['Alice', 'Bella', 'Cathy']
console.log(names[0]) // Alice
console.log(names[1]) // Bella
console.log(names[2]) // Cathy
console.log(names.length) // 3
| 메서드 | 역할 |
|---|---|
| push / pop | 배열 끝 요소를 추가 / 제거 |
| unshift / shift | 배열 앞 요소를 추가 / 제거 |
const names = ['Alice', 'Bella', 'Cathy']
names.push('Dan')
console.log(names[3]) // Dan
const names = ['Alice', 'Bella', 'Cathy']
console.log(names.pop()) // Cathy
console.log(names) // ['Alice', 'Bella']
names.unshift('Eric')
console.log(names) // ['Eric', 'Alice', 'Bella', 'Cathy']
const names = ['Alice', 'Bella', 'Cathy']
console.log(names.shift()) // Alice
console.log(names) // ['Bella', Cathy]
const numbers1 = [1, 2, 3]
numbers1.forEach(function (num) {
console.log(num ** 2)
})
// 1
// 4
// 9
const numbers2 = [1, 2, 3]
const callBackFunction = function (num) {
console.log(num ** 2)
}
numbers2.forEach(callBackFunction)
// 1
// 4
// 9
| 메서드 | 역할 |
|---|---|
| forEach | - 배열 내의 모든 요소 각각에 대해 함수를 호출 - 반환 값 없음 |
| map | - 배열 내의 모든 요소 각각에 대해 함수를 호출 - 함수 호출 결과를 모아 새로운 배열을 반환 |
arr.forEach(function(item, index, array){
})
const newArr = array.map(function(item, index, array))
const names = ['Alice', 'Bella', 'Cathy']
const result3 = names.map(function (name){
return name.length
})
const result4 = names.map((name) => {
return name.length
})
console.log(result3) // [5, 5, 5]
console.log(result4) // [5, 5, 5]
const names = ['Alice', 'Bella', 'Cathy']
// for loop
for (let idx = 0 ; idx <names.length; idx++){
console.log(names[idx])
}
// for...of
for (const name of names){
console.log(name)
}
// for Each
names.forEach((name) => {
console.log(name)
})
| 방식 | 특징 |
|---|---|
| for loop | - 배열의 인덱스를 이용하여 각 요소에 접근 - break, continue 사용 가능 |
| for ...of | - 배열 요소에 바로 접근 가능 - break, continue 사용가능 |
| forEach | - 간결하고 가독성이 높음 - callback 함수를 이용하여 각 요소를 조작하기 용이 - break, continue 사용 불가능 |