Computer literacy, assistance and repair

JavaScript Variables. JavaScript: Declaring Variables Data Actions and JavaScript Variable Values

Variables are a fundamental component of many programming languages; they are one of the most important concepts for new programmers. There are many different properties of variables in JavaScript, as well as several rules to follow when naming them. JavaScript has three keywords used to declare a variable—var, let, and const—and each of them affects how the variable will be interpreted in code.

This manual will introduce you to variables, teach you how to declare and name them, and also explain the difference between var, let and const. Additionally, you will learn what variable hoisting is and how scope affects the behavior of a variable.

What are variables

A variable is a named piece of memory used to store different values. A piece of information that can be referenced multiple times can be stored in a variable for later use or modification. IN JavaScript meaning The value contained within a variable can be any data type, including number, string, or object.

Prior to the ECMAScript 2015 (ES6) language specification, on which JavaScript is based this moment, there was only one way to declare a variable - using the var keyword. That’s why most old codes and manuals use only var to declare variables. Let's look at the differences between var, let and const.

The var keyword allows you to demonstrate the concept of the variable itself. In the example below, we declare a variable and assign a value to it.

// Assign the string value 8host to the username identifier
var username = "8host_blog";

This expression consists of several parts:

  • Declaring a variable using the var keyword;
  • Variable name (or identifier), username;
  • The assignment operator represented by the syntax =;
  • The assigned value is "8host_blog".

Now you can use the username variable in your code. JavaScript will remember that username represents the value 8host_blog.

// Check if variable is equal to value
if (username === "8host_blog") (
console.log(true);
}
true

As mentioned earlier, variables can be expressed by any JavaScript data type. In this example, the variables are expressed as string, number, object, boolean, and null.

// Assignment of various variables
var name = "Morty";
var spartans = 300;
var kingdoms = [ "mammals", "birds", "fish" ];
var poem = (roses: "red", violets: "blue" );
var success = true;
var nothing = null;

Using console.log you can view the value of any variable:

// Send spartans variable to the console
console.log(spartans);
300

Variables store data in memory that can later be used or changed. Variables can also be reassigned and given a new value. The simple example below demonstrates how a password can be stored and then updated in a variable.

// Assign value to password variable
var password = "hunter2";
// Reassign variable value with a new value
password = "hunter3";
console.log(password);
"hunter3"

In a real program, the password would most likely be stored securely in a database. However, this simple example illustrates a situation in which you might want to update the value of a variable. The value of the password variable was hunter2, but it was given a new value, hunter3, and JavaScript will now use the new value.

Naming Variables

In JavaScript, variable names are called identifiers. Several rules for naming identifiers can be found in the manual. Here they are in brief:

  • Variable names can only consist of letters, numbers (0-9), dollar sign ($), and underscore (_).
  • Variable names cannot contain whitespace characters.
  • The variable name must not begin with a number.
  • There are several reserved keywords that cannot be used as variable names.
  • Variable names are case sensitive.

JavaScript also has a convention for using camel case in the names of functions and variables declared with var or let. In this case, the first word is written in lowercase, and each subsequent word begins with a capital letter (words are written without spaces between them). Most variables that are not constants will follow this convention, with a few exceptions. Variable names that are constants (declared with the const keyword) are usually written in uppercase.

It seems that there are quite a lot of rules, but it seems so only at first glance. Working with JavaScript often, you will quickly remember them.

Difference between var, let and const

JavaScript uses three different keywords to declare variables, which add an extra layer of complexity. These keywords differ in variable scope, hoisting, and reassignment.

You may be wondering which of the three keywords you should use in your programs. It is common practice to use const as often as possible, and let in loops and for reassignment. Generally, var is used in legacy code.

JavaScript Scope

Scope in JavaScript refers to the current code context, which determines whether variables are accessible. The area can be local or global:

  • Global variables are those that are declared outside the block.
  • Local variables are those that are declared inside a block.

