Internet Windows Android

JavaScript. Data types and operators

There are syntax rules for creating variable names in JavaScript:

  • The following symbols are used for variable names: a-z, A-Z, numbers, $, underscore (_).
  • Variable names cannot start with a digit.
  • JavaScript is case sensitive, so keep this in mind when programming. itcounter and it C ounters are different variables.
  • JavaScript has no limitation on the length of a variable name.

Examples of valid variable names:

  • itcounter
  • $ _itcounter
  • it_counter

Wrong variable names:

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

Variables are declared with the var command.

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

String variables

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

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

Into the string created single quote, you can include a double quote and vice versa.

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

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


"); document.write ($ stroka_2);

Variable values ​​can be assigned to other variables:

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

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

Concatenating strings

It is very common to concatenate multiple lines into one. For example, our last example is too cumbersome.

Concatenation (concatenation) of strings in JavaScript is done using the sign + .

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

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

Concatenation operator + can also be used in variables:

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

Numeric Variables

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

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

Now another example:

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

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

Boolean variables

There is such a type of variables - boolean. It's simple, there are only two values: true and false, that is, true and false.

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

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

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

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

This is a strange recording, I know. But the variable $ count will be 2. In math context, true = 1 and false = 0.

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

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

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

Simple variable types

In JavaScript, variables are classified into several types. We have already covered the string, numeric and boolean (logical) types. Here's a broader list of simple types:

  • string is a string variable.
  • number is a numeric variable.
  • boolean is a boolean variable.
  • null is the special value "nothing".
  • undefined - type "value not assigned".

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

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

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

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

The syntax for the typeof statement might be:

  • typeof $ count
  • typeof ($ count)

So, run the code from the last example and see the result. The null variable type will be object. This is a bug in the language, and it will probably never be fixed due to the need to maintain compatibility of already written JavaScript scripts with new versions of the language.

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

String, Number, Boolean, Array, Object.

JavaScript data types

JavaScript variables can contain many data types: numbers, strings, arrays, objects and much more:

var length = 16; // Number
var lastName = "Johnson"; // String
var cars = ["Saab", "Volvo", "BMW"]; // Array
var x = (firstName: "John", lastName: "Doe"); // Object

Data type concept

In programming, data types are an important concept.

In order to be able to work with variables, it is important to know something about the type.

Without data types, the computer cannot safely solve this problem:

Var x = 16 + "Volvo";

Does it make sense to add "Volvo" to sixteen? Will it throw an error or will it produce a result?

JavaScript would treat the above example as:

Var x = "16" + "Volvo";

When adding a number and a string, JavaScript will treat the number as a string.

JavaScript evaluates expressions from left to right. Different sequences can lead to different results:

In the first example, JavaScript treats 16 and 4 as numbers until it reaches "Volvo".

In the second example, since the first operand is a string, all operands are treated as strings.

JavaScript has dynamic types

JavaScript has dynamic types. This means that the same variable can be used as different types:

example

var x; // Now x is undefined
var x = 5; // Now x is a Number
var x = "John"; // Now x is a String

JavaScript Strings

A string (or text string) is a series of characters, like "John Doe".

The lines are written in quotation marks. You can use single or double quotes:

example

var carName = "Volvo XC60"; // Using double quotes
var carName = "Volvo XC60"; // Using single quotes

You can use quotation marks inside a string, as long as they don't match quotation marks around the string:

example

var answer = "It" s alright "; // Single quote inside double quotes
var answer = "He is called" Johnny ""; // Single quotes inside double quotes
var answer = "He is called" Johnny ""; // Double quotes inside single quotes

Try it yourself "

You will learn more about strings later in this tutorial.

JavaScript Numbers

JavaScript only has one type of numbers.

Numbers can be written, or without decimal places:

example

var x1 = 34.00; // Written with decimals
var x2 = 34; // Written without decimals

Very large or extra small numbers can be written with scientific (exponential) notation:

You will learn more about numbers later in this guide.

JavaScript Booleans

Boolean can have only two values: true or false.

example

