JavaScript Function Scope

JavaScript function scope determines where variables declared inside a function can be accessed. When you declare a variable inside a function, that variable is generally available only within the function and its nested scopes.

Understanding function scope helps you organize your code, prevent naming conflicts, and avoid errors when accessing variables from different parts of a program.

In this tutorial, you will learn what function scope is, how it works with var, let, and const, how nested functions access variables, and how function scope differs from block scope and global scope.

What Is Function Scope in JavaScript?

Function scope refers to the accessibility of variables within the function where they are declared.

In JavaScript, variables declared using var, let, and const inside a function are local to that function. However, var is function-scoped, while let and const are block-scoped within the function.

Example of Function Scope

function greet() {
    let message = "Hello, World!";

    console.log(message);
}

greet();

Output:

Hello, World!

In this example, message is declared inside the greet() function. It can be accessed inside the function, so the message is displayed successfully.

However, trying to access message outside the function causes a ReferenceError.

function greet() {
    let message = "Hello, World!";
}

greet();

console.log(message);

Output:

ReferenceError: message is not defined

The variable message belongs to the function’s scope. The outer code cannot access it directly.

If you are new to variables, read our JavaScript Variables tutorial.

How Function Scope Works

When JavaScript executes a function, it creates an execution context in which the function’s local variables and parameters are available.

Variables declared inside the function can be accessed by statements within that function. Nested functions can also access variables from their enclosing functions.

Example of Local Variables Inside a Function

function calculateTotal() {
    let price = 200;
    let quantity = 3;
    let total = price * quantity;

    console.log(total);
}

calculateTotal();

Output:

600

Here, price, quantity, and total are declared inside calculateTotal(). They can be used within the function, but they cannot be accessed directly outside it.

Returning Values from a Function

If you need to use a function’s result outside the function, you can return the value.

function calculateTotal() {
    let price = 200;
    let quantity = 3;

    return price * quantity;
}

let result = calculateTotal();

console.log(result);

Output:

600

The variables price and quantity remain local to the function. Only the calculated result is returned and stored in the outer variable result.

Learn more about returning values in our JavaScript Function Fundamentals tutorial.

Function Scope with var

The var keyword declares variables that are scoped to the nearest enclosing function. If a var variable is declared inside a function, it cannot be accessed directly outside that function.

Example of var Function Scope

function showNumber() {
    var number = 10;

    console.log(number);
}

showNumber();

Output:

10

The variable number is accessible inside showNumber() because it is declared within that function.

Trying to access it outside the function results in an error.

function showNumber() {
    var number = 10;
}

showNumber();

console.log(number);

Output:

ReferenceError: number is not defined

Although var is function-scoped, it is not block-scoped.

var Inside an if Block

function checkNumber() {
    if (true) {
        var number = 50;
    }

    console.log(number);
}

checkNumber();

Output:

50

The variable number is accessible outside the if block because var is scoped to the function, not the block.

This behavior differs from let and const.

Function Scope with let and const

The let and const keywords are block-scoped. Their variables are accessible within the block in which they are declared and any nested scopes.

When declared directly inside a function body, they are limited to that function body. When declared inside an inner block, they are limited to that smaller block.

Example of let Inside a Function

function showMessage() {
    let message = "Welcome to JavaScript!";

    console.log(message);
}

showMessage();

Output:

Welcome to JavaScript!

The variable message can be accessed within the function.

Example of let Inside a Block

function checkAge() {
    if (true) {
        let age = 22;
        console.log(age);
    }
}

checkAge();

Output:

22

The variable age is declared inside the if block. It can be accessed within that block but not outside it, even though both locations are inside the same function.

Example of const Inside a Function

function displayWebsite() {
    const website = "Web4Learners";

    console.log(website);
}

displayWebsite();

Output:

Web4Learners

The website variable is available inside the function. Because it is declared using const, its binding cannot be reassigned.

For modern JavaScript, prefer const when a binding does not need reassignment and let when it does.

Nested Functions and Function Scope

A nested function is a function declared inside another function. In JavaScript, an inner function can access variables from its enclosing function.

This is possible because JavaScript uses lexical scoping, meaning variable accessibility depends on where functions and blocks are defined in the code.

Example of a Nested Function

function outerFunction() {
    let message = "Hello from the outer function";

    function innerFunction() {
        console.log(message);
    }

    innerFunction();
}

outerFunction();

Output:

Hello from the outer function

In this example, message is declared inside outerFunction(). The nested innerFunction() can access it because it is defined inside the outer function’s scope.