In the example below we will create a global variable.


var creature = "wolf";

You know that variables can be reassigned. In the local scope, you can create new variables with the same name as variables in the outer scope without changing or overriding the original value.

The example below creates a global variable species. Inside the function there is a local variable with the same name. When you send them to the console, you will see that the value of the variable differs depending on the scope, but the original value does not change.

// Initialize a global variable
var species = "human";
function transform() (
// Initialize a local, function-scoped variable
var species = "werewolf";
console.log(species);
}
// Log the global and local variables
console.log(species);
transform();
console.log(species);
human
werewolf
human

In this example, the local variable has function-level scope. Variables declared with the var keyword are always in that scope (that is, they recognize functions as having a separate scope). So a local variable is not accessible in the global scope.

However, the new let and const keywords are block-level scoped. This means that a new local area is created from any block, including function blocks, if statements, and for and while loops.

To illustrate the difference between function-level and block-level variables, create a new variable in an if block using let.

var fullMoon = true;
// Initialize a global variable
let species = "human";
if (fullMoon) (
// Initialize a block-scoped variable
let species = "werewolf";

}


It is not a full moon. Lupine is currently a human.

In this example, the variable species has one global value (human) and one local value (werewolf). However, if you use var, the result will be different.

// Use var to initialize a variable
var species = "human";
if (fullMoon) (
// Attempt to create a new variable in a block
var species = "werewolf";
console.log(`It is a full moon. Lupine is currently a $(species).`);
}
console.log(`It is not a full moon. Lupine is currently a $(species).`);
It is a full moon. Lupine is currently a werewolf.
It is not a full moon. Lupine is currently a werewolf.

As a result, both the global variable and the block-level variable produce the same value, werewolf. This is because instead of creating a new local variable, var reassigns the same variable in the same scope. var doesn't understand that if should be part of a different, new scope. It is generally recommended to declare variables at the block level because this reduces the risk of unintentionally overriding variable values.

Raising Variables

Most of the examples so far have used the var keyword to declare a variable and initialize the variable with a value. Once declared and initialized, the value can be accessed or reassigned.

If you try to use a variable before it has been declared and initialized, the result will be undefined.


console.log(x);
// Variable assignment
var x = 100;
undefined

However, if you omit the var keyword, the variable will not be declared, but only initialized. This will return a ReferenceError and stop the script from executing.

// Attempt to use a variable before declaring it
console.log(x);
// Variable assignment without var
x = 100;
ReferenceError: x is not defined

This is due to hoisting, a behavior in JavaScript that moves variable and function declarations to the top of their scope. Since only the actual declaration is hoisted and not the initialization, the first example returns undefined.

To better demonstrate this concept, we wrote the following code and explained how JavaScript reads it:

// The code we wrote
console.log(x);
var x = 100;
// How JavaScript interpreted it
var x;
console.log(x);
x = 100;

Before execution JavaScript script stores x in memory as a variable. Because the variable was called before it was defined, the result is returned undefined rather than 100. However, this does not raise a ReferenceError or stop the script. Although the var keyword didn't actually change the location of the var, it demonstrates how hoisting works. This behavior can cause problems because the programmer who wrote this code most likely expects the output of x to be true rather than undefined.

Raising can also lead to unpredictable results, as in the following example:


var x = 100;
function hoist() (
// A condition that should not affect the outcome of the code
if (false) (
var x = 200;
}
console.log(x);
}
hoist();
undefined

In this example, the global variable x is 100. Depending on the if statement, x may change to 200, but since the condition was false, it should not affect the value of x. Instead, x was raised before the start of hoist() and the value became undefined.

This unpredictable behavior can cause errors in the program. Since let and const are defined at the block level, they will not be hoisted in the same way as in the example below.

// Initialize x in the global scope
let x = true;
function hoist() (
// Initialize x in the function scope
if (3 === 4) (
let x = false;
}
console.log(x);
}
hoist();
true

