user11657234
user11657234

Reputation:

What would be consider as my local scope in this function?

just wondering what would be considered as my local scope in this function? Just a tad confused.

function hello(name, age) {
    var message = name + ", who is " + age + " years old, says hi!";

    return function sayHello() {
        console.log(message);
    };
}

var sayHelloToJohn = hello("John", 33);

sayHelloToJohn();

Upvotes: 1

Views: 39

Answers (2)

Domino
Domino

Reputation: 6768

Are you asking for the definition of the English word local? It just means "in the area". It's a relative term. The local scope is the scope of what you're currently talking about. When we speak of a variable local to a function, we mean that the variable isn't accessible outside said function.

When you declare a variable with var, it exists within the nearest enclosing function. When you declare a variable with let, it exists within the nearest enclosing braces { ... }.

In the example you've provided, 3 scopes were created:

  • The global scope which contains hello, sayHelloToJohn
  • hello's scope, which contains name, age, message and sayHello
  • The scope of the sayHello function.

Upvotes: 1

Tân
Tân

Reputation: 1

If I understand you mean correctly, in your case, message and sayHello are local variable/function. That means they cannot be assigned from the outside hello function.

But notice that, if you remove var keyword from

var message = name + ", who is " + age + " years old, says hi!";

it can be assigned from the outside of hello function. Same to sayHello function:

function hello(name, age) {
    message = name + ", who is " + age + " years old, says hi!";

    sayHello = function () {
        console.log(message);
    };

    return sayHello;
}

var sayHelloToJohn = hello("John", 33);

sayHelloToJohn();
console.log(message);
sayHello();

Upvotes: 1

Related Questions