JavaScript. Data types and operators. Javascript data types set variable type

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, data types 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 system number system, but also in octal (0) or hexadecimal number system (0x) using prefixes indicated 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 consist of 0 or more characters.

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

Data types help build a classification of data in programming languages. For example, a number and a character string are different types of data that JavaScript will treat differently.

This is important because each data type can take on specific values ​​and perform specific actions. To be able to perform operations on variables in JavaScript, it is important to understand the data type of each given variable.

This tutorial will introduce you to JavaScript data types.

Note: The information in this guide is not exhaustive, but it will give you an overview of the basic JavaScript options.

Dynamic typing

JavaScript is a dynamic language. This means that data type checking is done at run time, not at compile time.

In dynamic languages, variables of the same name can be used to store different types data.

For example, the variable t, defined by the var keyword, can store different types of data; it can also be initialized but left undefined:

var t = 16; // t is a number
var t = "Teresa"; // t is a string
var t = true; // t is a Boolean
var t; // t is undefined

All t variables contain different JavaScript data types. In JavaScript, you don't have to explicitly specify the data type of a variable before using it.

Numbers

JavaScript has a single numeric data type, not distinguishing between integers and floating point numbers. Therefore, numbers in JavaScript can be written with or without decimal places:

var num1 = 93;
var num2 = 93.00;

In the example above, both variables contain numbers, whether there is a comma in it or not.

Scientific notation in JavaScript allows you to abbreviate very large or small numbers:

var num3 = 987e8; // 98700000000
var num4 = 987e-8; // 0.00000987

In JavaScript, numbers are considered precise to 15 digits. This means that after reaching the 16th digit the numbers will be rounded:

var num5 = 999999999999999; // remains as 999999999999999
var num6 = 9999999999999999; // rounded up to 10000000000000000

Also, numbers in JavaScript have three symbolic meanings:

Infinity - numeric value, which is a positive number approaching infinity.

Infinity is a numeric value that represents a negative number approaching infinity.

NaN – Not-a-Number, a special state of a floating point number.

Infinity and -Infinity are returned when counting a number beyond the maximum possible number available in JavaScript. They also appear when counting undefined values, such as dividing by zero:

var num7 = 5 / 0; //Infinity
var num8 = -5 / 0; // -Infinity

Technically, Infinity is returned if the number is greater than 1.797693134862315E+308, which is the upper limit in JavaScript.

Likewise, -Infinity will be displayed when the number goes beyond the lower limit, -1.797693134862316E+308.

The Infinity number can also be used in loops:

while (num9 != Infinity) (
// Code here will execute through num9 = Infinity
}

For undefined numbers, NaN is printed. If you try to perform a mathematical operation on a number and a non-numeric value, you will get NaN. For example:

var x = 20 / "Shark"; // x will be NaN

Since 20 cannot be divided by the Shark string, the value of x will be NaN.

However, if the string can be evaluated as a numeric value, JavaScript will evaluate the mathematical expression:

var y = 20 / "5"; // y will be 4

Since JavaScript can treat 5 as a numeric value, 5 will work with the mathematical division operator.

If one variable in an expression is set to NaN, the result will be NaN, even if the second operand is a number.

var a = NaN;
var b = 37;
var c = a + b; // c will be NaN

So, in JavaScript there is only one numeric data type. In JavaScript, there is no need to separate numbers into integers and floating point numbers because JavaScript is a dynamic language.

Strings

A string is a sequence of one or more characters (letters, numbers, and other symbols). Strings represent text data.

In JavaScript, strings come in both single and double quotes. To create a string, you need to enclose a sequence of characters in quotes:

var singleQuotes = "This is a string in single quotes.";
var doubleQuotes = "This is a string in double quotes.";

You can use single or double quotes, but you must use one type of quote consistently within the same code.

Program "Hello, World!" demonstrates how strings are used in computer programming. Essentially, in in this example a string is a sequence of characters that makes up the phrase “Hello, World!” in alert().





function helloFunction() (
alert("Hello, World!");
}