Duplicate variable declarations, which are possible with var, will cause an error with let and const.

// Attempt to overwrite a variable declared with var
var x = 1;
var x = 2;
console.log(x);
2
// Attempt to overwrite a variable declared with let
let y = 1;
let y = 2;
console.log(y);

Uncaught SyntaxError: Identifier ‘y’ has already been declared
So, variables declared with var can be affected by hoisting. Hoisting is a mechanism in JavaScript in which variable declarations are stored in memory. This may result in undefined variables in the code. The let and const keywords solve this problem by causing an error if you try to use a variable before declaring it or declare a variable more than once.

Constants

Many programming languages ​​use constants, which are values ​​that cannot be changed. That is, values ​​assigned to a constant cannot be reassigned.

By general convention, const identifiers are written in uppercase. This distinguishes them from other variables.

In the example below, the SPECIES variable is initialized as a constant using the const keyword. Attempting to reassign a variable will result in an error.

// Assign value to const
const SPECIES = "human";
// Attempt to reassign value
SPECIES = "werewolf";
console.log(SPECIES);
Uncaught TypeError: Assignment to constant variable.

Since const values ​​cannot be reassigned, they must be declared and initialized at the same time, otherwise an error will occur.

// Declare but do not initialize a const
const TODO;
console.log(TODO);
Uncaught SyntaxError: Missing initializer in const declaration

Values ​​that cannot be changed by programming are called immutable, and values ​​that can be changed are called mutable (obviously). The values ​​of a constant cannot be reassigned, but they are mutable because the properties of objects declared with const can be changed.

// Create a CAR object with two properties
const CAR = (
color: "blue",
price: 15000
}
// Modify a property of CAR
CAR.price = 20000;
console.log(CAR);
( color: "blue", price: 20000 )

Constants allow you to communicate to other programmers working on the project, and to yourself, that a given variable should not be reassigned. To declare a variable that can be reassigned, you should use let.

Conclusion

In this manual, you learned what a variable is, became familiar with the rules for naming variables, and learned how to reassign their values. You also learned about variable scoping and hoisting, the limitations of the var keyword, and how let and const eliminate these problems.

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, then 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 type declaration is missing. 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.

A variable is a named memory location in which you can both store some information and retrieve it from it.

Declaring (creating) variables is done using the var keyword.

// message - variable name var message;

When you create a variable, you can immediately assign a value to it.

Assigning a value to a variable is done using the “=” operator.

// for example, create a variable email and assign it the string " [email protected]"var email = " [email protected]"; // set the email variable to a new value email = " [email protected]";

To get the value of a variable, simply refer to it by name.

// for example, output the value of the email variable to the browser console: console.log(email);

To declare more than one variable using a single var keyword, you must use a comma.

Var price = 78.55, quantity = 10, message;

JavaScript is a dynamically or weakly typed language. This means that when a variable is declared, it does not need to specify the data type it can accept. Therefore, you can first place a value of one data type in a variable, and then another.

Var output = "success"; // the variable has a string data type output = 28; // the same variable, but already of the “number” data type output = true; // the same variable, but already storing a Boolean value

The value of a variable can be changed an unlimited number of times.

// the age variable is created var age; // variable age is assigned the value 67 age = 67; // variable age is set to "Retirement age" age = "Retirement age"; // variable age is set to 55 age = 55;

A good practice when developing client applications is to use only one data type in a given variable, i.e. Do not write values ​​of different data types to a variable. To understand what type of data should be expected in a variable, when creating a variable, it is recommended to immediately initialize it with a specific value.

The variable name can be composed of letters, numbers, and the symbols $ and _. In this case, the first character of the variable must not be a number. In addition, you cannot use reserved words as variable names.

// creating two variables, the first variable is named phone, the second is meassage; var phone, message;

The case of the letters in the variable name matters. That is, for example, the variable phone and Phone are two different variables.

