JavaScript - Variables. Constants. Data types. Grammar and types Variable var

💖 Do you like it? Share the link with your friends

Working in Javascript, we can enter numeric, string and logical values, but they only work if the program contains the necessary information. For this purpose, variables were created that allow us to store various types of information and represent it as a kind of container that we can access at any time and get the information that is located in it.

Creating a Variable

A variable is created in two stages: declaring the variable and assigning a name to it.

First, we must declare the variable, that is, declare it, this is done using keyword var. Next we write an instruction, this is the name of the variable, its name is how we will access it, for example I will write dwstv.


What you name the variables is, of course, up to you, but there are a few rules that must be followed for javascript to work:

  • first rule, avoid using reserved words. Some words in the JavaScript language are used in the system itself, such as the word var with which we declare a variable. In addition, some words, such as alert , document , window , are considered special properties of a web page. If you try to use them as variables, you will receive an error message. Here you can see a list of reserved words.
  • second rule, the variable name must begin with a letter, $ or _ symbol. That is, the variable cannot begin with a number or punctuation mark: the name 1dwstv and &dwstv will not work, but the names $dwstv and _dwstv will.
  • third rule, the variable name can contain letters, numbers, $ and _ symbols, and spaces or other special characters cannot be used in the name: dws&tv and dws tv are invalid names, but this format can be dws_tv and dwstv1 or dws_tv_1.
  • fourth rule, variable names are case sensitive. The JavaScript interpreter treats lowercase and uppercase letters differently, meaning that the DWSTV variable is different from the dwstv variable, and also from the DwStv and Dwstv variables.
  • fifth rule, it is not recommended to use characters other than Latin; variables written in Cyrillic, although they will work, are not guaranteed, and will not be understood by colleagues from other countries.

These are the basic five rules that I recommend following, in addition to them I would also like to say, assign clear and expressive names to your variables. Name the variables according to the type of data that is stored in them, this will help you further understand what is written, and, looking at such variables, it will be clear what we are talking about.

When naming variables, try to make them easy to read. When using multiple words, add an underscore between them, or start each word after the first with a capital letter. For example, dwsTv or dws_tv.

Using Variables

At the beginning of the lesson, we looked at what a variable consists of, now that we know how to create it, we can store any types of data in it at our discretion.

In order to put data into a variable, a special symbol is used, the equal sign (=), it is called an assignment operator, since it is used to assign a value to a variable.


For example, let's put a digital value in the dwstv variable, the number of subscribers is 8500, declare the variable var dwstv; and in the second line we put in it the value dwstv = 8500;

Var dwstv; dwstv = 7200;

And so, with the first line we created a variable, and with the second we saved the value into it. We can also create a variable and store values ​​in it using a single statement, for example:

Var dwstv = 7200;

In a variable we can store any types of data that we covered in previous lessons, these can be numeric, string and logical values:

Var dwstv = 7200;var lessons = ‘JavaScript’; var youtubeKanal = 'DwsTV'; var subscribers = '7700'; var content = true;

We can also save space and time by declaring variables with one var key, example:

Var lessons = 'JavaScript', youtubeKanal = 'DwsTV', subscribers = '7700', content = true;

After storing the values ​​in variables, we are able to access this data. To do this, just use the name of the variable itself.

For example, if we want to open an alert dialog and display the value stored in the kanal variable, we can simply write the variable name in the alert function.

Alert(channel);

Note that we don't put quotes around variables - they're only for strings, so we don't write alert('kanal') as that would give us the words kanal rather than the value stored in the variable.

Now I think you understand why strings need to be quoted: the JavaScript interpreter treats unquoted words as either special objects (such as the alert() command) or variable names.

And there is also the moment when we have declared a variable with the keyword var and want to change the value in the variable, it is not necessary to declare it again by writing the word var , it is enough to call the name of the variable and assign a new value to it.

Subscribers = '10000';