Accessing Variables from Multiple Levels

Nested functions can access variables from their own scope and enclosing scopes.

function outerFunction() {
    let firstName = "Shaik";

    function middleFunction() {
        let lastName = "Karimulla";

        function innerFunction() {
            console.log(firstName + " " + lastName);
        }

        innerFunction();
    }

    middleFunction();
}

outerFunction();

Output:

Shaik Karimulla

The innermost function can access both firstName and lastName. The JavaScript engine looks through the surrounding lexical scopes to find the variables.

However, the outer function cannot directly access variables declared only inside the inner function.

Function Scope and Global Variables

A global variable is declared in a broader scope and can be accessed by functions within that scope, provided it is not shadowed by another declaration.

Example of a Global Variable Inside a Function

let website = "Web4Learners";

function displayWebsite() {
    console.log(website);
}

displayWebsite();

console.log(website);

Output:

Web4Learners
Web4Learners

The website variable is declared outside the function, so both the function and the outer code can access it.

Local Variables and Global Variables with the Same Name

A local variable can have the same name as a global variable. In that case, the local variable shadows the outer variable within its scope.

let message = "Global message";

function showMessage() {
    let message = "Local message";

    console.log(message);
}

showMessage();

console.log(message);

Output:

Local message
Global message

Inside showMessage(), JavaScript uses the local message variable. Outside the function, the outer message variable remains unchanged.

Read our JavaScript Local and Global Variables tutorial for more examples.

Function Scope vs Block Scope

Function scope and block scope determine where variables can be accessed, but they are not the same.

Function scope applies to variables declared using var inside a function. Block scope applies to variables declared using let and const inside a block.

FeatureFunction ScopeBlock Scope
Common declarationvar inside a functionlet and const inside a block
Scope boundaryEnclosing functionEnclosing block {}
Access outside an inner blockA var variable may remain accessible within its functionA let or const variable is not accessible outside its block
Access outside the functionNot directly accessible if declared locallyNot directly accessible if declared in a local block inside the function

Comparing Function Scope and Block Scope

function compareScope() {
    if (true) {
        var first = "Function scoped";
        let second = "Block scoped";
    }

    console.log(first);
    console.log(second);
}

compareScope();

Output:

Function scoped
ReferenceError: second is not defined

The variable first is accessible because var uses function scope. The variable second is not accessible because let uses block scope and was declared inside the if block.

Because the error occurs during execution, the second variable cannot be logged successfully.

Common Mistakes When Using Function Scope

Understanding common mistakes can help you avoid scope-related errors.

Accessing a Local Variable Outside a Function

function calculate() {
    let total = 100;
}

calculate();

console.log(total);

This causes a ReferenceError because total is local to the function.

To use the result outside the function, return it and store the returned value in another variable.

Assuming var Is Block-Scoped

function test() {
    if (true) {
        var number = 10;
    }

    console.log(number);
}

test();

Output:

10

The variable remains accessible within the function because var is function-scoped.

Declaring Variables with the Same Name

Variables declared in nested scopes can shadow variables from outer scopes. This is valid JavaScript, but it can make code harder to understand if used carelessly.

Choose clear variable names and avoid unnecessary shadowing when it makes the code confusing.

Using Global Variables Instead of Returning Values

Global variables can make data accessible to many parts of a program, but they also make it easier for unrelated code to change shared values.

When a function calculates a result, consider returning that result instead of storing it in a global variable.

Frequently Asked Questions

What is function scope in JavaScript?

Function scope determines where a variable declared inside a function can be accessed. A locally declared variable is generally accessible within that function and its nested scopes.

Which JavaScript keyword is function-scoped?

The var keyword is function-scoped. Variables declared using let and const are block-scoped.

Can a function access variables declared outside it?

Yes. A function can access variables from its enclosing lexical scopes unless a local declaration shadows them.

Can an outer function access variables inside an inner function?

No, not directly. Variables declared only inside an inner function are not accessible from the outer function. However, the inner function can access variables declared in its enclosing function.

What is the difference between function scope and block scope?

Function scope limits a variable to its enclosing function, as with var. Block scope limits a variable to the block in which it is declared, as with let and const.

How can I use a local variable’s value outside a function?

Return the value from the function and assign the returned result to a variable in the calling scope.

Why is function scope important?

Function scope helps prevent naming conflicts, limits unintended access to variables, improves code organization, and makes programs easier to understand and maintain.

1 thought on “JavaScript Function Scope”

Comments are closed.