If strict mode is not used, then you can create a variable with the initial value without the var keyword.

Price = 250.00; // created a variable and initialized it with the number 250.00 percent = "20%"; // created a variable and initialized it with the string “20%”

But creating variables in this way is not recommended.

Data types

IN JavaScript types data can be divided into primitive and object.

Variables containing primitive data types store their value explicitly.

There are 5 primitive data types in JavaScript:

  • number;
  • string;
  • boolean type (boolean);
  • null;
  • undefined.

If one variable is assigned the value of another that contains a primitive data type, it will receive its own copy of that value.

Var x = 77, y = x; x = 55; y; // 77

Variables containing an object do not actually store the object itself, but a reference to it.

If one variable is assigned the value of another that contains an object (a link to it), then it will also receive a link to it. As a result of this operation, these two variables will contain a reference to the same object.

// example 1 (with data type "object") var coord1 = (x: 77, y: 100), coord2 = coord1; coord1.x = 55; // set the x property of the object to a new value coord2.x; // 55, because coord1 and coord2 contain a reference to the same object // example 2 (with an array data type) var coord1 = , coord2 = coord1; coord1 = 55; // set the element with index 0 to a new value coord2; // 55, because coord1 and coord2 contain a reference to the same object // example 3 (with data type "date") var date1 = new Date(2018,00,01), date2 = date1; date2 = date2.setDate(date2.getDate()+7); // increase the date by 7 days date1; // 01/07/2018, because date1 and date2 contain a reference to the same object

Number

The numeric data type in JavaScript is generic. It is used to represent both integers and fractions.

Var int = 5; // integer var float = 5.98; // a fractional number

The format for representing numbers in JavaScript is in accordance with the IEEE 754-2008 standard.

Integers in JavaScript can be specified not only in decimal, but also in octal (0) or hexadecimal (0x) using prefixes specified in parentheses:

Var int = 010; // 8 int = 055; // 45 int = 0xFF; //255 int = 0xB8; // 184

It is possible to write numbers in exponential form:

Var num = 2e3; // exponential notation of the number 2*10^3 (2000) num = 2e-3; // exponential notation of the number 2*10^-3 (0.002) num = 3.2e3; // 3200 num = 1.5e-2; // 0.015

In addition to numbers, the numeric data type also contains special numeric values:

  • Infinity (positive infinity);
  • -Infinity (negative infinity);
  • NaN (Not a Number).

The special value Infinity means a very large positive number, i.e. a number that cannot be represented in JavaScript because it is too large.

Special meanings -Infinity means, on the contrary, a very large negative number, i.e. a number that cannot be represented by JavaScript because it is also too large.

An example of expressions that will return special numeric values ​​as a result of their calculation:

5/0; // Infinity -5/0; // -Infinity Math.pow(10,399); // Infinity (10 to the power of 399) Math.pow(10,399); // -Infinity (-10 to the power of 399)

The NaN value is returned as a result of performing mathematical operations that JavaScript cannot calculate.

5 - "Hi"; // NaN (subtract a line from the number 5) 1000 / "20px"; // NaN (number divided by string) true * "1rem"; // NaN (boolean value true multiplied by string)

What is very interesting is that the value of NaN in JavaScript is not equal to anything including itself.

NaN == NaN; // false NaN === NaN; //false

Boolean data type

Boolean is a primitive data type that has only two values: true and false.

Var a = true; var b = false;

String

String is a data type that is used in JavaScript to represent text.

A JavaScript string can be 0 or more characters long.

JavaScript always uses Unicode as its string format.

Creating a string (string literal) is done by enclosing text in single or double quotes.

"JavaScript"; "ECMAScript";

In JavaScript, there is no difference between single and double quotes.

But, in some cases, it makes sense to use single quotes rather than double quotes and vice versa.

For example, when a string contains double quotes, it is more convenient to enclose it in single quotes. This will eliminate the need to escape double quotes in it.

