Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

JavaScript scope


May 06, 2021 JavaScript


Table of contents


JavaScript scope


A scope is a collection of accessible variables.

In JavaScript, you can define either global or local scopes.


JavaScript scope

In JavaScript, objects and functions are also variables.

In JavaScript, the scope is a collection of accessible variables, objects, and functions.

JavaScript function scope: The scope is modified within the function.


JavaScript local scope

Variables are declared within functions, and variables are local scopes.

Local variables: Can only be accessed inside a function.

The carName variable cannot be called here

function myFunction() {
var carName = "Volvo";

The carName variable can be called within the function

}

Try it out . . .

Because local variables only work within functions, different functions can use variables with the same name.

Local variables are created when the function starts executing, and they are automatically destroyed when the function is executed.


JavaScript global variable

Variables are defined outside the function, i.e. global.

Global variables have a global scope: All scripts and functions in a Web page are available.

var carName = " Volvo";

The carName variable can be called here

function myFunction() {

The carName variable can be called within the function

}

Try it out . . .

If a variable is not declared within a function (no var keyword is used), it is a global variable.

In the following example, carName is within the function, but is a global variable.

The carName variable can be called here

function myFunction() {
carName = "Volvo";

The carName variable can be called here

}

Try it out . . .


JavaScript variable lifecycle

The JavaScript variable lifecycle is initialized when it is declared.

Local variables are destroyed after the function is executed.

Global variables are destroyed when the page is closed.


Function arguments

Function parameters only work within the function and are local variables.


The global variable in HTML

In HTML, the global variable is the window object: all data variables belong to the window object.

Window.carName can be used here

function myFunction() {
carName = "Volvo";
}

Try it out . . .


Do you know?

JavaScript scope Your global variable, or function, can override the window object's variable or function.
Local variables, including window objects, can override global variables and functions.
JavaScript scope

In ES6, the let and const keywords are available.

let is declared in the same way as var, and by declaring a variable with let instead of var, you can limit the variable to the current block of code.

A constant is declared using const, whose value cannot be changed once it is set.