var x = true;
var y = false;

Booleans are often used in conditional testing.

You will learn more about conditional testing later in this tutorial.

JavaScript arrays

JavaScript arrays are written using square brackets.

array elements are separated by commas.

The following code declares (creates) an array called cars, containing three items (car names):

Array indices start at zero, which means the first element, the second, and so on.

You will learn more about arrays later in this tutorial.

JavaScript objects

JavaScript objects are enclosed in curly braces.

Object properties are written as name: value pairs, separated by commas.

The object (person) in the above example has 4 properties: firstName, lastName, age and eyeColor.

You will learn more about objects later in this tutorial.

TypeOf Operator

You can use JavaScript code typeof operator to find the type of a JavaScript variable:

example

typeof "John" // Returns string
typeof 3.14 // Returns number
typeof false // Returns boolean
typeof // Returns object
typeof (name: "John", age: 34) // Returns object

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

By itself, a JavaScript variable does not contain information about the type of values ​​that will be stored in it. This means that by writing to a variable, for example, a string, 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 "untyped" language.

Before using a variable, it must be declared using keyword var or let. When it comes to a constant, the const keyword is used. You can declare a variable and assign a value to it without using these keywords, but this is not recommended.

▍The var keyword

Prior to ES2015, using the var keyword was the only way to declare variables.

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

So, if 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 that is implicitly declared in this way in a function will be available after the function completes its work. Usually, it is expected that the variables declared in the functions do not "go" out of their limits. It looks like this:

