Scope of function variables in JavaScript - Global and local variables. Scope of Javascript Variables Local and Global Variables

Home / Installing programs

All global variables and functions are actually properties and methods of a special object called a global object.

A global object is a regular object that is created automatically when the interpreter starts.

In JavaScript, the role of the global object is played by the Window object. This object has a window property that refers to the Window object itself. The Window object is both a global object and, in addition, contains a number of its own properties and methods for working with the browser window.

IN program code A top-level global object can also be referenced using the this keyword:

Alert(this === window); // true

Since global variables are properties of a global object, when working with a global variable, we are actually working with the properties of window:

Var num = 10; alert(window.num); // 10

Instead of declaring a variable using the var keyword, you can create a variable by explicitly specifying a new property for the Window object:

Window.num = 10; alert(num); // 10

Note that although global variables are actually properties of the Window object, it is not necessary to prefix the variable name:

Var num = 10; alert(num); // 10 alert(window.num); // 10. Same as alert(num);

If a global variable is declared using the var or let keyword, a non-configurable property is created, that is, a property that cannot be deleted using the delete operator:

Var num = 10; alert(delete num); // false, the variable is not deleted

If you assign a value to an undeclared variable, the JavaScript interpreter will automatically create a global variable. Variables created in this way become regular, custom properties of the global object, i.e. they can be deleted using the delete operator:

Num = 10; alert(delete num); // true, variable deleted

Methods Method Description
decodeURI()Returns a string containing the decoded URI.
decodeURIComponent()Returns a string containing the decoded portion of the URI.
encodeURI()Returns a string containing the URI encoded.
encodeURIComponent()Returns a string containing the encoded portion of the URI.
eval()The eval() function executes the code passed to it as a string. The code passed to a function is executed in the scope where the function was called.
isFinite()Converts the argument to a number (if necessary) and returns true if the argument contains any value other than NaN, positive infinity, and negative infinity. In these three cases it returns false.
isNaN()Determines whether the argument passed is NaN or not.
parseFloat()Parses a string argument and returns a floating point number or NaN.
parseInt()Parses a string argument and returns an integer or NaN.

Good day, JavaScript fans and my loyal subscribers. In today's post, I will tell you in detail about how global and local variables are created in JavaScript. I will definitely define important terms, talk about the features of declaring and initializing variables, describe what a scope is and how created elements function in it.

All this applies to the most basic, basic knowledge of the language. Without understanding all this, you will not be able to move forward and develop your js programming skills. In addition, the key concepts will be useful to you not only in this specialization, but also in the IT field in general. Well, let's get started!

What is a variable and how is it created?

A variable is an element of a programming language for which a memory area is allocated and in which certain values ​​are stored.

There can be a huge number of variables and they all must have a unique name.

There are two types of variables: global and local. Their difference lies only in the different scope of variables. Thus, global elements are visible throughout the entire code, and local ones are visible only in the small area where they were declared.

By the way, try from the very first day, from your first code, to call elements by logical and understandable names. Because later, when you work with heavy programs, after some period of time you will not remember what, for example, “aa1” or “perem3” means.

And absolutely nothing is clear from the title! This is not so bad, after all, it’s not so difficult to understand your own writings. What will you do if you are given the task of finishing tasks in another program that you have never even heard of before? With such names, analyzing the software implementation will kill a lot of useful time.

I've read the notation, now let's get back to declaring variables.

To create a variable, you must first write the keyword var, and then the name itself. This is what it looks like:

var text = “Hello, user!”

After this, text is accessed without “var”:

text = “New text.”

In this case the value will be overwritten.

For a better understanding, consider an example in which a single variable is created. We will turn to its meaning before and after rewriting.

1 2 3 4 var text = “Hello, user!”; alert(text); // will print “Hello, user!” text= “New text!”; alert(text); // will print “New text!”

var text = “Hello, user!”; alert(text); // will print “Hello, user!” text= “New text!”; alert(text); // will print “New text!”

Features of global objects

All created objects in js code are divided into global and local. Above I explained what the difference between them is. Now let's take a closer look at global objects.

They are all functions and variables that are declared in the main body of code, i.e. not inside any functions. All of them in js automatically become properties of a global object, which in browsers is clearly available under the word window. Let's look at an example.

var price = 145; // create a global variable

alert(window.price); // answer: 145

So far everything is simple, but be prepared for pitfalls. Sometimes, without knowing the specifics of saving and overwriting variable values, you can overwrite very important parameters. Such errors are quite difficult to track down and impossible to find using compilers. Therefore, carefully analyze the following material.

Pitfalls and scope

To better understand the problem, I will first show small program, where in the function I will create a local variable, and then outside its boundaries - a global one.

function test() ( p = 2; return p; ) alert(p); // undefined p = “important text”; alert(p); // will display “important text” test(); // call the function alert(p); // will print 2