At the end of this lesson, I want to say that by learning any language, you will not learn to program. Undoubtedly, you will learn something new, but most likely your brain will not remember this information, since you are not working with it. It is impossible to learn a language without practicing, so from this lesson you will receive a small task so that the information provided will fit into your mind and you can work with it.

Practical task:

Create three variables, assign one a numeric value, the second a string value, and the third a logical value. Declare all variables with one keyword var, and display them on the page. Then redefine the variable with a numeric value and display the result using the alert() function.


At the beginning of the next video we will analyze this task, share your results in the comments, write if anyone has any questions. If you liked the lesson and want to support the project, just share it on social networks.

In the next lesson, we will look in detail at how to work with data types and variables, get acquainted with mathematical operations and the order of their execution, and also analyze methods for combining string and numeric values.

The lesson was prepared by Denis Gorelov.

To be honest, I didn’t want to introduce this topic from the beginning. What about variables, especially in JavaScript? But then I remembered how I sometimes dealt with complex constructions and had difficulty understanding some expressions that seemed unacceptable in other programming languages. We can say this: here you will not get the “Invalid data type” error, and if you do, it will be very rare. If you have worked with other programming languages, then remember how often you got the error about invalid data types. In JavaScript, a data type can be easily redefined, but you may not even notice where - that's where the difficulty lies. On the other hand, if you are well versed in the principles of type conversions and know all the properties of variables and arrays, these capabilities will only give you confidence in writing programs.

JavaScript variables can store different types of values:

  • Lines are a sequence of characters;
  • Numeric values ​​- integers and real numbers;
  • Boolean values ​​- only two values ​​true or false;
  • Arrays - sets of variables of the same type;
  • Dates are date and time values.
The lifetime of a variable is related to the window in which they are created and depends on where they are defined. JavaScript programs are contained in HTML documents, and when you load a new document into the browser, any variables created in the program will be deleted.
To save any values ​​when loading a new document in JavaScript, there are only 2 solutions:
  • by creating variables in the frame document top level;
  • by using "cookies";
To store variables and functions using framed documents, you must define those variables and functions in the top-level document, and then use the parent or top properties of the window object to access them from documents loaded in the frames. IMPORTANT: such variables and functions must be set in the head of the top-level document between the tags. . .. Of course, there is a possibility that the document can be loaded without a frame and then accessing an undefined object will cause an error, but you can first check whether the document is loaded into a frame:



Cookies allow small pieces of information to be stored on local disk user. By setting the cookie values ​​and resetting them at subsequent stages of work, it is possible to restore the necessary values. We will talk about cookies in more detail later.

Variable names, variable creation

In JavaScript, creating a variable is much easier than in other programming languages. For example, when creating a variable, there is no need to specify its type. Variables are defined both with and without initial values. During program execution, already created variables can even be converted to different data types. Variable names can begin with any letter (a through z, or A-Z) or an underscore (_), and the rest can contain numbers, underscores, and letters. Remember that variable names differ between upper and lower case characters: for example, MyVariable is not the same as myvariable.
A variable can be created in one of the following ways:

  • using the var operator and the assignment operator (=);
  • using the assignment operator (=).
The Var operator is used not only to create a variable, but also to initialize it. The assignment operator (=) is needed to store a value in a variable, and it is not necessary to use it when working with variables created without an initial value. For example:

Var MyVariable = 35

Creates a variable named MyVariable containing the numeric value 35. The variable exists as long as the current document is loaded. If you create this variable in a top-level document containing a frame, it should be accessed using the expression top.MyVariable, or better yet parent.MyVariable to protect against nested frames.

In language JavaScript variables can be overridden, even by specifying a different data type. For example, after executing the statement

Var MyVariable = "35"

The variable will already store the string "35". Such transformations sometimes lead to misunderstandings. For example:



What value do you think the variable "c" will take after the program is executed? If you are not familiar with the rules for converting variables in JavaScript, you will not guess. The value of the variable "c" after the block is completed will be equal to the numerical value 320. We will talk about the principles of converting variable types later. A variable can be defined without using the “Var” operator, but simply by assigning a value, and whatever data type is assigned, the type of the variable will be. The "Var" operator is used mostly for the readability of a JS program. The variable can be specified without initial values, for example:

