LoginSignup
0
1

More than 5 years have passed since last update.

[JavaScript] Hoisting(巻き上げ)演習

Posted at

Hoisting(巻き上げ)演習

コードの実行結果がどうなるのかを考える。

:green_book: 問題

[1]

var a = b = 1;

function outer() {

    console.log(a, b);

    var a = 2;

    console.log(a, b);

    function inner() {

        console.log(a, b);

        var a = 3;

        console.log(a, b);

        var b = 2;

        console.log(a, b);
    }

    inner();

    console.log(a, b);
}

console.log(a, b);

outer();

[2-1]

(function(){
    foo();

    var foo = function bar() {
        console.log(foo.name);
    };
}());

[2-2]

(function(){
    bar();

    var foo = function bar() {
        console.log(foo.name);
    };
}());

[3-1]

(function(){
    foo();

    var foo;

    foo();

    function foo() {
        console.log( 1 );
    }

    foo();

    foo = function() {
        console.log( 2 );
    };

    foo();
}());

[3-2]

(function(){
    foo();

    function foo() {
        console.log(1);
    }

    var foo = function() {
        console.log(2);
    };

    function foo() {
        console.log(3);
    }
}());

:blue_book: 答え

[1]

1 1
undefined 1
2 1
undefined undefined
3 undefined
3 2
2 1

[2-1]

Uncaught TypeError: foo is not a function(…)

[2-2]

Uncaught ReferenceError: bar is not defined(…)

[3-1]

1
1
1
2

[3-2]

3
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1