Function notVar () (bNotVar = 1 // better not to do this) notVar () console.log (bNotVar)
The console will get 1, no one usually expects such behavior from the program, the expression bNotVar = 1 looks not like an attempt to declare and initialize a variable, but as an attempt to access a variable that is outside the scope of the function (this is quite normal). As a result, implicit variable declarations are confusing to the reader and can lead to unexpected program behavior. We'll talk about functions and scopes later, but for now try to use specialized keywords whenever the meaning of an expression is to declare a variable. If in this example the body of the function is rewritten as var bNotVar = 1, then an attempt to run the above code snippet will result in an error message (you can see it in the browser console).

For example, it may 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 the first time you run 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 re-declared many times, assigning new values ​​to them (but this can be confusing to the reader).

Var a = 1 var a = 2
Several variables can be declared in one expression:

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

A variable initialized with the var keyword outside of a function is assigned to the global object. It has a 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 inside this function, being a local variable for it.

If a variable is declared in a function using var, the name of which coincides with the name of a variable from the global scope, it will "overlap" the global variable. That is, when accessing such a variable within 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. A new scope is created when the function is called. The var keyword has what's called functional scope, not 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, you can refer to it at the beginning of the code as well, since JavaScript uses the hoisting mechanism. This mechanism "hoists" variable declarations, but not their initialization operations. This can be a source of confusion, so make it a rule to declare variables at the beginning of your function.

▍The let keyword

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

If the word "let" itself seems confusing, you can imagine using the word "let" instead. Then the expression let color = "red" can be translated into English like this: "let the color be red", and into Russian - like this: "let the color be red".

By using the let keyword, you can get rid of the ambiguities associated with the var keyword (for example, you cannot declare the same variable twice using let). Using let outside of a function, say when initializing loops, does not create global variables.

For example, code like this will throw an error:

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

Nowadays, 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

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 that object from changes.

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

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

Const obj = () console.log (obj.a) obj.a = 1 // running console.log (obj.a) // obj = 5 // raises an error
During initialization, a new empty object is written to the constant obj. An attempt to access its non-existent property a 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 sent to the console - 1. If you uncomment the last line of the example, then an attempt to execute this code will result in an error.

The const keyword is very similar to let, in particular, it is block-scoped.

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 point is that it is best to strive to use the simplest available constructs in order not to complicate programs and avoid mistakes.

Data types

JavaScript is sometimes referred to as "untyped" language, but this is not the case. It is true that you can write values ​​of different types to variables, but there are data types in JavaScript, after all. In particular, we are talking about primitive and object data types.

In order 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 primitive types JavaScript data:
  • number (number)
  • string (string)
  • boolean (boolean value)
  • null (the special value null)
  • undefined (special value undefined)
  • symbol (symbol, used in special cases, introduced in ES6)
Here, the names of the data types are shown in the form in which they are returned by the typeof operator.

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

Number type

JavaScript number values ​​are represented as 64-bit double-precision floating-point numbers.

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

Here are examples of writing integers:

10 5354576767321 0xCC // hexadecimal number
Here are the fractional numbers.

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

For example, here is how an attempt to access the variable a, in which a numeric literal is written, as an object, in the Google Chrome console looks like.

Number Object Wrap Hint

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

A.toString ()
Notice the double brackets after the method name. If they are not supplied, the system will not generate an error, but instead of the expected output, the console will display something that does not at all resemble the string representation of the number 5.

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

String type

String values ​​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 string can contain so-called escape sequences, which are interpreted when the string is printed to the console. For example, the \ n sequence means a line feed character. The backslash character can also be used to add quotation marks to strings enclosed in quotation marks. Escaping the quote character with \ causes the system to not interpret it as special character.

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

"A" + "string"

Template literals

ES2015 introduced the so-called template literals, or template strings. They are strings enclosed in backticks (`) and have some interesting properties.

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

`a string with $ (something)` `a string with $ (something + somethingElse)` `a string with $ (obj.something ())`
Using backticks makes it easier to write multi-line string literals:

`a string with $ (something)`

Boolean type

JavaScript has a couple of reserved words used when working with booleans - true and false. Comparison operations such as ==, ===,< , >, return true or false.

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

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

In particular, the following are false values:

0 -0 NaN undefined null "" // empty string
All other values ​​are true.

Null type

JavaScript has a special value, null, which indicates that there is no value. Similar meanings are used in other languages.

Undefined type

The undefined value written to a variable indicates that this variable is not initialized and there is no value for it.

This value is automatically returned from functions that do not explicitly return the result using the return keyword. If the function takes some 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 are talking about functions, arrays, what we call "objects", and many other entities. All of these data types are based on the object type, and although they differ in many ways, they also have a lot in common.

Expressions

Expressions are fragments of code that can be processed and obtained, based on the calculations performed, a certain value. There are several categories of expressions in JavaScript.

Arithmetic expressions

Expressions that evaluate to numbers fall into this category.

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, identifier references fall into this category.

2 0.02 "something" true false this // execution context, reference to the current object is 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 work of the yield generator * // delegate to another iterator or generator async function * // asynchronous functional expression await // wait for the asynchronous function execution / pattern / i // regular expression() // grouping

Array and Object Initialization Expressions

// array literal () // object literal (a: 1, b: 2) (a: (b: 1))

Boolean expressions

Boolean expressions use Boolean operators, the result of their evaluation is Boolean values.

A && b a || b! a

Property Access Expressions

These expressions allow you to access the properties and methods of objects.

Object.property // accessing the property (or method) of the 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)

Challenge expressions

Such expressions are used to call functions or methods of objects.

A.x (2) window.resize ()

Working with objects

Above, we have already encountered objects, talking about object literals, about calling their methods, about accessing their properties. Here we will talk about objects in more detail, in particular, we will look at the prototypal inheritance mechanism and the use of the class keyword.

▍ Prototypal inheritance

JavaScript stands out among modern programming languages ​​in that it supports prototypal inheritance. Most object-oriented languages ​​use a class-based inheritance model.

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

Suppose 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 either case, the prototype for car 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 usually you can refer to it. It should be noted that a more reliable way to get the prototype of an object is to use the getPrototypeOf () method of the global Object object.

Object.getPrototypeOf (new Object ())
All properties and methods of a prototype are available to an object that has this prototype. For example, here's 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 has no 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, they are searched in its prototype, then in the prototype prototype, and so on until the desired one is found, or until the prototype chain doesn't end.

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

Const car = Object.create (Object.prototype)
You can check if 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 (when calling them, the new keyword is used). 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 you call it, a new object is created, which is pointed to by the this keyword in the body of the constructor. We add a name property to this object and write what is passed to the constructor into it. This object is returned from the constructor automatically. Using a 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 is easy to check by creating another object of type Person and comparing its hello () function with the function of the object already in the example (in this case, the name of the function is written without parentheses).

▍Classes

In the ES6 standard, JavaScript came to be known as a "class".

Prior to that, JavaScript could only use the prototypal inheritance mechanism described above. This mechanism looked unusual for programmers who came to JS from other languages. Therefore, classes appeared in the language, which, in fact, are "syntactic sugar" for the prototypal inheritance mechanism. That is, both objects created using the traditional method and objects created using classes have prototypes.

Class declaration

This is what the class declaration looks like.

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

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

Methods can be declared in the class. In our case, hello () is a method that can be called by all objects created from the class. This is how it looks like creating a new object using the Person class.

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 defined in the extended class.

If a class extending another class (inheriting from this class) has a method whose name is the same as that of the parent class, this 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 above example will return the string Hello, I am Flavio. I am a programmer.

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

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

Static Methods

Methods described in a class can be called by referring to objects created on the basis of this class, but not to the class itself. Static methods can be called by referring directly to the class.

Private Methods

JavaScript does not have a built-in mechanism that allows you to declare private (private, private) methods. This limitation can be circumvented, for example, by using closures.

Getters and Setters

In a class, you can describe methods by preceding them with the keywords get or set. This allows you to create so-called getters and setters - functions that are used to control access to properties of objects created from a class. A getter is called when an attempt is made to read the value of a pseudo-property, and a setter is called when a new value is attempted to be written to it.

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

Outcomes

In this article, we talked about variables, data types, expressions, and working with objects in JavaScript. Functions will be the topic of our next article.

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.

I decided to write a series of articles called "Difficult about the simple". This series will focus on the JavaScript language. Why is "difficult about the simple"? Because everything that I will tell you I will tell taking into account the peculiarities of the interpreter's work, starting with data types. All this will be done in order to then be able to tell just about the complex, for example, about the methods of inheritance in JavaScript and other patterns.

JavaScript is an object-oriented programming language with a prototypical organization.
What does "with a prototype organization" mean, we will talk in the next article (it will definitely be), but why it is "object-oriented" and whether everything in JS is an object, we will find out today.
JS only needs 9 types to fulfill its goals. Moreover, only 6 of them are available to the program, the remaining 3 are available only at the implementation level and are used by the specification. At first glance (and this is the first misconception), everything in JS is objects. So five of the six types available to the program are so-called primitives and are not objects (below I will explain why and how they are confused with objects). These five primitives are:

- String (s = 'str')
- Number (n = 10)
- Boolean (b = true)

And as I call them "philosophical types":
- null (v = null)
- undefined (u = undefined)

Philosophical in that null means that nothing has been assigned to the variable, and undefined means that empty has been assigned to the variable. What is the difference between "nothing" and "emptiness" in this case - reflect at your leisure. We will not do this now.

The sixth type (object) available to the program is:
-Object(not to be confused with the Object constructor, we're only talking about abstract types right now!) is the only type that represents objects in JavaScript.
An object is a data structure (a whole set of them), represented as a set of key-value pairs. The value can be any of the data types - then it will be a property of the object, or even a function - then it will be a method of the object.

There are a myriad of ways to work with primitives. Starting with the fact that they can be assigned to variables through literals or through constructors and ending with the fact that primitives can not be declared in variables at all, working with them directly. The same primitives can be in global variables and in local ones.

Here are some examples:

Var v1; // undefined (empty) local variable var v2 = "2"; // string local literal variable var v3 = new String (2); // string local variable declared through the constructor. Will create a new object of type String v4 = String (2); // string global variable called through the constructor. Will create a variable window.v4 "2" .length; // the string will not become a variable, but it can already be used as an Object 34..toString (); // the number will not become a variable, but it can already be used as an object 12. toString (); // the number will not become a variable, but it can already be used as an object (22) .toString (); // the number will not become a variable, but it can already be used as an object

In the last 4 commands, you can clearly see how a primitive is confused with an object - after all, we call a method, through a dot - just like an object. It really looks like these primitives are objects.

The misconception is compounded when we check the type of a variable, for example

Var v = null; typeof v;

And we get "object" in response.

And if we write:
var v = null; v instanceof Object;

Then a mess will appear in my head, because the result of the last line will be "false". That is, the variable v is of type object, but not inherited from type Object. What the heck?!

First, I'll explain the trick with typeof null. This operator returns the type of the object. And the fact is that the typeof operator returns a string value taken from a hard-coded table, where it is written: "for null, return" object "". The instanceof operator - checks whether something belongs to the specified data type. I will tell you how it does this in the next article, but I assure you that in this case it worked correctly, the primitive null is by no means inherited from the Object type - it itself, a primitive, is the lowest stage of development.

Okay, we figured out with typeof and instanceof, but the methods are called for primitives - just like objects are straight! How if it's not an object?

Here's the thing. There is such a thing as wrapper functions (constructors) (and will be cleared up again in the second article). They are available for all primitives (Number (), Boolean (), String ()), as well as others. Their essence is to create an object from a primitive, which will have auxiliary methods for working with this type of primitive.
For example, a variable can be created like this:

Var num = new Number (23.456);

In this case, we get an object from primitive 23.456.
For the number type, the Number () constructor has a helper method toPrecision () - it determines the number of significant digits for the number. For example, if the number of significant digits is set to 23.456, then we get the number 23.45.
And here's when we try to refer to the primitive as an object:

(23.456). toPrecision (4);

The interpreter temporarily wraps the primitive into an object by calling new Number (23.456) and then calls the toPrecision () method of this object, which it now has. Thus, many people mistakenly think that everything in JS is an object.

There is also another example of a misleading and misunderstanding of what is happening. Here is the code:

Var str = ‘str’; str.test = ‘test’; // there will be no error, the program will continue to run, but console.log (str.test); // undefined

If we assumed, as before, that str is an object, we would be surprised why it did not remember the new property test. But now we know that when referring to a primitive as an object, it is temporarily wrapped in an object of type String. But after the operation is completed, this wrapper disappears, and with it the new property test. That's it, no magic.

In fact, looking ahead, while wrapping a primitive into an object, a whole chain of inheritance is built (as we will talk about it later), but in fact it turns out such a "matryoshka":

Object (Number (<примитив>)). The parent of any object in JS, one way or another, will be Object. When you call a property in an object, the search goes through this entire "matryoshka" until it finds this property in one of the objects or returns undefined, or if you were looking for a method, it throws an exception. Thus, the primitive also has the properties of the Object object available. We will talk about how prototypal inheritance works and its intricacies in the second article.

For the intrigue of the second article that I want to release, I'll talk about one more thing related to constructor functions - this is type conversion. JS is not a strongly typed language. This means that at the moment of declaring a variable, we are not obliged to indicate what type it is, and moreover, during the operation of the program, data of any absolute type can be put into this variable. And also we can use, for example, string variables in mathematical operations or vice versa, numbers in concatenation operations. Example:

Var str = "abc"; str + 1; // "abc1"

Here, a primitive of type number - 1 will be converted to a string primitive. In objects, this feature is available through the call to the toString () method, in objects of type number, there is a method valueOf () that will return a primitive of type number. But we kind of said that only objects can have methods. So, in the process of converting a primitive from one type to another, there is also wrapping in an object? I assure you not. This method is called implicitly when the constructor function is called by the interpreter without the new operator. What kind of magic operator new is and what happens when a constructor function is called without it, and what the hell is such a constructor function, we will talk in the next article. For now, take my word for it - type conversion occurs immediately - from primitive to primitive.

So far, of course, there are more questions than answers, however, believe me, everything will become much more transparent after reading the second article. Here I mainly intrigued and raised a number of questions - so to speak, excited the minds. But still, something can be learned from this article:
1. Despite the conventional wisdom that “everything in JS is objects” is not so, we found out that out of 6 data types available to the programmer, 5 are primitives and only one represents an object type.
2. About objects, we learned that this is a data structure that contains key-value pairs. When the value can be any of the data types (and this will be a property of the object) or a function (and this will be a method of the object).
3. But primitives are not objects. Although you can work with them as with an object (and this causes the misconception that a primitive is an object), but ...
4. Variables can be declared both in a simple (literal) way (var a = ‘str’) or in a constructor function (wrapper) (var a = new String (‘str’)). In the second case, we will no longer receive a primitive, but an object created by the String () wrapper function. (what kind of magic operator new and what a constructor function is, we will learn later).
5. We learned that it is by creating a wrapper over a primitive (new String (‘str’)) that you can work with it as an object. It is this wrapper that the interpreter creates around the primitive when we try to work with it as with an object, but after the operation is completed, it is destroyed (therefore, the primitive will never be able to remember the property that we assign to it a.test = 'test' - the test property will disappear with the wrapper ).
6. We learned that objects have a toString () method that returns a string representation of an object (for the number valueOf () type, it will return a numeric value).
7. We realized that when performing concatenation or mathematical operations, primitives can redefine their type to the desired one. To do this, they use wrapper functions of their types, but without the new operator (str = String (str)). (What is the difference and how it works, let's talk further)
8. Finally, we learned that typeof takes values ​​from a hard-coded table (this is where another misconception based on typeof null // object comes from).

Programming languages ​​all have built-in data structures, but these often differ from one language to another. This article attempts to list the built-in data structures available in JavaScript and what properties they have; these can be used to build other data structures. Wherever possible, comparisons with other languages ​​are drawn.

Dynamic typing

JavaScript is a loosely typed or a dynamic language. Variables in JavaScript are not directly associated with any particular value type, and any variable can be assigned (and re-assigned) values ​​of all types:

Let foo = 42; // foo is now a number foo = "bar"; // foo is now a string foo = true; // foo is now a boolean

Data types

The latest ECMAScript standard defines eight data types:

  • Seven data types that are:

Primitive values

All types except objects define immutable values ​​(values, which are incapable of being changed). For example and unlike to C, Strings are immutable. We refer to values ​​of these types as "primitive values".

Boolean type

Boolean represents a logical entity and can have two values: true, and false. See Boolean and Boolean for more details.

Null type

Properties

In JavaScript, objects can be seen as a collection of properties. With the object literal syntax, a limited set of properties are initialized; then properties can be added and removed. Property values ​​can be values ​​of any type, including other objects, which enables building complex data structures. Properties are identified using key values. A key value is either a String or a Symbol value.

There are two types of object properties which have certain attributes: The data property and the accessor property.

Data property

Associates a key with a value and has the following attributes:

Attributes of a data property
Attribute Type Description Default value
[] Any JavaScript type The value retrieved by a get access of the property. undefined
[] Boolean If false, the property "s [] can" t be changed. false
[] Boolean for ... in loops. See also Enumerability and ownership of properties false
[] Boolean If false, the property can "t be deleted, can" t be changed to an accessor property and attributes other than [] and [] can "t be changed. false
Obsolete attributes (as of ECMAScript 3, renamed in ECMAScript 5)
Attribute Type Description
Read-only Boolean Reversed state of the ES5 [] attribute.
DontEnum Boolean Reversed state of the ES5 [] attribute.
DontDelete Boolean Reversed state of the ES5 [] attribute.

Accessor property

Associates a key with one or two accessor functions (get and set) to retrieve or store a value and has the following attributes:

Attributes of an accessor property
Attribute Type Description Default value
[] Function object or undefined The function is called with an empty argument list and retrieves the property value whenever a get access to the value is performed. See also get. undefined
[] Function object or undefined The function is called with an argument that contains the assigned value and is executed whenever a specified property is attempted to be changed. See also set. undefined
[] Boolean If true, the property will be enumerated in for ... in loops. false
[] Boolean If false, the property can "t be deleted and can" t be changed to a data property. false

Note: Attribute is usually used by JavaScript engine, so you can "t directly access it (see more about Object.defineProperty ()). That" s why the attribute is put in double square brackets instead of single.

"Normal" objects, and functions

A JavaScript object is a mapping between keys and values. Keys are strings (or Symbol s) and values ​​can be anything. This makes objects a natural fit for hashmaps.

Functions are regular objects with the additional capability of being callable.

Dates

When representing dates, the best choice is to use the built-in Date utility in JavaScript.

Indexed collections: Arrays and typed Arrays

Arrays are regular objects for which there is a particular relationship between integer-key-ed properties and the "length" property. Additionally, arrays inherit from Array.prototype which provides to them a handful of convenient methods to manipulate arrays. For example, indexOf (searching a value in the array) or push (adding an element to the array), etc. This makes Arrays a perfect candidate to represent lists or sets.

Typed Arrays are new to JavaScript with ECMAScript 2015 and present an array-like view of an underlying binary data buffer. The following table helps you to find the equivalent C data types:

TypedArray objects

Type Value Range Size in bytes Description Web IDL type Equivalent C type
Int8Array -128 to 127 1 8-bit two "s complement signed integer byte int8_t
Uint8Array 0 to 255 1 8-bit unsigned integer octet uint8_t
Uint8ClampedArray 0 to 255 1 8-bit unsigned integer (clamped) octet uint8_t
Int16Array -32768 to 32767 2 16-bit two "s complement signed integer short int16_t
Uint16Array 0 to 65535 2 16-bit unsigned integer unsigned short uint16_t
Int32Array -2147483648 to 2147483647 4 32-bit two "s complement signed integer long int32_t
Uint32Array 0 to 4294967295 4 32-bit unsigned integer unsigned long uint32_t
Float32Array 1.2x10 -38 to 3.4x10 38 4 32-bit IEEE floating point number (7 significant digits e.g. 1.1234567) unrestricted float float
Float64Array 5.0x10 -324 to 1.8x10 308 8 64-bit IEEE floating point number (16 significant digits e.g. 1.123 ... 15) unrestricted double double
BigInt64Array -2 63 to 2 63 -1 8 64-bit two "s complement signed integer bigint int64_t (signed long long)
BigUint64Array 0 to 2 64 -1 8 64-bit unsigned integer bigint uint64_t (unsigned long long)

Keyed collections: Maps, Sets, WeakMaps, WeakSets

These data structures take object references as keys and are introduced in ECMAScript Edition 6. Set and WeakSet represent a set of objects, while Map and WeakMap associate a value to an object. The difference between Maps and WeakMaps is that in the former, object keys can be enumerated over. This allows garbage collection optimizations in the latter case.

One could implement Maps and Sets in pure ECMAScript 5. However, since objects cannot be compared (in the sense of "less than" for instance), look-up performance would necessarily be linear. Native implementations of them (including WeakMaps) can have look-up performance that is approximately logarithmic to constant time.

Usually, to bind data to a DOM node, one could set properties directly on the object or use data- * attributes. This has the downside that the data is available to any script running in the same context. Maps and WeakMaps make it easy to privately bind data to an object.

Structured data: JSON

JSON (JavaScript Object Notation) is a lightweight data-interchange format, derived from JavaScript but used by many programming languages. JSON builds universal data structures. See JSON and JSON for more details.

More objects in the standard library

JavaScript has a standard library of built-in objects. Please have a look at the reference to find out about more objects.

Determining types using the typeof operator

The typeof operator can help you to find the type of your variable. Please read the for more details and edge cases.

Specifications

Specification Status Comment
ECMAScript 1st Edition (ECMA-262) Standard Initial definition.
ECMAScript 5.1 (ECMA-262)
The definition of "Types" in that specification.
Standard
ECMAScript 2015 (6th Edition, ECMA-262)
Standard Added Symbol.
ECMAScript Latest Draft (ECMA-262)
The definition of "ECMAScript Data Types and Values" in that specification.
Draft