Var MyVariable;

A variable named MyVariable has been created with no defined data type and no initial value. Variables created using such declarations are known as null variables. For example, by comparing such a variable with the value null, you can find out whether the variable is defined. However, one should not confuse different things: "" - an empty string is a string type and not a null value at all.

The type of a variable can be set anywhere in a JS program, unlike other programming languages, which gives additional flexibility, but also the possibility of confusion - remember this. A variable that has not been created cannot be accessed. If you need to create a temporary variable, such as a loop counter, you need to prefix it with var:
for (var i=0; i "10"); The simplest and most common way to create a String object is to use operators such as

Var myVariable = "Good beer";

The following statement assigns the string "Good Beer" to the string variable myVariable. The myVariable variable is treated as a String object and can use any of the standard JavaScript String object methods. The Var operator can be skipped, as mentioned earlier, it is needed mainly for the readability of the program.

To create string objects, you can use the String() constructor with the new operator. The String object is not actually part of the JavaScript language, but is a built-in browser object, mainly because strings are created when the user needs them. Let's look at an example:

Var myVariable = new String();

This statement creates a new object, an empty string, named myVariable. Initially, this is the empty string (""), and the value of the myVariable.length property is 0.

The String() constructor allows a given string to be passed as an argument:

Var myVariable = new String("Proper beer");

A string object can contain Special symbols, controlling string formatting:

  • \n - newline character;
  • \r - carriage return character;
  • \f - code for moving to a new page;
  • \xnn - representation of the character as hexadecimal ASCII code nn;
  • \b - key code.
these characters will only be interpreted correctly in containers and "Alert" methods. Formatting for document.write() is done by other methods or HTML tags.
The String object has only one property, length, whose value is the number of characters in the string contained in the object. String object methods can be divided into two categories:
  • HTML document formatting methods;
  • string processing methods.
Document formatting methods are used to output strings to a document, and string manipulation methods are used to examine and modify the contents of a String object.
Here is a list of methods: (the letter F is formatting methods, and the letter U is row management)
Method Description
anchor() U Creates a named label, i.e. tag from the contents of the object
big() F Encloses a string in a container. . . , to display in large font
blink() F Encloses a string in a container. . . so that it appears flashing.
bold() F Encloses a string in a container. . . so that it appears in bold.
charAt() U Returns the character at a given string position
fixed() F Encloses a string in a container. . . so that it is displayed in a constant width font.
fontcolor() F Encloses a string in a container. . . so that it appears in a specific color.
fontsize() F Encloses a string in a container. . . so that it is displayed in a specific font size.
IndexOf() U Returns the index of the first specified character found in the string.
italics() F Encloses a string in a container . . . so that it appears in italics.
lastIndexOf() U Returns the index of the last specified character found in a string.
link() U Creates a hyperlink tag . . . and puts the contents of the object into it
small() F Encloses a line in a tag. . . so that it appears in a smaller font size.
strike() F Encloses a string in a container. . . so that it appears crossed out.
sub() F Encloses a string in a container. . . so that it appears as a subscript.
substring() U Returns a substring of a text string.
sup() F Encloses a string in a container. . . so that it appears as a superscript.
toLowerCase() U Converts all letters of a string to lowercase
toUpperCase() U Converts all letters in a string to uppercase

Numeric variables

Numeric values ​​can be either integer or floating point numbers. Floating point numbers are called real or floating point numbers. The following operations are applicable to numeric values:

  • multiply(*);
  • division(/);
  • addition (+);
  • subtraction (-);
  • increase(++);
  • decrease (--);
In addition, they use the operations of multiplication, division, addition and subtraction in combination with assignment (*=, /=, +=, -=), as well as methods Math object.

Boolean variables