Click me



By running the code and clicking the Click me button, you will see a pop-up window with the text:

Like other data types, strings can be stored in variables.

var hw = "Hello, World!";

You can then display the string by calling the variable:

...

var hw = "Hello, World!";
function helloFunction() (
alert(hw);
}

...
Hello, World!

Strings allow information to be passed to the user and back to the program.

Boolean data type

A Boolean (or Boolean) data type consists of two values ​​– true and false.

This type is used to represent truth values ​​associated with logic and algorithms in computer science.

Note: This data type is named after the mathematician George Boole.

Many operations in mathematics produce results that can be evaluated as true or false:

More than:

  • 500 > 100 true
  • 1 > 5 false

Less than:

  • 200 < 400 true
  • 4 < 2 false
  • 5 = 5 true
  • 500 = 400 false

Like other types, the Boolean data type can be stored in variables.

var myBool = 5 > 8; // false

Since 5 is not greater than 8, myBool will be false.

As you code in JavaScript, you'll become familiar with how boolean data works and how various truth-evaluating functions and operations can change the flow of a program.

Arrays

An array can contain multiple values ​​within a single variable. This means you can store a list of values ​​inside an array and iterate through them.

Each value within the array is called an element. You can access the elements of an array using an index.

Arrays are defined by square brackets.

The string array looks like this:

var fish = ["shark", "cuttlefish", "clownfish", "eel"];

By calling the fish variable, you will get the result:

["shark", "cuttlefish", "clownfish", "eel"]

Arrays are a very flexible data type because they are mutable: you can add, remove, and change the values ​​of elements.

Objects

An object in JavaScript consists of key:value pairs.

Object syntax consists of key:value pairs. An object is separated by curly braces on both sides (()).

Pairs in the object are separated by spaces:

var sammy = (firstName:"Wally", lastName:"Shark", color:"blue", location:"ocean");

An object can also be written on multiple lines (this is especially true for large objects).

var wally = (
firstName: "Wally",
lastName: "Shark",
color: "blue",
location: "Ocean"
};

Working with Multiple Data Types

Every program you create will likely contain multiple data types, but operations are typically performed on a single data type. math is applied to numbers, and slicing is applied to strings.

By using operators that work with all types of data (for example, the + operator can add numbers or perform string concatenation), you can get unexpected results.

If you create a variable for concatenation, JavaScript will interpret each element as a string.

var o = "Ocean" + 5 + 3;

By calling variable o, you will get the following result:

However, if the string contains numbers first and then a string, the + operator will perform addition and then concatenation:

var p = 5 + 3 + "Ocean";
8Ocean

Because the results are unpredictable, it is more convenient to perform operations and methods in a single data type. However, JavaScript does not return errors when mixing data types, as some other programming languages ​​do.

Conclusion

You are now familiar with JavaScript data types. Each of the types listed here is important when writing JavaScript programs.

Tags: A variable is an identifier that has been assigned a value. A variable can be accessed in a program, thus working with the value assigned to it.

A JavaScript variable itself does not contain information about the type of values ​​that will be stored in it. This means that by writing, for example, a string to a variable, you can later write a number to it. Such an operation will not cause an error in the program. This is why JavaScript is sometimes called an "untyped" language.

Before a variable can be used, it must be declared using the var or let keyword. If we are talking about a constant, the keyword const is used. You can declare a variable and assign a value to it without using these keywords, but it is not recommended to do so.

Keyword var Before the ES2015 standard, the use of the var keyword was the only way variable declarations.

Var a = 0
If you omit var in this construct, the value will be assigned to an undeclared variable. The result of this operation depends on the mode in which the program is executed.

So, if the so-called strict mode is enabled, this will cause an error. If strict mode is not enabled, the variable will be implicitly declared and assigned to the global object. In particular, this means that a variable declared implicitly in a function in this way will remain available after the function has completed. Typically, it is expected that variables declared in functions do not “go beyond” their scope. It looks like this:

