Skip to main content

Command Palette

Search for a command to run...

09_Javascript: Scope

Global Scope, Function Scope, Block Scope, Hoisting

Updated
•2 min read•View as Markdown
09_Javascript: Scope
  1. Global Scope(전역)

  2. Function Scope(함수)

  3. Block Scope(블록) - if, for, switch


Ex01. Global Scope & Function Scope 01

// global scope
const value = 'hello!';
function myFunction() {
    console.log('myFunction: ');
    console.log(value);
}
function otherFunction() {
    console.log('otherFunction: ');
    const value = 'bye!';
    console.log(value);
}
myFunction(); // myFunction: hello!
otherFunction(); // otherFunction: bye!

console.log('global scope: ');
console.log(value); // hello!

Ex02. Global Scope & Function Scope 02

const value = 'hello!';
function myFunction() {
    const value = 'bye!';
    const anotherValue = 'world';
    function functionInside() {
        console.log('functionInside: ');
        console.log(value);
        console.log(anotherValue);
    }
    functionInside();
}

myFunction() //functionInside: bye! world
console.log('global scope: ');
console.log(value); //hello!
console.log(anotherValue); // ERROR! (ReferenceError)

Ex03. block scope

const value = 'hello!';
function myFunction() {
    const value = 'bye!';
    if (true) {
        const value = 'world';
        console.log('block scope: ');
        console.log(value);
    }
    console.log('function scope: ');
    console.log(value);
}

myFunction(); // block scope: world function scope: bye!
console.log('global scope: ');
console.log(value); //hello!

Ex04. var

var value = 'hello!';
function myFunction() {
    var value = 'bye!';
    if (true) {
        var value = 'world'; // if문 밖에도 영향
        console.log('block scope: ');
        console.log(value);
    }
    console.log('function scope: ');
    console.log(value); // 여기에 영향
}

myFunction(); // block scope: world function scope: world
console.log('global scope: ');
console.log(value); //hello!

Ex05. Hoisting

//hoisting으로 에러 안남 
myFunction();

function myFunction() {
    console.log('hello world');
}
console.log(number); // undefined -> var number만 먼저 인식하고, 할당은 나중에 함 
var number = 2;
  • var과 hoisting 이용하지 않기

  • const, let은 hoisting 안되므로 오히려 안정적

More from this blog

Next.js의 Routing

라우팅은 네트워크 용어로서 네트워크상의 주소로 이동하여 해당 주소에 연결되어있는 데이터를 사용하는 일련의 과정을 의미 라우터는 라우팅을 수행할 수 있는 장치 pages (혹은 src/pages) 폴더 아래에 파일을 추가하는 방식으로 각 컴포넌트에 URL을 부여 install - 리액트에서는 라우터를 제공하지 않기 때문에 react-router-dom이라는 패키지를 설치 router 객체 확인 가능 동적 라우팅(Dynamic Rout...

Aug 30, 20232 min read
Next.js의 Routing

What I've learned on my tech journey

26 posts

Frontend Developer👩‍💻