온라인강의정리하기/JS

선언적 함수와 익명 함수의 차이점 + arrow함수

루체도 2019. 10. 29. 16:18
Hello1();

//선언적 function
function Hello1() {
 console.log('hello1');
}

Hello1();

선언적 함수는 Hello1의 선언 위치와는 상관 없이 사용을 해도 오류가 나지 않는다.

hello2();
//익명 함수
var hello2 = function() {
 console.log('hello2');
}

//이러한 오류가 뜨게 된다.
TypeError: hello2 is not a function

var hello2 변수에 function이라는 객체를 생성을 했다. 그리고 이 함수를 실행하는 곳 위치를 보면

선언보다 위에서 실행을 하고 있다. 이렇게 할 경우에는 TypeError가 뜨게 됩니다.

끌어올림 현상(호이스팅)으로 hello2가 뭔지는 알지만 함수가 아니라고 판단을 하고 있다.

//또 다른 익명 함수 사용
hello3();

const hello3 = function() {
 console.log('hello3');
}

ReferenceError: hello3 is not defined

이렇게 해서 사용을 하면 hello3이라는 것이 아예 뭔지 모르는 ReferenceError가 뜨게 됩니다.`

 

//arrow 함수 익명 함수
const hello1 = () => {
 console.log('hello1');
};

//함수의 return
const hello4 = (name) =>{
 return `hello4 ${name}`;
}

const hello5 = name => `heelo5 ${name}' ;
함수 자체가 굉장히 간소해진다.
return만 필요한 경우에 이렇게 간략하게 만들어서 사용해도 될 것 같다.
물론 중괄호 안에 다른 로직이 필요하다면 중괄호를 추가해서 로직을 추가해야한다.