Function notVar() ( bNotVar = 1 //better not to do this) notVar() console.log(bNotVar)
1 will appear in the console, no one usually expects such behavior from a program, the expression bNotVar = 1 does not look like an attempt to declare and initialize a variable, but like an attempt to access a variable located in a scope external to the function (this is quite normal). As a result, implicit variable declarations are confusing to those reading the code and can lead to unexpected program behavior. Later we will talk about both functions and scopes, but for now try to always use specialized keywords when the meaning of an expression is to declare a variable. If in this example the function body is rewritten as var bNotVar = 1, then trying to run the above code fragment will result in an error message (you can see it in the browser console).

For example, it might look like this: Uncaught ReferenceError: bNotVar is not defined . Its meaning boils down to the fact that the program cannot work with a non-existent variable. It is much better to see such an error message when you first start a program than to write incomprehensible code that can behave unexpectedly.

If, when declaring a variable, it is not initialized or assigned any value, it will automatically be assigned the value undefined.

Var a //typeof a === "undefined"
Variables declared with the var keyword can be declared again many times, assigning new values ​​to them (but this can be confusing for the person reading the code).

Var a = 1 var a = 2
You can declare multiple variables in one expression:

Var a = 1, b = 2
The scope of a variable is the area of ​​the program in which this variable is accessible (visible).

A variable initialized with the var keyword outside of a function is assigned to a global object. It has global scope and is accessible from anywhere in the program. If a variable is declared using the var keyword inside a function, then it is visible only within that function, being a local variable for it.

If a function using var declares a variable whose name is the same as a variable in the global scope, it will “override” the global variable. That is, when accessing such a variable inside a function, its local version will be used.

It is important to understand that blocks (areas of code enclosed in curly braces) do not create new scopes. New area visibility is created when the function is called. The var keyword has what is called functional scope rather than block scope.

If a variable is declared in the function code, it is visible to the entire function code. Even if a variable is declared using var at the end of the function code, it can be accessed at the beginning of the code, since JavaScript has a variable hoisting mechanism. This mechanism "lifts" variable declarations, but not their initialization operations. This can be a source of confusion, so make it a habit to declare variables at the beginning of your function.

▍The let keyword The let keyword was introduced in ES2015 and, in a simplistic way, can be called the “block” version of var . Variables declared with the let keyword are scoped to the block, statement, or expression in which it is declared, and to nested blocks.

If the word “let” itself does not seem very clear, you can imagine using the word “let” instead. Then the expression let color = "red" can be translated into English as follows: “let the color be red”, and into Russian as follows: “let the color be red”.

By using the let keyword, you can avoid the ambiguities that come with the var keyword (for example, you won't be able to declare the same variable twice using let ). Using let outside of a function, say when initializing loops, does not create global variables.

For example, this code will generate an error:

For (let i = 0; i< 5; i++) { console.log(i) } console.log(i)
If, when the loop is initialized, the counter i is declared using the var keyword, then i will be available outside the loop after it completes its work.

These days, when developing JS programs based on modern standards, it is quite possible to completely abandon var and use only the let and const keywords.

▍The const keyword The values ​​of variables declared using the var or let keywords can be overwritten. If const is used instead of these keywords, then a constant declared and initialized with its help cannot be assigned a new value.

Const a = "test"
In this example, the constant a cannot be assigned a new value. But it should be noted that if a is not a primitive value like a number, but an object, using the const keyword does not protect this object from changes.

When they say that an object is stored in a variable, what they really mean is that the variable stores a reference to the object. This link cannot be changed, but the object itself to which the link leads can be changed.

The const keyword does not make objects immutable. It simply protects references to them written in the corresponding constants from changes. This is what it looks like:

Const obj = () console.log(obj.a) obj.a = 1 //works console.log(obj.a) //obj = 5 //causes an error
During initialization, a new empty object is written to the obj constant. An attempt to access its property a, which does not exist, does not cause an error. The console gets undefined . After that, we add a new property to the object and try to access it again. This time the value of this property is 1 in the console. If you uncomment the last line of the example, attempting to execute this code will result in an error.

The const keyword is very similar to let , in particular, it has block scope.

In modern conditions, it is quite acceptable to use the const keyword to declare all entities whose values ​​​​are not planned to be changed, resorting to let only in special cases. Why? The whole point is that it is best to strive to use the simplest possible constructions available in order not to complicate the program and avoid errors.

JavaScript data types are sometimes called an "untyped" language, but this is not the case. It’s true that you can write values ​​of different types into variables, but there are still data types in JavaScript. In particular, we are talking about primitive and object data types.

To determine the data type of a value, you can use the typeof operator. It returns a string indicating the type of the operand.

▍Primitive Data Types Here is a list of JavaScript primitive data types:
  • number
  • string
  • boolean (boolean value)
  • null (special value null)
  • undefined (special value undefined)
  • symbol (symbol, used in special cases, introduced in ES6)
Here the names of the data types are given as they are returned by the typeof operator.

Let's talk about the most commonly used data types from this list.

The number type Values ​​of type number in JavaScript are represented as 64-bit double-precision floating point numbers.

In the code, numeric literals are represented as integers and fractions in the decimal number system. You can use other methods to write numbers. For example, if there is a prefix 0x at the beginning of a numeric literal, it is perceived as a number written in hexadecimal notation. Numbers can also be written in exponential notation (the letter e can be found in such numbers).

Here are examples of writing integers:

10 5354576767321 0xCC // hexadecimal number
Here are the fractions.

3.14 .1234 5.2e4 //5.2 * 10^4
Numeric literals (this behavior is also typical for some other primitive types), when you try to access them as objects, are automatically, for the duration of the operation, converted into the corresponding objects, which are called “object wrappers”. In this case we are talking about the Number object wrapper.

Here, for example, is what an attempt to access the variable a, which contains a numeric literal, looks like as an object in the Google Chrome console.

Number object wrapper hint

If, for example, you use the toString() method of an object of type Number, it will return a string representation of the number. The corresponding command looks like this, which can be executed in the browser console (and in regular code) like this:

A.toString()
Note the double parentheses after the method name. If you do not supply them, the system will not generate an error, but instead of the expected output, you will see something in the console that is not at all similar to the string representation of the number 5.

The global Number object can be used as a constructor, creating new numbers with its help (however, it is almost never used in this form), it can also be used as an independent entity, without creating its instances (that is, certain numbers represented with its help). For example, its Number.MAX_VALUE property contains the maximum numeric value representable in JavaScript.

Type string Values ​​of type string are sequences of characters. Such values ​​are specified as string literals enclosed in single or double quotes.

"A string" "Another string"
String values ​​can be split into multiple parts using the backslash character.

"A\string"
The line may contain so-called escape sequences, which are interpreted when the line is output to the console. For example, the sequence \n means a newline character. The backslash character can also be used to add quotation marks to strings enclosed within the same quotation marks. Escaping the quote character with \ causes the system to not treat it as a special character.

"I'm a developer"
Strings can be concatenated using the + operator.

"A" + "string"

Template literals In ES2015, so-called template literals, or template strings, appeared. They are strings enclosed in backquotes (`) and have some interesting properties.

`a string`
For example, you can substitute certain values ​​that are the result of evaluating JavaScript expressions into template literals.

`a string with $(something)` `a string with $(something+somethingElse)` `a string with $(obj.something())`
Using backquotes makes it easier to write string literals on multiple lines:

`a string with $(something)`

The boolean type JavaScript has a pair of reserved words used when working with boolean values: true and false. Comparison operators, such as == , === ,< , >, return true or false .

Boolean expressions are used in statements like if and while to help control the flow of a program.

It should be noted that where the value true or false is expected, you can use other values ​​that are automatically evaluated by the language as true (truth) or false (falsy).

Specifically, the following are false values:

0 -0 NaN undefined null "" //empty string
The remaining values ​​are true.

The null Type JavaScript has a special value, null , which indicates the absence of a value. Similar values ​​are used in other languages. Type undefined The value undefined written to a certain variable indicates that this variable is not initialized and there is no value for it.

This value is automatically returned from functions whose results are not explicitly returned using the return keyword. If a function takes a parameter that is not specified when it is called, it is also set to undefined .

In order to check a value for undefined , you can use the following construction.

Typeof variable === "undefined"

▍Objects All non-primitive values ​​are of object type. We're talking about functions, arrays, what we call "objects", and many other entities. All these data types are based on the object type, and although they differ from each other in many ways, they also have a lot in common. Expressions Expressions are pieces of code that can be processed and obtained a certain value based on the calculations performed. There are several categories of expressions in JavaScript. Arithmetic Expressions This category includes expressions that evaluate to numbers.

1 / 2 i++ i -= 2 i * 2

String Expressions The result of evaluating such expressions is strings.

"A " + "string" "A " += "string"

Primary expressions Literals, constants, and references to identifiers fall into this category.

2 0.02 "something" true false this //execution context, reference to the current object undefined i //where i is a variable or constant
This also includes some JavaScript keywords and constructs.

Function class function* //yield generator //command to pause/resume the generator yield* //delegation to another iterator or generator async function* //asynchronous functional expression await //organization of waiting for the execution of an asynchronous function /pattern/i // regular expression() //grouping

Initialization expressions for arrays and objects //array literal () //object literal (a: 1, b: 2) (a: (b: 1)) Logical expressions Logical expressions use logical operators, the result of their calculation is logical values.

A && b a || b!a

Property Access Expressions These expressions allow you to access properties and methods of objects.

Object.property //calling a property (or method) of an object object object["property"]

Object creation expressions new object() new a(1) new MyRectangle("name", 2, (a: 4)) Function declaration expressions function() () function(a, b) ( return a * b ) (a, b) => a * b a => a * 2 () => ( return 2 ) Calling Expressions Such expressions are used to call functions or methods of objects.

A.x(2) window.resize()

Working with objects We have already encountered objects above, talking about object literals, calling their methods, and accessing their properties. Here we'll talk about objects in more detail, in particular, we'll look at the mechanism of prototypical inheritance and the use of the class keyword.▍Prototypical inheritance JavaScript stands out among modern programming languages ​​in that it supports prototypical inheritance. Most object-oriented languages ​​use a class-based inheritance model.

Every JavaScript object has a special property (__proto__) that points to another object that is its prototype. An object inherits the properties and methods of the prototype.

Let's say we have an object created using an object literal.

Const car = ()
Or we created an object using the Object constructor.

Const car = new Object()
In any of these cases, the prototype of the car object will be Object.prototype .

If you create an array that is also an object, its prototype will be the Array.prototype object.

Const list = //or so const list = new Array()
You can check this as follows.

Car.__proto__ == Object.prototype //true car.__proto__ == new Object().__proto__ //true list.__proto__ == Object.prototype //false list.__proto__ == Array.prototype //true list.__proto__ == new Array().__proto__ //true
Here we used the __proto__ property; it does not have to be available to the developer, but it can usually be accessed. It should be noted that more in a reliable way to get the prototype of an object is to use the getPrototypeOf() method global Object.

Object.getPrototypeOf(new Object())
All properties and methods of a prototype are available to the object that has that prototype. Here, for example, is what their list looks like for an array.


Array hint

The base prototype for all objects is Object.prototype.

Array.prototype.__proto__ == Object.prototype
Object.prototype does not have a prototype.

What we saw above is an example of a prototype chain.

When you try to access a property or method of an object, if the object itself does not have such a property or method, their search is performed in its prototype, then in the prototype's prototype, and so on until the desired property is found, or until the chain of prototypes will not end.

In addition to creating objects using the new operator and using object or array literals, you can create an instance of an object using the Object.create() method. The first argument passed to this method is an object that will be the prototype of the object it creates.

Const car = Object.create(Object.prototype)
You can check whether an object is part of the prototype chain of another object using the isPrototypeOf() method.

Const list = Array.prototype.isPrototypeOf(list)

Constructor functions Above, we created new objects using the constructor functions already available in the language (the keyword new is used when calling them). You can create such functions yourself. Let's look at an example.

Function Person(name) ( this.name = name ) Person.prototype.hello = function() ( console.log(this.name) ) let person = new Person("Flavio") person.hello() console.log( Person.prototype.isPrototypeOf(person))
Here we create a constructor function. When called, it is created new object, which is indicated by the key the word this in the body of the constructor. We add a name property to this object and write to it what was passed to the constructor. This object is returned from the constructor automatically. Using the constructor function, you can create many objects whose name properties will contain what was passed to the constructor when they were created.

After creating the constructor, we add a function to its prototype that will print to the console the value of the name property of the object created using this function. All objects created using this constructor will have the same prototype, and therefore use the same hello() function. This can be easily checked by creating another object of type Person and comparing its hello() function with the function of the object already existing in the example (in this case, the function name is written without parentheses).

▍Classes In the ES6 standard, JavaScript introduced the concept of a “class”.

Previously, JavaScript could only use the above-described prototypic inheritance mechanism. This mechanism looked unusual for programmers who came to JS from other languages. Therefore, classes appeared in the language, which, in essence, are “syntactic sugar” for the prototype inheritance mechanism. That is, objects created traditional way, and objects created using classes have prototypes.

Class Declaration This is what a class declaration looks like.

Class Person ( constructor(name) ( this.name = name ) hello() ( return "Hello, I am " + this.name + "." ) )
A class has an identifier that can be used to create new objects using the new ClassIdentifier() construct.

When a new object is created, the constructor method is called and parameters are passed to it.

You can declare methods in a class. In our case, hello() is a method that can be called by all objects created based on the class. This is what creating a new object using the Person class looks like.

Const flavio = new Person("Flavio") flavio.hello()

Class-Based Inheritance Classes can extend other classes. Objects created from such classes will inherit both the methods of the original class and the methods specified in the extended class.

If a class that extends another class (a subclass of that class) has a method whose name is the same as that of the parent class, that method takes precedence over the original one.

Class Programmer extends Person ( hello() ( return super.hello() + " I am a programmer." ) ) const flavio = new Programmer("Flavio") flavio.hello()
Calling the hello() method in the example above will return the string Hello, I am Flavio. I am a programmer.

Classes do not provide for the presence of variables (properties); the properties of objects created using classes must be configured in the constructor.

Within a class, you can access the parent class using the super keyword.

Static methods Methods described in a class can be called by accessing objects created from the class, but not by accessing the class itself. Static methods can be called by accessing the class directly. Private Methods JavaScript does not have a built-in mechanism that allows you to declare private methods. This limitation can be overcome, for example, by using closures. Getters and setters You can define methods in a class by prefixing them with the get or set keywords. This allows you to create so-called getters and setters - functions that are used to control access to the properties of objects created based on the class. The getter is called when you try to read the value of a pseudo-property, and the setter is called when you try to write a new value to it.

Class Person ( constructor(name) ( this.userName = name ) set name(value) ( ​​this.userName = value ) get name() ( return this.userName ) )

Summary In this material we talked about variables, data types, expressions and working with objects in JavaScript. The topic of our next material will be functions.

Dear readers! If you have been writing in JS for a long time, please tell us how you feel about the appearance of the class keyword in the language.

In this tutorial we will introduce a very important concept - JavaScript data types. We recommend that you pay close attention to this concept - if you do not understand it from the very beginning, then you will often have to deal with strange behavior of the program you created.

Dynamic typing

In progress computer programs manipulate different values, each of which can be processed in a programming language and belongs to a specific data type.

In JavaScript, data types can be divided into two categories: simple (also called primitive) types and composite (also called reference or object).

JavaScript is a weakly typed or dynamic programming language that allows data types to be defined, parsed, and compiled on the fly during program execution. This means that you don't have to define the type of the variable in advance. The type will be determined automatically during program execution.
Thus, in different parts of the program, the same variable can take on values ​​of different types:

Data types

The ECMAScript® standard defines the following data types:

  • Simple (also called primitive) types:
    • Boolean - can take two possible values, sometimes called true and false;
    • null – the value null represents a reference that points, usually intentionally, to a non-existent or incorrect object or address;
    • undefined – denotes a predefined global variable initialized with an undefined value;
    • numeric (English Number) – numeric data type in the format of a 64-bit double precision floating point number;
    • string (English String) – is a sequence of characters used to represent text;
    • symbol (eng. Symbol) is a data type, instances of which are unique and immutable. (new in ECMAScript 6).
  • An object is a collection of named values, usually called properties of an object.
Difference between primitive and composite types

Before we look at each data type, let's first become familiar with the typeof operator. The typeof operator returns a string describing the data type of a variable.
Let's demonstrate how it works using the following example:

The example script declares variables, initializes them (assigns values), and then prints the type of each variable.

The difference between primitive and composite data types occurs when their values ​​are copied.

When a variable is assigned a value of a simple type, the value itself (for example, a number) is written to the variable. When we assign a variable of a simple type to another, it copies the value. As a result, each variable will have its own value and changes in one of the variables will not affect the value of the other variable in any way:

When we assign a value of a composite (reference) type to a variable, a reference to the value (a reference to an object) is written to the variable. When we assign one variable (whose value contains a reference to a composite value) to another variable, the reference to the composite value is copied. As a result, both variables refer to the same composite value, and changes in the value of one variable will affect the other variable:

Primitive types

All data types in JavaScript, except objects, are immutable or immutable. This means that their values ​​cannot be modified, but only overwritten with a new, different value. For example, strings cannot be adjusted character by character - they can only be rewritten completely. Values ​​of such types are called "primitive".

The simplest data that a program can operate with are called literals. Literals are numbers or strings that are used to represent values ​​in JavaScript. The information provided can be very diverse, and therefore the meanings vary various types. The simplest data types in JavaScript are called basic data types: numbers, strings, and booleans. All of them are classified as "primitive".

Boolean (logical) type “boolean”

Logical, or Boolean values ​​(after the name of their inventor - Boolean), can have only one of two values: true (true) or false (false). Values ​​true or false usually appear in comparison or logical operations.

The following program creates a Boolean variable and then tests its value using an if/else statement:

Any expression can be used as a comparative expression. Any expression that returns 0, null, undefined, or the empty string is interpreted as false . An expression that specifies any other value is interpreted as true .

Note: When writing Boolean values, they are not enclosed in quotes: var myVar = true;
At the same time, declaring var myVar = "true" creates a string variable.

Number data type

In JavaScript, there is no distinction between an integer and a floating point number—essentially, JavaScript represents all numbers as a floating point value.

JavaScript uses a 64-bit format defined by the IEEE-754 standard to represent numbers. This format is capable of representing numbers in the range of ±1.7976931348623157 × 10308 to ±5 × 10 -324.

A number found directly in the program code is called a numeric literal. In addition to decimal integer literals, JavaScript recognizes hexadecimal values.
Hexadecimal numbers can include any sequence of numbers from 0 to 9 and letters from a to f, which must begin with the character sequence "0x".

Var a = 255; var b = 0xFF; // Number 255 in hexadecimal notation

Additionally, JavaScript contains special numeric values:

  • NaN (not a number or calculation error). Is the result of an incorrect mathematical operation on invalid data, such as strings or an undefined value.
  • Infinity (positive infinity). Used when a positive number is too large to be represented in JavaScript.
  • -Infinity (negative infinity). Used when a negative number is too large to be represented in JavaScript.
  • ±0 (positive and negative 0). JavaScript distinguishes between positive and negative zero.
String data type

A string type is an immutable, ordered sequence of 16-bit values, each of which represents a Unicode character (letters, numbers, punctuation, special characters, and spaces). Lines can be empty or consist of one or more characters. Strings are created using double (") or single (") quotes. A string delimited by a pair of single quotes can use double quotes, and conversely, single quotes can be used within a string enclosed by a pair of double quotes:

In JavaScript, there is no difference between double and single quotes, but the quotes at the beginning and end of a string should not be different. For example, an expression like this would cause a syntax error:

var firstName = "Max"; //syntax error - different quotes

Note: JavaScript does not have a special single-character data type like char in C, C++, and Java. A single character is represented by a string of unit length.

Null data type The null type contains a single special value—null.

The null keyword cannot be used as a function or variable name. The value null is a reference to an "empty" object and has a special purpose - it is usually used to initialize a variable that will later be assigned a value.

The typeof operator for a null value returns the string "object", indicating that the null value is a special "empty" object.

Undefined data type

An undefined type forms its own type, which contains a single special value - undefined. This is the value of a variable declared using the var operator, but not initialized:

The value undefined is returned when accessing a variable that has never been assigned a value, a non-existent object property, or an array element.

It should be noted that a variable with the value undefined is different from a variable that is not defined at all:

In this example, the alert() method displays the value of the age variable, which is undefined. In the second case, an undeclared car variable is passed to the alert() method, which leads to an error.

The following example may be somewhat confusing for novice programmers, because... The typeof operator returns undefined for both an uninitialized and an undeclared variable:

In the above example, the variable age is declared, but nothing is written to it, so its value is just undefined . The car variable is not declared - in fact, it does not exist. However, typeof returns the string undefined in both cases. This makes some sense, of course, because it is impossible to perform any operations with any of these variables, although technically they are completely different.

Note: It is recommended to always initialize a declared variable. In this case, you will know that the typeof operator returns undefined because the variable was not declared, not because it was not initialized.

The value undefined is derived from null , so in ECMA-262 the == equivalence operator treats them as equal:

Although null and undefined are related, they are used differently. You should not explicitly assign the value undefined to a variable, but this does not apply to null. In case the required object is not available, null should be used instead. This indicates that null was introduced as a pointer to an empty object, and emphasizes its difference from undefined .

To distinguish between null and undefined in a program, you can use the identity operator === :

Data type Symbol

A symbol is a new addition to JavaScript since ECMAScript version 6. A symbol is a unique, immutable, primitive value that is used to create unique identifiers.

To create a symbol you need to call the Symbol function:

var mySymbol = Symbol();

To define a symbol, you can use the typeof operator; if the value is a symbol, the string symbol will be returned:

The Symbol function has an optional parameter - a string that serves to describe the symbol:

The property name is a string, so objects can be considered to associate strings with values. Together, these pieces of information form key-value pairs.

IN JavaScript objects can be created using one of two syntaxes:

1. var obj = (); // using object literal 2. var obj = new Object(); // using a method called constructor

Creating an object using an object literal begins with defining a regular variable. The right side of this statement writes an object literal - this is a comma-separated list of pairs enclosed in curly braces (). "name-value", enclosed in curly braces. The property name and value are separated by a colon:

var cat = ( "legs": 4, "name": "Murzik", "color": "Red" )

The second way to create objects is using the Object() constructor. In this case, the new Object() expression is first used, and then the properties of the resulting object are defined and initialized:

  • When we assign one variable (whose value contains a reference to a composite value) to another variable, the reference to the composite value is copied. As a result, both variables refer to the same composite value, and changes in the value of one variable will affect the other variable.
  • Any expression that returns 0, null, undefined, or the empty string is interpreted as false .
  • Strings are created using double (") or single (") quotes. A string delimited by a pair of single quotes can use double quotes, and vice versa, single quotes can be used in a string enclosed by a pair of double quotes.
  • The value null is a reference to an "empty" object and has a special purpose - it is usually used to initialize a variable that will later be assigned a value.
  • The value (undefined) is a variable declared using the var operator, but not initialized.
  • In JavaScript, objects can be created in one of two ways:
    • using an object literal
    • using a method called constructor
  • An object contains an unordered collection of properties, each of which contains a name and a value. You can add new named values ​​to an object at any time or remove existing ones.