Honey-Programming

Hoisting(호이스팅) & Scope(스코프) 본문

JAVASCRIPT

Hoisting(호이스팅) & Scope(스코프)

Latte_is_horse 2020. 7. 20. 18:25

let, var, const  이들의 차이점을 이해하려면 Hoisting(호이스팅)과 Scope에 대한 개념이 필요하다

 

Hoisiting(호이스팅)

: 변수의 정의가 그 범위에 따라 선언(declaration)/초기화(initialization)/할당 분리되는 것을 의미한다.

쉽게 말하면, 변수가 함수내에서 정의되었을 경우 선언이 함수의 최상위로,

함수 바깥에서 정의되었을 경우엔 전역 컨텍스트의 최상위로 변경된다.

 

1번 코드
const hoisting = () => {
  console.log("First-Name:", name);
  var name = "Marcus";
  console.log("Last-Name:", name);
}

hoisting();
// First Name : undefined
// Last Name : Marcus
// First Name이 undefined인 이유는 지역변수 name이 호이스트 되었기 때문이다.
2번 코드
const hoisting = () => {
     var name; // name 변수는 호이스트 되었습니다. 할당은 이후에 발생하기 때문에, 이 시점에 name의 값은 undefined 입니다.
     console.log("First name : " + name); // First Name : undefined
     name = "Marcus"; // name에 값이 할당 되었습니다.
     console.log("Last Name : " + name); // Last Name : Ford
}

hoisting();
// First Name : undefined
// Last Name : Marcus
// First Name이 undefined인 이유는 지역변수 name이 호이스트 되었기 때문이다.

변수 name이 함수 내에서 정의되으므로 선언이 함수의 최상위로 변경됬다. 

 

위에서 var로 작성한 hoisting 함수를 let const로 바꿔보자

const hoisting = () => {
  console.log("Name:", name);
  let name = "Marcus";
}

hoisting();
// ReferenceError: name is not defined

let으로 했을 경우 name is not defined라는 에러가 발생한다.
이 이유를 설명하려면 우리는 Temporal Dead Zone(TDZ)라는 개념을 알아야한다.

TDZ는 어휘적 바인딩이 실행되기 전까지 액세스할 수 없는 현상이다

스코프에 진입할 때 변수가 만들어지고 TDZ(Temporal Dead Zone)가 생성되지만,

코드 실행이 변수가 실제 있는 위치에 도달할 때까지 액세스를 할 수 없기 때문에 오류가 났던 것이다.

 

그렇다면 오류가 안나게 하려면 제일 먼저 변수 name을 선언해주고 시작하면 된다.

const hoisting = () => {
  let name = "Marcus";
  console.log("Name:", name);
}

hoisting();
// Name: Marcus

 

 

Javascript Hoisting

Hoisting Javascript에 Hoisting을 알아보자 Hoisting은 어쩌면 우리가 무의식적으로 사용하고있을 수 있다. Hoisting에 특징을 알아보자 모든 변수 선언은 호이스트된다. 호이스트란, 변수의 정의가 그 범위

velog.io


Scope(스코프)

: 어떤 변수들에 접근할 수 있는지를 정의

스코프에 종류에는 2가지가 있다. 전역 스코프(Global Scope), 지역 스코프(Local Scope)

 

전역 스코프(Global Scope)

: 전역 스코프는 말 그대로 전역에 선언되어있어 어느곳에서도 해당 변수에 접근할 수 있다는 의미다.

함수 바깥이나  { } 바깥에서 선언되었다면, 전역 스코프에 해당

const globalVariable = 'variable'
const hello = 'Hello Marcus'
function marcusHello () {
  console.log(hello)
}
console.log(hello) // 'Hello Marcus!'
sayHello() // 'Hello Marcus!'

전역 스코프를 이용하여 변수를 선언할 수 있지만 두 개 이상의 변수의 이름이 충돌하는 경우가 생길 수도 있으므로 조심해서 사용

 

// 잘못된 예시
let thing = 'Marcus'
let thing = 'Marcus else' // 이미 같은 이름의 변수가 존재합니다.

var를 이용해서 변수를 선언했다면, 두 번째 var thing  변수가 첫번째 var thing 변수를 덮어씌게 된다.

// var는 되도록이면 사용하지 않도록 한다.
var thing = 'Marcus'
var thing = 'Marcus else' // 위에 thing = 'Marcus' -> 'Marcus else'
console.log(thing) // ‘Marcus else’

그렇기 때문에 되도록이면 var을 사용하지 않는다.

 

var global = '전역변수';

function isGlobal() {
  return `${global}은 글로벌하다`
}

isGlobal(); // output: 전역변수는 글로벌하다
let a = 50;

const myNum = function() {
  a = 100;
  console.log(a);
}

myNum(); // output: 100
console.log(a); // output: 100

 

지역 스코프(Local Scope)

: 해당 지역에서만 접근할 수 있어 지역을 벗어나게 되면 접근을 할 수 없다는 의미다.

블록 { } 안에 선언된 변수를 말한다. 지역 스코프는 함수 스코프(Function Scope)와 블록 스코프(Block Scope)로 나뉜다.

두 가지 모두 해당 블록안에 있을 때만 접근이 가능한 변수

 

* 함수 스코프(Function Scope)

: 변수 생성이 블록 ({ }) 안에 있다

function isLocal() {
  var local = '지역변수';
  return `${local}는 로컬하다`
}

isLocal(); // output: 지역변수는 로컬하다

 

바깥에서 변수 local를 부른다면 아래와 같은 참조에러가 뜬다.

function isLocal() {
  var local = '지역변수';
  return `${local}는 로컬하다`
}

console.log(local); // output: Uncaught ReferenceError: local is not defined

 

* 블록 스코프(Block Scope)

: const 혹은 let으로 변수를 선언한다.

{
  const hey = 'Hello';
  console.log(hey);
}
// output: Hello
console.log(key); // output: Uncaught ReferenceError: hey is not defined

 

 

 

(JavaScript) 스코프(Scope)란?

자바스크립트를 공부할 때 스코프(Scope)란 단어를 많이 접할 수 있는데요. 이 스코프란 무엇인지에 대해 알아보겠습니다.

medium.com

 

'JAVASCRIPT' 카테고리의 다른 글

map 메소드  (0) 2020.07.23
forEach 메소드  (0) 2020.07.22
slice, splice, split 메소드  (0) 2020.07.22
immutable vs mutable  (0) 2020.07.21
var, let, const 차이(비교)  (0) 2020.07.21
Comments