Boolean, or logical, variables contain only literal values ​​- true and false - and are used in logical expressions and operators.
To check the value of a Boolean variable, the logical equality operation is also used:
booleanVar == true
although in this case such a verification operation is unnecessary. To check for values ​​that are not true, use the logical negation sign (!). For example, the expression!booleanVar will return true if booleanVar is false. Instead of the words "true" and "false", you can use the numeric values ​​"1" and "2", since it is the TakBoolean values ​​​​that are represented in the computer's memory: 1==true and 0==false.

Array variables

Array variables contain ordered sets of values ​​of the same type, represented as a single variable for convenience. Many standard document property objects in JavaScript, particularly hyperlinks and labels, are arrays. In JavaScript, an array element must be accessed using an expression:

ArrayName

Where arrayName is the name of the array, and index is a numeric variable or a number that specifies the position of the element in the array. For example, arrayName is the first element of this array. Indices of array elements in JavaScript start from zero. Array elements can be of any type, such as strings or booleans. In addition, under certain conditions, an array can contain elements of different data types. In language JavaScript arrays are created using:

  • constructor Array();
  • constructor Object();
  • user defined constructor.
The Array() constructor not only creates an array object, but also assigns initial values ​​to its elements. It is possible to add elements to an array dynamically - by assigning certain values ​​to the elements of the array. It is also possible to “skip” array elements and set them in any order. To create a new instance of an array object, the Array() constructor must be used with the new operator. For example, the following example creates an array named arrayImg containing two elements, each of which is a String object

Var path = "c:/images/" ,
arrayImg = new Array();
arrayImg = path+"img1.gif";
arrayImg = path+"img2.gif";

When you use the Array() constructor, the length property is set automatically. Therefore, after initializing the array elements in the example above, the expression arrayImg.length returns the value 2. Array elements can also be specified as constructor parameters:

Var path = "c:/images/" ,
arrayImg = new Array(path+"img1.gif", path+"img2.gif");

This expression is a shorthand version of the previous example.
In JavaScript, you can create an array, this is an array in which the elements have different data types:

Var myArray = new Array(3.14, true, 85, date(), "word");

Creates an array whose element myArray is a floating point number, whose element myArray is a Boolean value, and whose element myArray is a Date object.
The size of the array, and therefore the value of the length property of the object created by the Array() constructor, depends on the maximum index value that was used to specify the array element. For example:

Var myArray = new Array;
myArray = "This is the 21st element of the array";

The twenty-first element of the array is assigned the string value "This is the 21st element of the array," and the value of the myArray.length property is 21, regardless of whether array elements with index less than 20 have values.
The length property of an Array object is automatically set when you explicitly specify the number of elements in the Array() constructor:

MyArray = new Array(10);

The operator creates an array of 10 elements from 0 to 9. The length property of an array cannot be set by assignment because length is a read-only property. For example, to set the length property to 10, you only need to determine the value of the last, in this case, the 9th element of the array:

MyArray = new Array();
myArray = 0;

In addition, it is possible to set the values ​​of array elements when constructing it:

MyArray = new Array(0,0,0,0,0,0);

Object() constructor

The concepts of object and array are equivalent, although the Object() and Array() constructors work differently. It is impossible to pass multiple array elements to the Object() constructor, so this expression
var myObj = new Object(value1, value2);
won't work. Arrays created using the Object() constructor do not have a length property. Therefore, when creating an array in this way, you should either traverse this array using for loop and count the elements of the array, or hardcode the length of the array to the value of its first element (this is usually done by simulating the length property), and then access it as needed to check the size of the array, increment the value when adding a new element, and also as a loop parameter when cyclically reading or changing element values. Such an object is often inappropriate for cases where the contents of the array must change dynamically, so in most cases the Array() constructor is used. The index values ​​of arrays created in the Object() constructor also start from zero. To create an array using the Object() constructor, it is common to use a notation like:

Var myObj = new Object();
myObj = 2; // set the array size
myObj = "First element";
myObj = "Second element";

To find out the size of an array created in this way, you need to access the myObj element. The value of the myObj.length property is null, since the value is undefined.

Converting Strings and Numbers

