Computer literacy, assistance and repair

What is the type of variable null in js. JavaScript Data Types

In this lesson we will get acquainted with a very important concept - types JavaScript data. 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(they are 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).
  • Object(English Object) is a collection of named values, which are usually called properties (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 simple type to the other, she copies value. As a result, each variable will have its meaning and changes in one of the variables has no effect on the value of another variable:

When a variable assign the value of the composite(reference) type, then the variable is written link to value ( object reference). When we assign one variable (whose value contains a reference to a composite value) to another variable, what happens is copy link to a composite value. As a result both variables refer to the same composite value and changes in the value of one of the variables will have an impact on another 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 varied, and therefore the values ​​come in different 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). The values ​​true or false typically 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. On the right side of this instruction, an object literal is written - this is enclosed in braces() list of comma separated pairs "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.
  • I decided to write a series of articles called “Complicated things about simple things.” This series will be dedicated to JavaScript language. Why is it “complicated about simple things”? Because everything I will tell you, I will tell you taking into account the features of the interpreter, starting with data types. All this will be done so that later we can simply talk about complex things, for example, about methods of inheritance in JavaScript and other patterns.

    JavaScript is an object-oriented programming language with a prototypical organization.
    We will talk about what “with a prototype organization” means in the next article (there will definitely be one), but today we will find out why it is “object-oriented” and whether everything in JS is an object.
    To achieve its goals, JS only needs 9 types. 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 an object. 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 what I call them “philosophical types”:
    - null (v = null)
    - undefined (u=undefined)

    Philosophical in that null means that nothing is assigned to the variable, and undefined means that emptiness is assigned to the variable. What is the difference between “nothing” and “emptiness” in in this case- think about it at your leisure. We won't do this now.

    The sixth type (object) available to the program is:
    -Object(not to be confused with the Object constructor, we are only talking about abstract types 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 an object, or even a function - then it will be a method of the object.

    There are a great many 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 into variables at all, working with them directly. Primitives can also be in global and local variables.

    Here are some examples:

    Var v1; //undefined (empty) local variable var v2="2"; //string local literal variable var v3 = new String(2); //local string 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 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, it is clearly visible how a primitive is confused with an object - after all, we call a method through a dot - just like an object. It really seems like these primitives are objects.

    The misconception gets worse when we check the type of a variable, e.g.

    Var v = null; typeof v;

    And we get “object” in response.

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

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

    First, let me explain the catch with typeof null. This operator returns the type of the object. But the fact is that the typeof operator returns a string value taken from a rigidly fixed table, where it is written: “for null – return “object””. The instanceof operator checks whether something belongs to the specified data type. How he does this, I will tell you in the next article, but I assure you that in this case it worked correctly, the null primitive is in no way inherited from the Object type - it is a primitive in itself, a lower stage of development.

    Okay, we’ve sorted out typeof and instanceof, but methods are called on primitives - just like on objects! What if it's not an object?

    Here's the thing. There is such a thing as wrapper functions (constructors) (and again everything will become clearer in the second article). They exist for all primitives (Number(), Boolean(), String()), as well as others. Their essence is to create an object from a primitive that 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 will 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 we set the number of significant digits to 4 for the number 23.456, we get the number 23.45.
    And this is when we try to access a 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 on this object, which it now has. Thus, many people mistakenly believe that everything in JS is an object.

    There is also another example that is misleading and causes misunderstanding of what is happening. Here's the code:

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

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

    In fact, looking ahead, when wrapping a primitive into an object, a whole chain of inheritance is built (we’ll talk about how this is organized later), but in essence this is what we get as a “matryoshka doll”:

    Object(Number(<примитив>)). The parent of any object in JS, one way or another, will be Object. When calling 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 it was looking for a method, it will throw an exception. Thus, the primitive also has Object properties available. We will talk about how prototypic inheritance works and its intricacies in the second article.

    To add some intrigue to the second article that I want to release, I’ll tell you about another point related to constructor functions - type conversion. JS is not a strongly typed language. This means that at the time of declaring a variable, we are not required to indicate what type it is, and moreover, while the program is running, data of absolutely any type can be placed in this variable. We can also use, for example, string variables in mathematical operations or, conversely, numbers in the concatenation operation. 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 by calling the toString() method; in objects of type number, there is a valueOf() method, which 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, it is also wrapped in an object? I assure you that it is 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 a constructor function after all, 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 clearer after reading the second article. Here I mainly intrigued and raised a number of questions - stirred minds, so to speak. But still, something can be taken away from this article:
    1. Despite the popular belief “everything in JS is an object” - this is not true, we found out that out of 6 data types available to a programmer, as many as 5 are primitives and only one represents an object type.
    2. We learned about objects 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 an 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 either simply (literally) (var a = ‘str’) or through 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. (We will find out what kind of magic operator new is and what a constructor function is further).
    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 a primitive when we try to work with it as an object, but after performing the operation it is destroyed (so 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 the object (for the number type, valueOf() will return a numeric value).
    7. Understood that when performing concatenation operations 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)). (We’ll talk further about what the difference is and how it works)
    8. And finally, we learned that typeof takes values ​​from a rigidly fixed table (this is where another misconception based on typeof null //object comes from).

    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, using the var keyword was the only way to declare variables.

    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. A new scope is created when a 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.

    ▍Keyword let

    The let keyword was introduced in ES2015 and can be simply 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.

    ▍Keyword const

    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.

    Data types

    JavaScript is sometimes called an "untyped" language, but this is not true. 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.

    Type number

    Number values ​​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 special character.

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

    "A" + "string"

    Template literals

    ES2015 introduced so-called template literals, or template strings. 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)`

    Type boolean

    JavaScript has a couple 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.

    Type null

    JavaScript has a special value, null , which indicates the absence of a value. Similar meanings 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 of 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 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

    This category includes expressions that result in 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

    Array and Object Initialization Expressions

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

    Boolean expressions

    Boolean expressions use logical operators and produce logical values ​​as a result of their evaluation.

    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 )

    Call 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 will talk about objects in more detail, in particular, we will look at the mechanism of prototypal inheritance and the use of the class keyword.

    ▍Prototype 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 an object's prototype 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 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 it is called, a new object is created, pointed to by the this keyword 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

    The ES6 standard introduced the concept of a “class” to JavaScript.

    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, both objects created in the 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 prefacing 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 ) )

    Results

    In this article 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.

    Lesson #3
    Data types in JavaScript

    In the last lesson, we found out that a variable is a named memory area that stores some data (values).

    Each value in JavaScript has its own data type. There are a total of 6 data types in JavaScript, in this JavaScript tutorial we will look at 4 data types:
    — numeric data type number ,
    — string data type string ,
    — boolean data type,
    — undefined data type undefined .

    We'll study the other two a little later:
    — object data type object
    — empty data type null

    typeof operator

    Before you consider JavaScript data types, let's first get acquainted with the typeof operator, it allows you to find out what data type is assigned to a variable, this is done as follows:

    Alert(typeofVariablename);

    After this, the script should display some message: number, string, boolean, undefined, object.

    Data type: number

    When a variable is assigned a number (without quotes) as its value, its data type becomes number

    Var myNumber; myNumber = 5; alert(typeof myNumber);

    In the first line we created a variable called myNumber, in the second line we assigned the value 5 to the variable, in the third we calculated the data type of the variable myNumber using the typeof operator, and the alert() function showed us the result of these calculations.

    As a result, this script will display the message number . If the number is surrounded by quotes (single "5" or double "5"), then it will turn into a string string .

    Data type: string

    When a variable is assigned as a value any value enclosed in double " " or single quotes " " , its data type becomes string .

    Var myString; myString = "Hi, I'm JavaScript string!"; alert(typeof myString);

    On the first line, we created a variable called myString, on the second line, we assigned the variable the value "Hi, I'm a JavaScript string!" , in the third, using the typeof operator, we calculated the data type of the myString variable, and the alert() function showed us the result of these calculations. As a result, this script should give us a string message.

    Data type: logical data type (boolean)

    When a variable is assigned true or false as its value, without quotes, its data type becomes boolean.

    The boolean data type is a logical data type and has only two values: true or false.

    Var myBoolean; myBoolean = true; alert(typeof myBoolean);

    In the first line we created a variable called myBoolean , in the second line we assigned the value true to the variable, in the third we calculated the data type of the variable myBoolean using the typeof operator, and the alert() function showed us the result of these calculations. As a result, this script should give us a boolean message.

    We will study the Boolean data type in more detail in the following lessons on comparison operations, logical operations and the branch operator if

    Data type: undefined

    The undefined data type appears when a variable is declared but not initialized, i.e. The variable was created, but no value was assigned to it.

    Var myUndefined; alert(typeof myUndefined);

    In the first line we created a variable called myUndefined , in the second line we calculated the data type of the myUndefined variable using the typeof operator, and the alert() function showed us the result of these calculations. As a result, this script should give us the message undefined .

    Accessing a variable's value

    To access the value of a variable, you need to refer to it by name:

    // declare variables var myString; var myNumber; // initialize variables myString = "Hello WORLD!"; myNumber = 5; // access variables alert(myString); alert(myNumber);

    In the first and second lines of code we created the variables myString and myNumber , in the third and fourth lines we assigned variable values"Hello World!" and 5 , in the fifth and sixth lines, using the alert() function, they displayed the results of Hello, WORLD! and 5

    Last update: 03/26/2018

    All data used in javascript has a specific type. JavaScript has five primitive data types:

      String: represents a string

      Number: represents a numeric value

      Boolean: represents the Boolean value true or false

      undefined : indicates that the value is not set

      null : indicates an undefined value

    All data that does not fall under the above five types is of type object

    Numeric data

    Numbers in JavaScript can take two forms:

      Whole numbers, such as 35. We can use both positive and negative numbers. Range of numbers used: -2 53 to 2 53

      Fractional numbers (floating point numbers), for example 3.5575. Again, both positive and negative numbers can be used. Floating point numbers use the same range: -2 53 to 2 53

    For example:

    Var x = 45; var y = 23.897;

    As in other programming languages, a dot is used as a separator between the integer and fractional parts.

    Strings

    The string type represents strings, that is, data that is enclosed in quotation marks. For example, "Hello world". Moreover, we can use both double and single quotes: “Hello world” and “Hello world”. The only limitation is that the type of the closing quote must be the same as the type of the opening quote, that is, either both double or both single.

    If there are quotes inside a string, we must escape them with a slash. For example, let's say we have the text "Bureau "Horns and Hooves"". Now we escape the quotes:

    Var companyName = "Horns and Hooves Bureau";

    We can also use another type of quotes inside the lines:

    Var companyName1 = "Horns and Hooves Bureau"; var companyName2 = "Horns and Hooves Bureau";

    Type Boolean

    The Boolean type represents the Boolean or logical values ​​true and false (that is, yes or no):

    Var isAlive = true; var isDead = false;

    null and undefined

    There is often confusion between null and undefined. So, when we just define a variable without giving it an initial value, it represents the type undefined:

    Var isAlive; console.log(isAlive); // will print undefined

    An assignment to null means that the variable has some undefined value (not a number, not a string, not a boolean value), but still has a value (undefined means that the variable has no value):

    Var isAlive; console.log(isAlive); // undefined isAlive = null; console.log(isAlive); // null isAlive = undefined; // set the type to undefined again console.log(isAlive); // undefined

    object

    The object type represents a complex object. The simplest definition of an object is represented by curly braces:

    Var user = ();

    An object can have various properties and methods:

    Var user = (name: "Tom", age:24); console.log(user.name);

    In this case, the object is called user, and it has two properties: name and age. This short description objects, more detailed description is given in the corresponding chapter.

    Weak typing

    JavaScript is a weakly typed language. This means that variables can dynamically change type. For example:

    Var xNumber; // type undefined console.log(xNumber); xNumber = 45; // type number console.log(xNumber); xNumber = "45"; // type string console.log(xNumber);

    Although in the second and third cases the console will display the number 45, in the second case the xNumber variable will represent a number, and in the third case it will represent a string.

    This is an important point that must be taken into account and on which the behavior of the variable in the program depends:

    Var xNumber = 45; // type number var yNumber = xNumber + 5; console.log(yNumber); // 50 xNumber = "45"; // type string var zNumber = xNumber + 5 console.log(zNumber); // 455

    In both cases above, the addition (+) operation is applied to the xNumber variable. But in the first case, xNumber represents a number, so the result of xNumber + 5 is 50.

    In the second case, xNumber represents a string. But the addition operation between the string and the number 5 is impossible. Therefore, the number 5 will be converted to a string, and the string concatenation operation will occur. And the result of the expression xNumber + 5 will be "455".

    typeof operator

    Using the typeof operator you can get the type of a variable:

    Var name = "Tom"; console.log(typeof name); // string var income = 45.8; console.log(typeof income); // number var isEnabled = true; console.log(typeof isEnabled); // boolean var undefVariable; console.log(typeof undefVariable); // undefined

    Related publications