JavaScript has three scopes: global, function, and block scope. Variable scope- this is a plot source code program in which variables and functions are visible and can be used. The global scope is also called top-level code.

Global Variables

A variable declared outside a function or block is called global. The global variable is available anywhere in the source code:

Var num = 5; function foo() ( console.log(num); ) foo(); // 5 console.log(num); // 5 ( console.log(num); // 5 )

Local variables

A variable declared inside a function is called local. A local variable is accessible anywhere within the body of the function in which it was declared. The local variable is created anew each time the function is called and destroyed when exiting it (when the function completes):

Function foo() ( var num = 5; console.log(num); ) foo(); // 5 console.log(typeof num); // undefined

A local variable takes precedence over a global variable of the same name, meaning that inside a function the local variable will be used rather than the global one:

Var x = "global"; // Global variable function checkscope() ( var x = "local"; // Local variable with the same name as the global one document.write(x); // Use a local variable, not a global one) checkscope(); // => "local" Try »

Block Variables

A variable declared inside a block with keyword let is called block . A block variable is accessible anywhere within the block in which it was declared:

Let num = 0; ( let num = 5; console.log(num); // 5 ( let num = 10; console.log(num); // 10 ) console.log(num); // 5 ) console.log(num) ; // 0

Re-announcement

If you use the var keyword to re-declar a variable with the same name (in the same scope), then nothing will happen:

Var a = 10; var a; console.log(a); // 10

If the re-declaration is accompanied by an initialization, then such a statement acts like a normal assignment of a new value:

Var a = 10; var a = 5; // Same as a = 5; console.log(a); // 5

If you use the let keyword to re-declar a variable with the same name (in the same scope), an error will be thrown:

Var a = 10; let a; // Error.

Scope chain

Consider the following example:

Var num = 5; function foo() ( var num2 = 10; function bar() ( var num3 = 15; ) )

This code has three scopes: global, foo() function scope, and bar() function scope. The global scope defines the variable num and the function foo() . The scope of the foo() function defines the variable num2 and the function bar() , and the variable num from the global scope is also available in it. The scope of the bar() function contains one variable, num3, which is only accessible within the bar() function. The bar() function's scope also has access to variables from the other two scopes because they are its parents. The scope chain for this example is shown in the figure below:

In the figure, different visibility areas are shown by rectangles of different colors. The inner scope in a chain of scopes has access to everything from the outer scopes, but the outer scopes have access to nothing from the inner scopes.

The scope chain is ordered. The interpreter looks outward, not inward, for identifiers in the scope chain. This means that the name search starts from the scope where the identifier was accessed. If the ID name is found, the search stops. If a name cannot be found in the current scope, a search is performed in the next (outer) scope, etc. Thus, the identifier from the scope in which it was found will be used. If the identifier is not found in any of the scopes, JavaScript will generate an error:

Var str = "global"; var num = 5; function foo() ( var str = "local"; // Using local variable str num = 10; // Using global variable num // alert(x); // Error. Variable x is not in any scope ) foo( ); alert(str); // "global" alert(num); // 10

If you assign a value to an undeclared variable in the body of a function, then at the time the function is called, if there is no variable with the same name in the global scope, a new global variable will be created:

Function foo() ( num = 2; ) foo(); // Created a new global variable num alert(num); // 2

Rise of advertisements

In JavaScript, declared variables are accessible anywhere relative to their scope, meaning that variables are visible even before they are declared in code. This feature of JavaScript is informally called hoisting: the program code behaves as if variable declarations were implicitly hoisted (without initialization) to the very top of their scope.

Consider the following code snippet:

Var str = "global"; function foo() ( alert(str); // undefined var str = "local"; alert(str); // "local" ) foo();

Looking at the code, you would think that the first alert should print the string "global" because the declaration of the local variable str has not yet been done. However, it actually outputs the value undefined . By raising declarations, the function above is equivalent to the implementation below, in which the variable declaration is raised to the beginning of the function:

Function foo() ( var str; // Declaration of a local variable at the beginning of the function alert(str); // Here it is available, but not initialized str = "local"; // Here it is initialized alert(str); // And here it has the expected value - "local")

The same applies to the global scope, a variable declared at the bottom is accessible at the top:

Alert(num); // undefined var num = 10; alert(num); // 10

IN JavaScript, there are two scopes: local and global. Depends on where the variable is declared, inside the function or outside the function.

If a variable is declared inside a function, then it is called local, if a variable is declared outside the function, then it is called global.

The modern concept of programming recommends that all variables in scripts (programs) be local, and the program itself consists only of functions, where each function performs only one task. For example, in another web programming language, PHP, they completely abandoned the use of global variables.

Global Variables in JavaScript

Global variables are declared outside functions and can be accessed (accessed) from any function or program line.

Var russia; russia = "Russia"; function getValueRussia() ( alert(russia); ) getValueRussia();

Here russia is a global variable, since it is declared outside the function. To prove that the variable is global, we accessed it from the inside custom getValueRussia() function, using the alert() function which displayed the value of the russia variable.

Local Variables in JavaScript

Local variables in JavaScript are declared inside functions. You can access local variables only within the function in which they are declared.

Function getValueRussia() ( var russia; russia = "Russia"; ) alert(russia);

IN in this example, nothing will happen (the window with the inscription “Russia” will not appear), and if we view the script through the console, it will tell us that the russia variable is undefined, this means that the alert() function (placed outside the function) does not see the russia variable, which was created inside the function.

Function getValueRussia() ( var russia; russia = "Russia"; alert(russia); ) getValueRussia();

By placing the alert() function inside the function and then calling the getValueRussia() function, we will see a window with the inscription “Russia”. These examples show us that local variables can only be accessed within the function in which they are created.

Hello! Today we will talk about the scope of variables (read what a variable is). The fact is that when you create a variable in a function and its name matches the name of a variable outside the function, then there can be various interesting situations related to the global and local scope of the variable.

This is exactly what we will deal with in this lesson.

Global variable

Global variables include all variables that you create outside of the function. And you definitely need to create a variable using the var keyword; if you don’t do this, the variable will be visible everywhere in the program and, moreover, if strict mode is enabled, it will cause an error. In order to enable strict mode, just write the line “use strict” at the beginning of your script. This will tell the JavaScript interpreter to strictly adhere to the JavaScript standard. Here is an example using a global variable

Var a =6; //global variable function double() ( return alert(a*a); //using a global variable ) double();

In the example, a global variable a is declared, which is assigned the value 6. In the function, we can access this variable and even change its value, and this value will change everywhere.

Let's look at an example where the value of a global variable is changed in a function, and then we access the global variable outside the function and see the value that was set to it in the function itself.

Var a =6; function double() ( a = 5; //change the value of the global variable in the function return alert(a*a); ) double(a); //call the function document.write(a); //global variable value

As you can see from the example, if you change the value of a global variable in a function, it remains with it everywhere, both in the function and outside it.

Local variable.

When you declare a variable in a function, it becomes local and can only be accessed from within the function. It is worth noting that if/else , for, while, do...while statements do not affect the scope of variables.

So it turns out that within a function you can access a global variable, but globally outside the function you cannot access a local variable created in the body of the function. Let's look at an example.

Function double() ( var a =6; return alert(a*a); ) double(); document.write(a); //trying to access a local variable

In the example, the variable is not declared globally, but rather declared in the function, that is, locally. Then we call the function and try to access the local variable, but as a result nothing happens, and in the console we see an error that the variable is not defined.

And the last option is when both a global variable and a local one with the same name are created, what will happen then. Let's see an example.

Var a =7; function double() ( var a =6; return alert(a*a); ) document.write(a);

As you can see, here a different variable is created in the function, despite the fact that its name coincides with the global one and it is the local variable that will be available in the function; it will not be able to overwrite the global one, which is what this example shows.

What conclusion can be drawn from all this? This means trying to use variables both inside and outside the function with different names. But you need to know about local and global scopes.

Results.

A variable created outside a function is global.

From a function you can access a global variable and change its value.

Variables serve as "containers" for storing information.

Do you remember High School Algebra?

Do you remember school algebra? x=5, y=6, z=x+y

Do you remember that a letter (eg x) could be used to store a value (eg 5), and that you could use the information above to calculate that the value of z is 11?

These letters are called variables, and variables can be used to store values ​​(x=5) or expressions (z=x+y).

JavaScript Variables

Just like in algebra, JavaScript variables are used to store values ​​or expressions.

The variable can have a short name, such as x, or a more descriptive name, such as carname.

Rules for JavaScript variable names:

  • Variable names are case sensitive (y and Y are two different variables)
  • Variable names must begin with a letter or underscore

Comment: Since JavaScript is case sensitive, variable names are also case sensitive.

Example

The value of a variable can change while the script is running. You can reference a variable by its name to display or change its value.

Declaring (Creating) JavaScript Variables

Creating variables in JavaScript is more commonly referred to as "declaring" variables.

You declare JavaScript variables using a keyword var:

After following the suggestions above, the variable x will contain the value 5 , And carname will contain the value Mercedes.

Comment: When you assign a text value to a variable, enclose it in quotation marks.

Comment: If you declare a variable again, it will not lose its value.

JavaScript Local Variables

A variable declared inside a JavaScript function becomes LOCAL and will only be available within this function. (the variable has local scope).

You can declare local variables with the same name in different functions because local variables are recognized in the function in which they are declared.

Local variables are destroyed when the function exits.

You'll learn more about functions in subsequent JavaScript lessons.

JavaScript Global Variables

Variables declared outside the function become GLOBAL, and all scripts and functions on the page can access them.

Global variables are destroyed when you close the page.

If you declare a variable without using "var", the variable always becomes GLOBAL.

Assigning Values ​​to Undeclared JavaScript Variables

If you assign values ​​to variables that have not yet been declared, the variables will be declared automatically as global variables.

These offers:

You'll learn more about operators in the next JavaScript lesson.