Finally we come to the most interesting topic. The fact is that in the JavaScript language, unlike other languages, there are no functions like Val() and Str(). I once saw a program in JavaScript, I won’t name the author, where, with the help of all kinds of data type conversions, there was an attempt to confuse the program for “non-advanced” users. So, you need to remember two rules:

  • Converting a number to a string of characters is done by adding the numeric argument to the string argument, regardless of the rearrangement of the terms. For example, if the variable is varI = 123, then you can convert the variable and therefore its value into a character string: varI = varI + "" or vice versa: varI = "" + varI. If folded not with empty line: varI = varI + "456", then the result of the value of the varI variable will be "123456". The same is true vice versa: varI = "456" + varI - result: "456123";
  • Converting a string to a number is done by subtracting one operand from another and also regardless of their position. For example, if the variable varI = "123", then you can convert it into a number by subtracting the values ​​0 from it: varI = varI - 0, and accordingly the value of the variable from a string type is converted to a numeric one: 123. When rearranging the operands, the sign of the numeric value will change to opposite. Unlike converting a number to a string, subtraction operations cannot use literal values. So if "JavaScript" + 10 turns into varI == "JavaScript10", then an operation like varI = "JavaScript" - 10 will produce the value "NON" - that is, such an operation is not allowed. And yet, when subtracting a string value from a string value, a transformation also occurs: varI = "20" - "15", the value of the varI variable will be the number 5.

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 ​​to a variable that have Various types data. 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

Numeric type in JavaScript data is universal. 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).

Special meaning Infinity means 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 characters. 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";

Variables in JavaScript are containers for storing various information.

JavaScript Variables

JavaScript variables are "containers" into which you can load various information, and later remove 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.

Last update: 04/05/2018

Variables are used to store data in a program. Variables are designed to store some temporary data or data that can change its value during operation. The var and let keywords are used to create variables. For example, let's declare the variable myIncome:

Var myIncome; // another option let myIncome2;

Each variable has a name. The name is a random string of alphanumeric characters, an underscore (_), or a dollar sign ($), and names must not begin with numeric characters. That is, we can use letters, numbers, and underscores in the name. However, all other characters are prohibited.

For example, the correct variable names are:

$commission someVariable product_Store income2 myIncome_from_deposit

The following names are incorrect and cannot be used:

222lol @someVariable my%percent

Also, you cannot give variables names that match reserved keywords. There are not many keywords in JavaScript, so this rule is not difficult to follow. For example, the following name would be incorrect because for is a keyword in JavaScript:

Var for;

List of reserved words in JavaScript:

abstract, boolean, break, byte, case, catch, char, class, const, continue, debugger, default, delete, do, double, else, enum, export, extends, false, final, finally, float, for, function, goto, if, implements, import, in, instanceof, int, inteface, long, native, new, null, package, private, protected, public, return, short, static, super, switch, synchronized, this, throw, throws, transient, true, try, typeof, var, volatile, void, while, with

When naming variables, keep in mind that JavaScript is a case-sensitive language, that is, two different variables are declared in the following code:

Var myIncome; var MyIncome;

You can define several variables at once, separated by commas:

Var myIncome, percentage, sum; let a, b, c;

Using the equal sign (also called the assignment operator), you can assign a value to a variable:

Var income = 300; let price = 76;

The process of assigning an initial value to a variable is called initialization.

Now the income variable will store the number 300, and the price variable will store the number 76.

The great thing about variables is that we can change their value:

Var income = 300; income = 400; console.log(income); let price = 76; price = 54; console.log(price);

Constants

Using the const keyword, you can define a constant that, like a variable, stores a value, but that value cannot be changed.

Const rate = 10;

If we try to change its value, we will encounter an error:

Const rate = 10; rate = 23; // error, rate is a constant, so we cannot change its value

It is also worth noting that since we cannot change the value of a constant, it must be initialized, that is, when we define it, we must provide it with an initial value. If we don't do this, then again we will encounter an error:

const rate; // error, rate is not initialized



tell friends