function hello() { console.log('hello~') }
const hello = function() { console.log('hello~') }
함수를 호출한 결과는 선언문/표현식 모두 같음
함수 선언부가 유효범위 최상단으로 끌어올려지는 현상
함수 선언문으로 작성했기 때문에 선언보다 호출을 먼저했지만 호이스팅 발생으로 에러없이 코드 실행 가능
hello() //hello~ function hello() { console.log('hello~') }
함수 내부에 아무런 내용이 없거나 return 에 값을 할당하지 않으면 함수를 호출했을 때 undefined
가 반환된다.
function hello() { return } console.log(hello()) //undefined
예제 1
function greeting(name) { return name + ' 안녕' } console.log(greeting('다빈')) //다빈 안녕 console.log(greeting()) //undefined 안녕
예제 2
function plus(num) { return num + 1 } console.log(plus(1)) //2 console.log(plus(7)) //8 console.log(plus()) //NaN = undefined + 1
위와 같은 상황을 미연에 방지하기 위해 개발자는 들어온 값이 없으면 (=undefined) 다른 값이나 메세지를 반환하라는 조건문을 추가할 수 있다.
function plus(num) { if (typeof num !== 'number') { console.log('숫자를 입력해주세요') return 0 } return num + 1 } console.log(plus()) //숫자를 입력해주세요 //0
function sum(a, b) { return a + b } console.log(1, 3) //4 console.log(7) //NaN
undefined
가 반환되면서 결과가 제대로 나오지 않는다.function sum(a, b = 1) { // 인수 b에 기본값 1을 지정 return a + b } console.log(7) //8
const user = { name: 'HEROPY', age: 85 }
방법 1
function getName(user) { return user.name } console.log(getName(user))
방법 2
function getName(user) { const { name } = user return name }
⭐ 방법 3 ⭐
//매개변수를 받을 때 바로 객체를 구조 분해 할당해서 받으면 코드가 훨씬 간단해진다. function getName({ name }) { return name }
방법 4
//찾으려는게 객체에 없는 값일수도 있으니 미리 기본값을 넣어주면 좋다. function getName({ email = '이메일이 없습니다.' }) { return email }
매개변수를 받을 때 바로 객체를 구조 분해 할당해서 받으면 코드가 훨씬 간단해진다.
const fruits = ['Apple', 'Banana', 'Cherry'] // 일반적인 방법 function getSecondItem(array) { return array[1] } console.log(getSecondItem(fruits)) //Banana // 구조 분해 할당 사용 function getSecondItem([,second]) { return second }
예제 1
function sum(...rest) { console.log(rest) } console.log(sum(1, 2)) console.log(sum(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)) // 결과 [1, 2] [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
전개 연산자를 사용하면 sum 함수로 들어오는 모든 인수를 배열 데이터로 받을 수 있다.
예제 2
function sum(a, b, ...rest) { console.log(rest) } console.log(sum(1, 2)) //3 console.log(sum(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)) //55 // 결과 [] [3, 4, 5, 6, 7, 8, 9, 10]
- 첫 번째 코드는 인수
1, 2
가a, b
에 할당되었기 때문에 rest 배열에는 아무런 값이 없고- 두 번째 코드는 인수
1, 2
를 제외한 나머지 값들이 모두 rest 배열에 들어갔다.
sum 함수 완성
function sum(...rest) { console.log(rest) return rest.reduce(function (acc, cur) { return acc + cur }, 0) } console.log(sum(1, 2)) //3 console.log(sum(1, 2, 3, 4)) //10 console.log(sum(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)) //55
배열의 reduce 메소드와 콜백 함수를 통해 sum 함수 완성
(reduce 메소드와 콜백 함수는 추후 학습 예정)
function sum() {}
const sum = function () {}
//NEW! 화살표 함수
const sum = () => {}
1. 함수의 내용(중괄호 내부)가 return
으로 시작하면 중괄호 { }
와 return
을 생략할 수 있다.
//정석 화살표 함수 const sum = (a, b) => { return a + b } const sum = (a, b) => a + b
return
으로 시작하지 않으면 생략할 수 없다!!const a = (x, y) => { console.log(x * y) return x * y }
2. 매개변수가 하나라면 매개변수를 감싼 소괄호를 생략할 수 있다.
중괄호 { }
와 return
키워드를 생략했을 때 남은 내용이 객체 데이터라면 소괄호 ( )
사이에 넣어줘야 한다.const b = x => {} //소괄호 생략 가능 const c = (a, b) => {} // 소괄호 생략 불가능 const d = () => { return { a: 1 } } //반환할 내용이 객체 데이터 const e = () => { a: 1 } // 잘못된 문법 const f = () => ({ a: 1 }) //올바른 문법
;()()
사용 방법
;(() => {})() //(F)(), 화살표 함수 ;(function () {})() //(F)(), 일반 함수 ;(function () {}()) //(F()) ;!function () {}() //!F() ;+function () {}() //+F()
예제
const loadImage = (url, cb) => { const imgEl = document.createElement('img') imgEl.src = url imgEl.addEventListener('load', () => { setTimeout(() => { cb(imgEl) }, 1000) }) } const containerEl = document.querySelector('.container') loadImage('https://i.pinimg.com/originals/1c/cf/f0/1ccff0a256a5dfd24bf32782326582f7.jpg', (imgEl) => { containerEl.innerHTML = '' containerEl.append(imgEl) })
⭐ 아아... 콜백 너무 어렵다
더 공부하고 복습할게요 ㅠ
함수에서 자기 자신을 다시 호출해 작업을 수행하는 방식
const userA = { name: 'A', parent: null } const userB = { name: 'B', parent: userA } const userC = { name: 'C', parent: userB } const userD = { name: 'D', parent: userC } const getRootUser = user => { if (user.parent) { return getRootUser(user.parent) } return user } console.log(getRootUser(userD)) //userA의 내용 { name: 'A', parent: null }
(참조) setTimeout과 setInterval을 이용한 호출 스케줄링
setTimeout
을 이용해 일정 시간이 지난 후에 함수를 실행하는 방법setInterval
을 이용해 일정 시간 간격을 두고 함수를 실행하는 방법setTimeout
은 일정 시간이 지난 후에 함수를 실행할 수 있다.
setTimeout(func|code, [delay], [arg1], [arg2], ...)
func|code
실행하고자 하는 코드 (함수 또는 문자열 형태)
대개는 이 자리에 함수가 들어갑니다.
하위 호환성을 위해 문자열도 받을 수 있게 해놓았지만 추천하진 않습니다.
delay
실행 전 대기 시간
단위는 밀리초(millisecond, 1000밀리초 = 1초)이며 기본값은 0
arg1, arg2…
함수에 전달할 인수들
예제 1
function sayHi() { alert('안녕하세요.'); } setTimeout(sayHi, 1000); //안녕하세요.
function sayHi(who, phrase) { alert( who + ' 님, ' + phrase ); } setTimeout(sayHi, 1000, "홍길동", "안녕하세요."); // 홍길동 님, 안녕하세요.
예제 2
const hello = () => { console.log('hello~') } const timeout = setTimeout(hello, 1000) //hello 함수를 1초 뒤에 실행한다. const h1El = document.querySelector('h1') h1El.addEventListener('click', () => { //h1태그로 작성된 내용을 클릭하면 (=클릭 이벤트가 발생하면) console.log('Clear!') //Clear! 를 콘솔에 출력하고 clearTimeout(timeout) //TImeout을 취소한다. })
setInterval
은 지정한 시간 간격마다 함수를 실행한다.
예제 1
const hello = () => { console.log('hello~') } const timeout = setInterval(hello, 1000) //hello 함수를 1초 간격으로 실행 const h1El = document.querySelector('h1') h1El.addEventListener('click', () => { //h1태그로 작성된 내용을 클릭하면 (=클릭 이벤트가 발생하면) console.log('Clear!') //Clear! 를 콘솔에 출력하고 clearInterval(timeout) //Interval을 취소한다. })
(참조) 유튜브 코딩알려주는누나 - 자바스크립트의 this
⭐ this도 아직 내가 감당할 깜냥은 아니다...
이 놈도 다음에 객체 학습한 후에 다시 봐주겠습니다..!!!!!