Variables. Arithmetic and Boolean Operations in JavaScript

A variable is a named piece of memory in which you can both store some information and get it from it.

Variables are declared (created) 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 an email variable and assign 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, display the value of the email variable in the browser console: console.log(email);

To declare more than one variable with the same 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 declaring a variable, it does not need to specify the type of data it can take. Therefore, a variable can be placed first with a value of one data type, and then another.

var output = "success"; // variable has string data type output = 28; // the same variable, but already having the data type "number" output = true; // the same variable, but already storing a boolean value

Variable value can be changed unlimited quantity once.

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

It is good practice when developing client-sides to use only one data type in a particular variable, i.e. do not store values ​​that have different data types in a variable. To understand what type of data to expect in a variable, it is recommended to immediately initialize it with a certain value when creating a variable.

The variable name can be composed of letters, numbers, and the symbols $ and _. The first character of the variable must not be a digit. In addition, reserved words cannot be used as a variable name.

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

The case of letters in a 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 a 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, data types can be divided into primitive and object types.

Variables containing primitive data types store the value explicitly.

There are 5 primitive data types in JavaScript:

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

If one variable is assigned a value to another that contains a primitive data type, then it will get 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, which contains an object (a reference to it), then it will also receive a reference 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 data type "array") 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); // increment the date by 7 days date1; // 01/07/2018, because date1 and date2 contain a reference to the same object

Number (number)

The numeric type in JavaScript data is generic. It is used to represent both whole and fractional numbers.

varint = 5; // integer var float = 5.98; // fractional number

The number representation format 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 number system (0x) using the prefixes given in parentheses:

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

You can write numbers in exponential form:

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

The numeric data type, in addition to numbers, 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.

The special values ​​-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 as a result of which the calculation will be returned special numeric values:

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 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 multiply by string)

That being said, it's very interesting that the NaN value in JavaScript is not equal to anything including itself.

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

Boolean data type (Boolean)

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

Var a = true; varb=false;

String

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

JavaScript string can be 0 or more characters.

JavaScript always uses Unicode as the string format.

The creation of a string (string literal) is done by enclosing the 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\""; // escaped

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

"This is a sentence.\nThis is also a sentence, but it will start on 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 string to the end of the first.

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

Meaning "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.

Varnum; // undefined

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

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

Value "null"

null is a special primitive data type that has one value, null .

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

Object

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

An object is created using object literal notation 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 the pairs are separated from each other using a comma.

Moreover, if a function acts as the value of a pair, then it is called a method of this object. All other pairs, i.e. pairs that do not use a function 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; ) )

Access to the properties of an object is performed through a dot or by means of bracket notation.

// display the value of the age property in the browser console // 1 way (through a dot) console.log(person.age); // 2nd way (using brackets) console.log(person["age"]); // call the getAge method; the value it will return 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 for the typeof operator (the version without the parentheses):

typeof expression

The syntax for the typeof operator (using parentheses):

typeof(expression)

Varname, 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 for compatibility purposes and should 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 seen if you execute 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 being changed. Those. attempting to change the value will throw an error.

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";

To be honest, I did not want to introduce this topic from the beginning. What can be said about variables, especially in JavaScript? But then I remembered how sometimes I dealt with complex constructions and had difficulty understanding some expressions that seemed to be unacceptable in other programming languages. You can say this: here you will not get the "Invalid data type" error, and if it does, it will be very rare. If you have worked with other programming languages, then remember how often you had an error about incorrect data types. In JavaScript, a data type can be easily overridden without you noticing where, and that's where it gets tricky. On the other hand, if you are well versed in the principles of type conversions, know all the properties of variables and arrays, these features will only bring you confidence in writing programs.

JavaScript variables can store values ​​of various types:

  • Strings - a sequence of characters;
  • Numeric values ​​- integers and real numbers;
  • Boolean values ​​are just two values ​​true or false;
  • Arrays are 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 a new document is loaded into the browser, any variables created in the program will be removed.
To save any values ​​when loading a new document in JavaScript, there are only 2 solutions:
  • by creating variables in the frame-containing document top level;
  • by using "cookies";
To store variables and functions using framed documents, these variables and functions must be defined in the top-level document and then use the parent or top properties. window object to access them from documents loaded in 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 cookie values ​​and sorting them out at subsequent stages of work, you can restore the necessary values. We will talk more about cookies later.

Variable names, creating variables

It is much easier to create a variable in JavaScript than in other programming languages. For example, when creating a variable, it is not necessary to specify its type. Variables are defined with or without initial values. During program execution, already created variables can even be cast to different data types. Variable names can start with any letter (a through z, or A-Z) or underscore (_), the remainder can contain numbers, underscores, and letters. Remember that variable names distinguish 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 required to store a value in a variable, and is not necessary when working with variables created without an initial value. For example:

VarMyVariable = 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 framed document, it should be accessed using the top.MyVariable expression, or even better parent.MyVariable to protect against nested frames.

In language JavaScript variables can be overridden, even 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 completion of the block will be equal to the numerical value 320. We will talk about the principles of variable type conversion later. A variable can be defined without using the "Var" operator, but simply assigning a value, and what type of data will be assigned, that type will be a variable. The "Var" operator is mainly used for the readability of a JS program. A variable can also be set without initial values, for example:

VarMyVariable;

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, comparing such a variable with null, you can find out if 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 you more flexibility, but also the possibility of confusion - remember this. A variable that has not been created cannot be accessed. If you want to create a temporary variable, such as a loop counter, you need to prefix it with var:
for (var i=0; i<= document.links.length; i++) {
. . . . .
}
in this example, the variable i is initialized and then used as the counter of the for statement.
Variables defined with var are separated by a comma. For greater readability of a JS program, each variable is usually written on a new line.

String variables

A string is a set of characters enclosed in single or double quotes. Strings in JavaScript are treated as objects. This is by far the most common kind of object, so JavaScript has many standard functions for manipulating strings. You can create a String object in one of several ways:

  • assigning a value using the String() constructor;
  • using the Var operator and the assignment operator to create and initialize a string;
  • creation and initialization of a string variable in an assignment statement;
  • converting a variable of a numeric type by adding to a string type (10+"" ==> "10");
The simplest and most common way to create a String object is to use operators like

Var myVariable = "Good beer";

The above statement assigns the string "Good beer" to the string variable myVariable. The variable myVariable is treated as a string object and can use any of standard methods JavaScript String object. 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 operator new. In fact, the String object is not a JavaScript language object, but a built-in object of the browser, mainly because strings are created when the user needs them. Consider an example:

Var myVariable = new String();

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

The String() constructor accepts a given string as an argument:

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

A string object can contain special characters that control string formatting:

  • \n - newline character;
  • \r - carriage return character;
  • \f - transition code to a new page;
  • \xnn - character representation as hexadecimal ASCII code nn;
  • \b - key code.
these characters will only be interpreted correctly in containers