-
면접대비-3. Hoisting & TDZ 4.Parameter, argument차이항해99 2023. 3. 28. 12:43728x90
Hoisting 이란? TDZ란?
호이스팅은 코드를 실행하기 전에 선언된 변수 및 함수를 해당 범위의 맨 위로 이동하는 JavaScript의 메커니즘입니다.
일반적으로 선언되지 않은 변수를 접근할 수 없습니다. 마찬가지로, JavaScript에서도 선언되지 않은 변수를 접근할 수 없으며, 선언되지 않은 변수를 접근하면 ReferenceError가 발생합니다.
하지만, JavaScript는 다음 예제처럼 나중에 선언되는 변수를 미리 접근할 수 있습니다.console.log(value); // undefined var value = 'Hello' console.log(value); // Hello
변수를 최상단으로 끌어올리는 호이스팅은 장점도 존재하지만, 단점도 존재합니다.호이스팅에 의해 에러는 나지 않지만, 코드를 예측하기가 어렵다는 문제가 발생합니다. 편리하다는 이유로 가독성이 떨어지는 코드를 작성하지 않도록 주의해야합니다.
TDZ 는 변수가 선언되고 초기화되기까지의 그 사이에 위치하는 사각지대입니다.
let과 const는 선언단계와 초기화단계가 분리되어 실행됩니다.
그래서 선언단계와 초기화단계 사이에서는 실행컨텍스트를 변수에 등록했지만 메모리가 할당되지 않은 상태라 ‘reference error’가 발생한다. 이러한 사각지대가 TDZ(Temporal Dead Zone)이다.
선언 방식 중 var는 변수 선언 전에 선언단계와 초기화단계를 동시에 실행합니다.
선언과 초기화가 동시에 실행되기 때문에 TDZ가 존재하지 않고, 실행 컨텍스트 변수 객체를 등록 후 바로 그 메모리를 undefined합니다.
parameter와 argument의 차이에 대해 설명해주세요.
Parameter는 함수를 정의할 때 함수가 입력으로 받을 값을 선언하는 데 사용됩니다. 함수 내에서 이 값을 변수처럼 사용할 수 있습니다. 예를 들어, 아래의 함수
add
는 두 개의 parameterx
와y
를 입력으로 받습니다.function add(x, y) { return x + y; }
Argument는 함수를 호출할 때 함수에 전달하는 값을 나타냅니다. 이 값은 parameter와 일치해야 하며, 순서대로 대응되어야 합니다. 예를 들어,
add
함수를 호출할 때, 다음과 같이 두 개의 argument2
와3
을 전달할 수 있습니다.let sum = add(2, 3);
이때 함수는
2
와3
을 각각x
와y
parameter에 할당하여5
를 반환합니다. 반환된 값은sum
변수에 할당됩니다.따라서, parameter는 함수를 정의할 때 함수가 받을 입력값을 나타내며, argument는 함수를 호출할 때 전달되는 입력값을 나타냅니다.
728x90'항해99' 카테고리의 다른 글
면접대비 7. HTTP메세지구조 8. CSS position속성 (0) 2023.03.30 면접대비 5. 프레임워크 & 라이브러리 차이점 6. 캐시의 장단점과 프론트엔드에서 캐시를 사용할 수 있는 영역 (0) 2023.03.29 면접대비-1. 웹페이지가 브라우저에 렌더링되는 과정, 2. Restful API (0) 2023.03.27 [항해 11기 수료] 집에 플랜카드 달게된 사연 (0) 2023.03.23 37. 네이버 로그인 검수 썰 푼다 🚬 (0) 2023.03.14