""ECMAScript""; // without escaping (using single quotes) "\"ECMAScript\""; // with escaping

A string in JavaScript can contain Special symbols. For example, \n (line feed), \t (tab), \r (carriage return), etc.

"This is a sentence.\nAnd this is also a sentence, but it will start from a new line.";

With strings you can perform the operation of addition (union) or, in other words, concatenation. The "+" operator is used for this. The meaning of this operation is to append the second line to the end of the first.

"I love " + "JavaScript"; // I love JavaScript

The value is "undefined"

undefined is a special primitive data type that has a single value equal to undefined .

This data type has a declared variable that has not yet been assigned a value.

Var num; // undefined

The value undefined will also be returned when accessing a non-existent property of an object.

Var obj = (); // empty object obj.prop; // undefined

"null" value

null is a special primitive data type that has a single value equal to null .

null is just a special value that has the meaning of "nothing" or "unknown value", i.e. it clearly doesn't mean anything.

Object

An object is a data structure consisting of name-value pairs.

Creating an object using object literal notation is done as follows:

( name_1: value_1, name_2: value_2, name_3: value_3, ... )

As you can see, the name is separated from the value using a colon, and pairs are separated from each other using a comma.

Moreover, if the value of the pair is a function, then it is called a method of this object. All other pairs, i.e. pairs in which a function is not used as a value are called object properties.

In other words, an object is a data structure consisting of properties and methods.

Var person = ( name: "Vitaly", age: 27, getAge: function () ( return "Age: " + this.age; ) )

Accessing the properties of an object is done through a period or using bracket notation.

// display the value of the age property in the browser console // 1st method (via a dot) console.log(person.age); // Method 2 (using parentheses) console.log(person["age"]); // call the getAge method; the value it returns will be output to the console console.log(person.getAge());

typeof operator

The typeof operator is used to obtain information about the data type of an expression as a string.

The syntax of the typeof operator (option without parentheses):

Typeof expression

Typeof operator syntax (using parentheses):

Typeof(expression)

Var name, age = 37, email = " [email protected]", isLicense = true, interest: null, lastExperience: ( period: "June 2011 - June 2018", place: "ISACA, Moscow", position: "Web designer" ), getExperience: function() ( return lastExperience.period + " ("+ lastExperience.position + " - " + lastExperience.place + ")"; ); typeof name; // "undefined" typeof age; // "number" typeof isLicense; // "boolean" typeof interest; / / "object" (1) typeof lastExperience; // "object" typeof getExperience; // "function" (2) /* (1) is a bug that has been present in the language since its first implementation; it has not been fixed in order to maintain compatibility and this must be taken into account when writing scripts; null is a primitive data type, it is not an object */ /* (2) - it is very convenient that the typeof operator separates functions separately; but a function in JavaScipt is also object; this can be easily verified by executing the following construction: */ typeof getExperience.__proto__.__proto__ // "object" (the function prototype is an object)

Constants

With the release of ECMAScript 6, it became possible to create constants. This is done using the const keyword.

Const COLOR_RED = "#ff0000";

A constant is a variable whose value is protected from change. Those. When you try to change the value, an error will be thrown.

Const COLOR_RED = "#ff0000"; COLOR_RED = "#f44336"; // Uncaught TypeError: Assignment to constant variable.

If, for example, a constant contains an object, then it cannot be changed, or rather a reference to it. But the properties of this object can be changed.

Const COLORS = ( red: "#ff0000", green: "#00ff00", blue: "#00ff00" ) COLORS = ["#ff0000","#00ff00","#00ff00"]; // Uncaught TypeError: Assignment to constant variable. COLORS.green = "#4caf50";

The syntax rules for creating variable names in JavaScript are:

  • The following symbols are used for variable names: a-z, A-Z, numbers, the $ symbol, and the underscore (_).
  • The variable name cannot begin with a number.
  • JavaScript is case sensitive, something to keep in mind when programming. itcounter and it C ounter are different variables.
  • JavaScript has no restrictions on the length of a variable name.

