09_Javascript: Scope

09_Javascript: Scope

Global Scope, Function Scope, Block Scope, Hoisting

·

2 min read

  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 안되므로 오히려 안정적