JavaScript: Variable Scope. Variable scope Js global variable in function

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 coincides with the name of a variable outside the function, then there can be various interesting situations related to the global and local scopes of the variable.

It is with this that we will understand this lesson.

Global variable

All variables that you create outside of the function are global. And it is imperative to create a variable using the var keyword, if this is not done, then the variable will be visible everywhere in the program, and moreover, with the strict mode enabled, this will cause an error. In order to enable strict mode, it is enough to 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 \u003d 6; // global variable function double () (return alert (a * a); // using a global variable) double ();

The example declares a global variable a, which is assigned the value 6. In the function, we can access this variable and even more, 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 \u003d 6; function double () (a \u003d 5; // change the value of the global variable in the function return alert (a * a);) double (a); // call the function document.write (a); // value of the global variable

As you can see from the example, if you change the value of a global variable in a function, it already 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 should be noted that the statements if / else, for, while, do ... while do not affect the scope of the variables.

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

Function double () (var a \u003d 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 is declared in the function, that is, locally. Then we call the function and try to access the local variable, 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 variable with the same name are created, what will happen then. Let's see an example.

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

As you can see here, in the function, it is as if another variable is created, 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, as this example shows.

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

Results.

A variable created outside of a function is global.

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

Variables serve as "containers" for storing information.

Do You Remember School Algebra?

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

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

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

JavaScript variables

Just like in algebra, JavaScript variables are used to store values \u200b\u200bor expressions.

A 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 start 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 during script execution. You can refer to 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 are declaring JavaScript variables using the keyword var:

After executing the suggestions above, the variable x will contain the value 5 and carname will contain the value Mercedes.

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

Comment: If you re-declare a variable, 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 will learn more about functions in later JavaScript lessons.

JavaScript Global Variables

Variables declared outside of a function become GLOBALand 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 \u200b\u200bto Undeclared JavaScript Variables

If you assign values \u200b\u200bto variables that have not yet been declared, the variables will be automatically declared as global variables.

These suggestions:

You will learn more about operators in the next JavaScript tutorial.

Global variables in javascript

What are global variables: variables are "visible" at any point in the execution of the program, everywhere they can be read and overwritten.
Usually global variables are defined at the very beginning of the program, outside of any blocks (())
in the case of Js, they are set after the script, or all other functions

hello \u003d "Hello"; // set a global variable and check it
document.writeln ("-\u003e 1" + hello + "every one
"); // -\u003e 1 Hello every one

If (true)
// if (false)
{
var hello \u003d "Hello Dolly and"; // this is also global
world \u003d "world"; // global
var cont \u003d ", we continue" // global
document.writeln ("-\u003e 1.2" + hello + world + cont + "
");
//1.
}
document.writeln ("-\u003e 2" + hello + world + cont + "
");
// -\u003e 2 Hello Dolly and world, we continue

If true, we get the answer

-\u003e 1 Hello every one
-\u003e 1.2 Hello Dolly and world, we continue
-\u003e 2 Hello Dolly and world, we continue

Execution aborts

Thus, it turns out that the use of var does not affect the global scope in any way. A variable mentioned in a script outside of procedures is considered global even if it is enclosed in brackets () of the if while for block and other scopes remains global even inside loops

Conclusions, briefly

* for variables used in the global scope, the presence of var is not important.
* Blocks after if while for do not create local scope (as it happens in other languages)

Local variables are variables set within the executable block (function) and do not affect other functions. and the external environment, i.e. global scope.

Boy \u003d "Jhone";
did \u003d "kills Kenny"; // so we have 2 global variables
function doit ()
{
// printing has already passed --1, and we change the data, change the data
var boy \u003d "Gary"; // create a locale
did \u003d "helps Anny"; // change the global
;
document.writeln ("- 2" + boy + "" + did + "
");
// - 2 Gary helps Anny
;
// now, inside the function, set local and global variables
var good \u003d "he was a good boy
"; // locale!
bad \u003d "he likes a bad girls
"; // global
}
;
document.writeln ("- 1" + boy + "" + did + "
");
// - 1 Jhone kills Kenny
doit ();
// - 2 Gary helps Anny
document.writeln ("- 3" + boy + "" + did + "
");
// - 3 Jhone helps Anny
;
if (! true)
// if (! false)
{
document.writeln ("- 4" + good);
// execution of this block will throw an error.
// we are currently out of local scope
// doit () function, so for us, given via var
// variable good just doesn't exist
}
document.writeln ("- 5" + bad);
// - 5 he likes a bad girls

Result:

1 Jhone kills Kenny
--2 Gary helps Anny
--3 Jhone helps Anny
--5 he likes a bad girls

Local variables in javascript

* var works inside a function by declaring a local variable. This is his main task.

* Javascrip is very different from si in that only (?) Inside a function are local variables possible.
* using var or not using it in the global scope depends only on your personal experience. But for me it's better not to be lazy. in pearl it is called use strict

\u003e\u003e\u003e var is not important for variables used in the global scope

Important. First, “vars” cannot be deleted (using delete). Secondly, their instantiation occurs on the “zero line” (before starting work “line by line”), where they are immediately assigned the undefined value, and only then the variable can receive (or may not receive) a new value:

Var glb_1 \u003d 1;
if (false) (var glb_2 \u003d 2; glb_3 \u003d 3;)

Alert (glb_1) // instantiated and got the value 1
alert (glb_2) // fleshed out and got the value 'undefined'
alert (glb_3) // not a variable at all (no var), an error when calling

Last update: 05.04.2018

All JavaScript variables have a specific scope within which they can act.

Global Variables

All variables that are declared outside of functions are global:

Here the variables x and d are global. They are accessible from anywhere in the program.

But the variable z is not global, since it is defined inside the function.

Local variables

A variable defined inside a function is local:

Function displaySquare () (var z \u003d 10; console.log (z); let b \u003d 8; console.log (b);)

The variables z and b are local, they only exist within the function. They cannot be used outside of a function:

Function displaySquare () (var z \u003d 10; console.log (z);) console.log (z); // error because z is undefined

When the function finishes its work, then all the variables defined in the function are destroyed.

Hiding Variables

What if we have two variables, one global and the other local, that have the same name:

Var z \u003d 89; function displaySquare () (var z \u003d 10; console.log (z); // 10) displaySquare (); // ten

In this case, the function will use the z variable that is defined directly in the function. That is, the local variable will hide the global one.

var or let

When using the let statement, each block of code defines a new scope in which the variable exists. For example, we can define a variable at the block level and at the function level at the same time:

Let z \u003d 10; function displayZ () (let z \u003d 20; (let z \u003d 30; console.log ("Block:", z);) console.log ("Function:", z);) displayZ (); console.log ("Global:", z);

Here, inside the displayZ function, a block of code is defined in which the variable z is defined. It hides the global variable and the function-level z variable. In a real program, a block could represent a nested function, a for loop, or if statements. But in any case, such a block defines a new scope, outside of which the variable does not exist.

And in this case, we get the following console output:

Block: 30 Function: 20 Global: 10

With the var statement, we cannot simultaneously define a variable with the same name both in a function and in a block of code in this function:

Function displaySquare () (var z \u003d 20; (var z \u003d 30; // Error! Variable z is already defined console.log ("Block:", z);) console.log ("Function:", z);)

That is, using var, we can define a variable with the same name, either at the function level or at the code block level.

Constants

Everything about the let statement also applies to the const statement, which allows you to define constants. Code blocks define the scope of constants, and constants defined in nested code blocks hide external constants of the same name:

Const z \u003d 10; function displayZ () (const z \u003d 20; (const z \u003d 30; console.log ("Block:", z); // 30) console.log ("Function:", z); // 20) displayZ ( ); console.log ("Global:", z); // ten

Undeclared variables

If we do not use this keyword when defining a variable in a function, then such a variable will be global. For example:

Function bar () (foo \u003d "25";) bar (); console.log (foo); // 25

Although foo is not defined anywhere outside of the bar function, it is still available outside the function in the external context.

It would be different if we not only assigned the value to the variable, but also defined it:

Function bar () (var foo \u003d "25";) bar (); console.log (foo); // mistake

strict mode

Defining global variables in functions can lead to potential errors. To avoid them, strict mode or strict mode is used:

"use strict"; function bar () (foo \u003d "25";) bar (); console.log (foo);

In this case, we will receive a SyntaxError: Unexpected identifier error, which indicates that the variable foo is not defined.

There are two ways to set strict mode:

    add the expression "use strict" to the beginning of the JavaScript code, then strict mode will be applied to the entire code

    add the expression "use strict" to the beginning of the function body, then strict mode will be applied only for this function

This four-part tutorial explores how to write good JavaScript code that is easy to maintain and develop, even if you have to come back to a project after a long time.

Write code with the expectation that it will need to be maintained

Software bugs come with a cost. Their cost is expressed in terms of the time it takes to fix them. Errors in publicly launched projects are especially costly. It is very good if you can fix errors immediately, when the structure of the code is still fresh in memory, and you can quickly find the problem area. But if you switched to other tasks and have already partially forgotten the features of a certain code, then returning to the project will require:

  • Time to study and understand the problem.
  • Time to understand the code that is the source of the problem.

Another problem that affects large projects or companies is that the person fixing the bugs is not the person who creates them (and often is not the one who finds them in the project). Therefore, reducing the time to understand the code becomes a critical issue, regardless of whether you wrote the code yourself some time ago, or it was written by another developer on your team. The answer to the question will significantly affect both the financial result of the project and the level of satisfaction of the developers, because sometimes it is better to do everything in a new way than to spend hours and days supporting old incomprehensible code.

Another fact related to software development is that it usually takes longer reading code, not creating it. In the initial setting of the problem, the developer focuses and immerses himself in the question, and then sits down and can create significant code in one evening. Then the code probably works, but, by the natural nature of software products, situations arise that require repeated revisions of the code. For example:

  • Errors are identified.
  • New features are added to the project.
  • The application must be launched in a new environment (for example, a new browser has appeared).
  • The purpose of the code is changing.
  • The code needs to be completely rewritten or ported to another architecture or programming language.

As a result, it will take several man-hours to write the code, and several man-days to read it. Therefore, creating easily maintainable code is critical to the success of your application.

Easy to maintain code has the following features:

  • It's easy to read.
  • It is well structured and the parts fit together.
  • It is predictable.
  • It looks like it was written by one person.
  • Documented.

Minimizing the use of global variables

JavaScript uses functions to manipulate context. Variables declared inside functions are local to them and are not available outside of functions. Global variables are declared outside of functions or simply used without declaration.

Every JavaScript environment has a global object that is used outside of functions. Every global variable you create becomes a property of the global object. For convenience, browsers have an additional property of the global object called window, which (usually) points to the global object itself. The following code shows an example of creating and accessing global variables in the browser environment:

Var myglobal \u003d "hello"; console.log (myglobal); // "hello" console.log (window.myglobal); // "hello" console.log (window ["myglobal"]); // "hello" console.log (this.myglobal); // "hello"

Problems with global variables

The problem with global variables is that they will be available throughout the JavaScript code of your application or page. They are in the global namespace, and there is always a chance for naming collisions when two different parts of the application define global variables with the same name but for different purposes.

Also, usually, a web page includes code written by other developers. For example:

  • Other JavaScript libraries.
  • Advertising partner scripts.
  • User tracking and analytics code.
  • Various widgets, buttons and plugins.

Let's say one of the third-party scripts defines a global variable called, for example, result. Then, in one of your functions, you define another global variable and call it result. As a result, the last declaration of the result variable will override the first, and the third-party script may stop working.

Therefore, to successfully combine different code on the same page, it is important to use as few global variables as possible. In this question, the use of the var directive when declaring variables plays an essential role.

Unfortunately, it is very easy to inadvertently create a global variable in JavaScript due to two features. First, you can use a variable without declaring it. Second, JavaScript has an implied global definition, which means that any un-declared variable becomes a property of the global object (and will be available as a properly declared global variable). For example:

Function sum (x, y) (// bad: implied global result \u003d x + y; return result;)

In this code, the result variable is used without a declaration. The code works fine, but after calling the function, you will get another result variable in the global namespace, which can lead to problems.

The rule of minimization is to define variables using the var directive. The following is an improved version of the sum () function:

Function sum (x, y) (var result \u003d x + y; return result;)

Another bad option for creating implied globals is chaining a value within a var declaration. In the following example, the variable a will be local, and the variable b will become global, which is probably not in the list of targets of the code creator:

// bad, don't use function foo () (var a \u003d b \u003d 0; // ...)

If you are surprised by what is happening, then this is a right-to-left calculation. The expression b \u003d 0 is executed first, and therefore the variable b will not be declared. The return value of the expression will be 0, and it is assigned to the new local variable a, which is declared by the var directive. This definition of variables is equivalent to the following notation:

Var a \u003d (b \u003d 0);

If you've already declared variables, then the chained view will work fine and won't create unwanted globals:

Function foo () (var a, b; a \u003d b \u003d 0; // both variables are local)

Another reason to avoid using global variables is portability. If you plan to run your code in a different environment, then global variables can overwrite objects that are not present in the original environment (so it might seem that the name used is safe).

Side effect of forgotten var declaration

There is a slight difference between explicitly defined and implied globals. It consists in the ability to delete a variable using the delete operator:

  • A global variable declared with a var declaration (created outside of functions in the program) cannot be deleted.
  • An implicit global variable created without a declaration (regardless of where it was created) can be deleted.

Technically, an implied global variable is a property of the global object, not a variable. Properties can be deleted using the delete operator, but variables cannot:

// define three global variables var global_var \u003d 1; global_novar \u003d 2; // bad (function () (global_fromfunc \u003d 3; // bad) ()); // Trying to delete delete global_var; // false delete global_novar; // true delete global_fromfunc; // true // Check for deletion typeof global_var; // "number" typeof global_novar; // "undefined" typeof global_fromfunc; // "undefined"

Accessing the global object

In browsers, the global object is available anywhere in the code through the window property (unless you do something special or unexpected, such as declaring a local variable named window). But in other environments, this convenient property may be available in another way (or even not available to the programmer at all). If you need access to the global object without using the window identifier, then you can use the following method at any level of the nested function namespace:

Var global \u003d (function () (return this;) ());

Thus, it is always possible to access the global object, since inside a function that is called as a function (and not as a constructor with a new declaration) this always points to the global object.

Single var declaration template

Using a single var declaration at the top of your function is a very useful practice. This method has the following advantages:

  • Provides a single place to declare all local variables of a function.
  • Boolean errors are prevented when a variable is used before it is declared.
  • Helps you remember to declare local variables and therefore reduces the number of global variables.

A template with a single var declaration looks like this:

Function func () (var a \u003d 1, b \u003d 2, sum \u003d a + b, myobject \u003d (), i, j; // Function code ...)

You are using one var declaration to declare multiple variables separated by commas. An excellent addition would be to initialize variables with the original data when they are declared. This prevents logical errors (all uninitialized variables are undefined by default) and improves the readability of the code. When you look at the code later, how can you determine the purpose of a variable by its initial value (for example, you will immediately see that it is an object or an integer).

You can also perform an operation when declaring a variable, such as sum \u003d a + b from the previous example code. DOM manipulation is another working example. You can assign references to DOM elements to local variables when you declare:

Function updateElement () (var el \u003d document.getElementById ("result"), style \u003d el.style; // do operations with el and style ...)

Lifting: the problem with scattered var declarations

JavaScript allows multiple var declarations anywhere in a function, and they work the same regardless of where they are placed. This feature is known as "lifting". This behavior can lead to logical errors when you use a variable and then declare it for further function code. For JavaScript, since a variable is in the same namespace (in the same function), it is assumed to be declared, even if used before the var directive. for example

// bad myname \u003d "global"; // global variable function func () (alert (myname); // "undefined" var myname \u003d "local"; alert (myname); // "local") func ();

In this example, the first call to alert () is expected to produce the message "global", and the second to "local." This is a reasonable expectation, since on the first call the local variable myname is not declared and the function must use the global variable myname. But in reality, everything works differently. The first call to alert () will return “undefined” because myname is treated as a declared local variable in the function (although it will be declared later). All variable declarations are hoisted up the function. Therefore, to avoid this type of error, you need to declare all the variables at the top of the function.

The previous example will act as if it were implemented like this:

Myname \u003d "global"; // global variable function func () (var myname; // same as -\u003e var myname \u003d undefined; alert (myname); // "undefined" myname \u003d "local"; alert (myname); // " local ") func ();

It's worth mentioning that the actual implementation of the code is more complex. There are two stages of code processing. The first stage creates variables, function declarations, and formal parameters, and defines the context. The second stage executes code, evaluates functions, and creates unqualified identifiers (undeclared variables). But for practical use, the concept of hoisting can be used, which describes the behavior of the code well.