Examples of correct variable names:

  • itcounter
  • $_itcounter
  • it_counter

Incorrect variable names:

  • 9room
  • it-counter
  • #itcounter
  • &itcounter

Variables are declared with the var command.

Variables can store strings and numbers. In fact, you can store other types of data, but we'll talk about them later.

String variables

To write a string to a variable, you need to enclose its value in quotes, double or single.

Var $stroka_1 = "Hello!"; var $stroka_2 = "Caution!";

You can include a double quote in a string created with a single quote, and vice versa.

Var $stroka_1 = ""Hello!" is a greeting."; var $stroka_2 = ""Caution!" is a warning."; document.write($stroka_1); document.write("

To display a quote of the same type, it must be escaped with a backslash character. It's simple:


"); document.write($stroka_2);

Variable values ​​can be assigned to other variables:

Var $stroka_1 = "\"Hello!\" is a greeting."; var $stroka_2 = "\"Caution!\" is a warning."; document.write($stroka_1); document.write("
"); document.write($stroka_2); $stroka_2 = $stroka_1; document.write("
"); document.write($stroka_2);

In this example, we first assigned one string value to the $stroka_2 variable, but then assigned it the value of the $stroka_1 variable.

Concatenating Strings

Very often you need to combine several lines into one. For example, our last example is too cumbersome.

Combining (concatenating) strings in JavaScript is done using the + sign.

To display 2 string variables separated by a tag
variables you can use one command document.write() .

Var $stroka_1 = ""Hello!" is a greeting."; var $stroka_2 = ""Caution!" is a warning."; document.write($stroka_1 + "
" + $stroke_2);

The concatenation operator + can also be used in variables:

Var $stroka_1 = ""Hello!" is a greeting."; var $stroka_2 = ""Caution!" is a warning."; var $stroka_3 = $stroka_1 + "
" + $stroka_2; document.write($stroka_3);

Numeric variables

To create a numeric variable, you simply assign a numeric value to it.

Var $count_1 = 23; var $count_2 = 10.34; document.write($count_1 - $count_2);

Now another example:

Var $count_1 = 23; // Numeric variable. var $stroka_1 = "57"; // String variable. document.write($stroka_1 + $count_1);

You see, the value of the $stroka_1 variable is in quotes, which means it is a text variable. Then we add the text and numeric variables and get the string "5723", this is how JavaScript works in such cases - it turns the number into a string and adds it to the summed string.

Boolean variables

There is such a type of variables - Boolean. Everything is simple, there are only two values: true and false, that is, true (true) and false (false).

This data type is used in comparison operations. Here are simple examples:

  • 9 > 1 is true.
  • 2 > 5 is a lie.
var $count = 2

Now let's try to substitute Boolean values ​​into arithmetic operations. Let's summarize the two comparison operations:

Var $count = (3 > 2) + (4 > 2); document.write($count);

This is a weird post, I know. But the $count variable will be equal to 2. In a mathematical context, the value of true = 1 and the value of false = 0.

Comparison operators are used in a commonly used if statement in JavaScript. The word if in English means - if.

Var $count = 100; if ($count == 100) document.write("The $count variable is 100.");

In this example, a message will be displayed on the screen because the condition of the if statement ($count == 100) is true. If you change the value of the $count variable to 99, then the condition ($count == 100) will become false and nothing will be displayed on the screen.

Simple Variable Types

In JavaScript, variables are classified into several types. We have already looked at string, numeric and Boolean (logical) types. Here is a broader list of simple types:

  • string - string variable.
  • number - numeric variable.
  • boolean - Boolean variable.
  • null is a special value for “nothing”.
  • undefined - type “no value assigned”.

The value of a null variable forms its own separate null type, consisting of the only possible null value. null is a special value that has the meaning of "nothing" or "the value is unknown."

Var $price = null; // this means that the price is not known.

In JavaScript, you can find out the type of variables using the typeof statement.

Var $count; document.write(typeof $count + "
"); var $count = true; document.write(typeof $count + "
"); var $count = "true"; document.write(typeof $count + "
"); var $count = 100; document.write(typeof $count + "
"); var $count = null; document.write(typeof $count + "
");

The syntax of the typeof statement could be:

  • typeof $count
  • typeof($count)

So, run the code from the last example and look at the result. The type of the variable null will be object. This is a bug in the language and will probably never be fixed due to the need to keep existing JavaScript scripts compatible with new versions of the language.

The object type is no longer a primitive type; we will talk about it in other lessons.

Variables in JavaScript are containers for storing various information.

JavaScript Variables

JavaScript variables are "containers" into which you can load various information and later retrieve it back.

Each JavaScript variable must have its own unique name, which can begin with a Latin letter or the "_" symbol.

Please note: Variable names in JavaScript cannot begin with numbers.

Please note: since JavaScript is case sensitive, variables with the same names written in different case (for example, var and VAR) will be different variables.

Creating Variables

Creating variables in JavaScript is often called "announcement" variables.

Variables in JavaScript are declared using the var command.

//Create a variable named ex1 var ex1; //Create a variable named ex2 var ex2;

The variables created above will be empty, that is, we have created containers, but have not loaded any values ​​into them.

Values ​​can also be loaded into containers right at the time of creation, as in the example below:

//Create a variable named ex1 containing the value 4 var ex1=4; //Create a variable named ex2 containing the value 5 var ex2=5;

In order to extract a value from a previously created variable, you need to refer to its name.

In the following example, we will extract the contents of variables and immediately output them to the page using the document.write command.

//Write the number 4 into the variable ex1 var ex1=4; //Write the number 5 into the variable ex2 var ex2=5; //Output the contents of variable ex1 to the page document.write(ex1+"
"); //Output the contents of the variable ex2 document.write(ex2+"
"); //Change the contents of the ex2 variable ex2=200; //Output the new contents of the ex2 variable document.write(ex2);

Quick view

String variables

In addition to numbers, you can store arbitrary text in variables. Variables that store text are called string variables.

When writing text to a variable, be sure to enclose it in double quotes (") or single quotes (").

//Write the string “Hello everyone!” into the ex variable var ex="Hello everyone!"; //Output the value of the ex variable to the page document.write(ex);

Quick view

Defining variables with and without var

In JavaScript, you can define variables with or without var.

//Create a new variable with var var ex=123; //Create a new variable without var ex2=20;

You might think that variable declarations with and without var always produce the same result, but this is only true when the declaration occurs in a global context (i.e. outside of all functions).

If the declaration occurs in a local context (i.e., in the body of a function), a declaration with var creates a local variable (i.e., a variable that will be available only in the body of this function and will be destroyed after the function is executed), a declaration without var creates a global variable (i.e. a variable that will be available to other functions within a given script).

Note that we'll talk more about local and global variables later in this tutorial.

About deleting and redefining variables

By redefining variables, you do not erase the value that is stored in them.

Var ex=123; var ex; document.write(ex); // Prints 123

If you want to delete a variable in JavaScript and it was not declared with var, you can use the delete operator.

Ex=123; delete ex;

The delete operator cannot delete variables declared with var, so if a variable was declared with var, the only way to delete it is to set it to null or undefined.

Var ex=123; ex=null; // or ex=undefined

Do it yourself

Exercise 1 . Correct the errors in the code below:

Exercise 1

var 33var=33; document.write(33var); document.write("
"); var str1=Hello everyone!; document.write(str1); document.write("
"); var vaR = 288; document.write(var); document.write("
");

Task 2. The external file secred1.js contains the variables sec1, sec2, sec3 and sec4, which contain the letters of the code word (not in order). Connect an external file and find out the code word by displaying variable values ​​on the page.

Related publications