Initially, in the test function, I initialized a local variable with the value 2, and then created a global text variable that stores some important data.

And here that “underwater block” pops up.

Firstly, due to the fact that I used the creation of elements according to the rules of the outdated JavaScript standard, all “p” variables were created only at the time of assignment (when using the var directive, variables are created immediately with the value undefined, and during initialization through “= » value is overwritten).

Secondly, in this case, to assign a value to implicitly created elements in js, an existing one is used or a new global variable is created. Therefore, in the above example, after calling the test function, the value of the global “p” was lost.

To avoid crashes, always use the var keyword. Then all objects will be declared explicitly and new ones will be created.

Here's the corrected example:

function test() ( var p = 2; alert (p); return p; ) alert(p); // undefined var p = "important text"; alert(p); // will display “important text” test(); // call the function, in this case it will display 2 alert(p); // will display "important text"

Now the code works correctly. As you noticed, the scope of the local “p” is within the test function, and the global one is within the rest of the code.

A few words about constants

Like all other programming languages, JavaScript has constants. For those who don't know what it is, I'll attach the definition.

A constant is a type of variable whose value remains unchanged.

According to the rules of syntax in js, their name is always written in lowercase (capital) letters. For example,

var MAIN_COLOR = “#fff”

Not in a scripting language technical means, which would make the constant truly a constant. In fact, they are ordinary variables that can be overwritten. However, according to the rules, developers use these elements with capital letters in the name as constants and do not change their meaning while writing code.

The main purpose of constants is to store complex strings, important numbers or other values ​​in which, when re-written, it is easy to make a typo or should never be changed, or to simplify the code. For example, constants can be used to store frequently repeated requests for

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

Note: 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 the var keyword:

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

Note: When you assign text value variable, enclose it in quotes.

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

JavaScript Local Variables

Variable declared inside JavaScript functions 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 a 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.

Last update: 04/05/2018

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

Global Variables

All variables that are declared outside functions are global:

var x = 5; let d = 8; function displaySquare())( var z = x * x; console.log(z); )

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 = 10; console.log(z); let b = 8; console.log(b); )

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

Function displaySquare())( var z = 10; console.log(z); ) console.log(z); //error because z is not defined

When a function finishes its work, all 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 = 89; function displaySquare())( var z = 10; console.log(z); // 10 ) displaySquare(); // 10

In this case, the function will use the variable z 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 simultaneously define a variable at the block level and at the function level:

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

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

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

Block: 30 Function: 20 Global: 10

With the var operator, we cannot define a variable with the same name both in a function and in a block of code within that function:

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

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

Constants

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

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

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 = "25"; ) bar(); console.log(foo); // 25

Even though the variable foo is not defined anywhere outside the bar function, it is nevertheless available outside the function in the external context.

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

Function bar())( var foo = "25"; ) bar(); console.log(foo); // error

strict mode

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

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

In this case, we will receive the error SyntaxError: Unexpected identifier, 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 all code

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

Variables

Declaring Variables

Before you can use a variable in JavaScript, it must be declared. Variables are declared using the var keyword as follows:

Var i; var sum;

By using the var keyword once, you can declare multiple variables:

Declaring variables can be combined with their initialization:

Var message = "hello"; var i = 0, j = 0, k = 0;

If no initial value is specified in the var statement, the variable is declared, but its initial value remains undefined until it is changed by the program.

If you have experience using programming languages ​​with static data types, such as C# or Java, you may notice that variable declarations in JavaScript lack a type declaration. Variables in JavaScript can store values ​​of any type. For example, in JavaScript you can assign a number to a variable, and then assign a string to the same variable:

Var i = 10; i = "hello";

With the var statement, you can declare the same variable more than once. If the repeated declaration contains an initializer, then it acts like a regular assignment statement.

If you try to read the value of an undeclared variable, JavaScript will generate an error. In the strict mode provided by the ECMAScript 5 standard, an error is also raised when attempting to assign a value to an undeclared variable. However, historically, and when not executed in strict mode, if you assign a value to a variable that is not declared with a var statement, JavaScript will create that variable as a property of the global object, and it will act much the same as a correctly declared variable. This means that global variables need not be declared. However, this is considered a bad habit and can be a source of errors, so always try to declare your variables using var.

Variable scope

The scope of a variable is the part of the program for which the variable is defined. A global variable has global scope - it is defined for the entire JavaScript program. At the same time, variables declared inside a function are defined only in its body. They are called local and have local scope. Function parameters are also considered local variables, defined only within the body of that function.

Within a function body, a local variable takes precedence over a global variable of the same name. If you declare a local variable or function parameter with the same name as a global variable, the global variable will actually be hidden:

Var result = "global"; function getResult() ( var result = "local"; return result; ); console.log(getResult()); // Display "local"

When declaring variables with global scope, the var statement can be omitted, but when declaring local variables, you should always use the var statement.

© 2024 ermake.ru -- About PC repair - Information portal