Data types in javascript. JavaScript Data Types

I decided to write a series of articles called “Complicated things about simple things.” This series will be dedicated to the 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.

Sixth, available to the program type (object) is:
- Object (not to be confused with the Object constructor, we are talking only 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 new object 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 strict 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 a named memory location in which you can both store some information and retrieve it from it.

Declaration (creation) of variables is carried out using keyword var.

// message - variable name var message;

When you create a variable, you can immediately assign a value to it.

Assigning a value to a variable is done using the “=” operator.

// for example, create a variable email and assign it the string " [email protected]"var email = " [email protected]"; // set the email variable to a new value email = " [email protected]";

To get the value of a variable, simply refer to it by name.

// for example, output the value of the email variable to the browser console: console.log(email);

To declare more than one variable using a single var keyword, you must use a comma.

Var price = 78.55, quantity = 10, message;

JavaScript is a dynamically or weakly typed language. This means that when a variable is declared, it does not need to specify the data type it can accept. Therefore, you can first place a value of one data type in a variable, and then another.

Var output = "success"; // the variable has a string data type output = 28; // the same variable, but already of the “number” data type output = true; // the same variable, but already storing a Boolean value

The value of a variable can be changed an unlimited number of times.

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

A good practice when developing client applications is to use only one data type in a given variable, i.e. do not write values ​​to a variable that have Various types data. To understand what type of data should be expected in a variable, when creating a variable, it is recommended to immediately initialize it with a specific value.

The variable name can be composed of letters, numbers, and the symbols $ and _. In this case, the first character of the variable must not be a number. In addition, you cannot use reserved words as variable names.

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

The case of the letters in the variable name matters. That is, for example, the variable phone and Phone are two different variables.

If strict mode is not used, then you can create a variable with the initial value without the var keyword.

Price = 250.00; // created a variable and initialized it with the number 250.00 percent = "20%"; // created a variable and initialized it with the string “20%”

But creating variables in this way is not recommended.

Data types

In JavaScript, data types can be divided into primitive and object.

Variables containing primitive data types store their value explicitly.

There are 5 primitive data types in JavaScript:

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

If one variable is assigned the value of another that contains a primitive data type, it will receive its own copy of that value.

Var x = 77, y = x; x = 55; y; // 77

Variables containing an object do not actually store the object itself, but a reference to it.

If one variable is assigned the value of another that contains an object (a link to it), then it will also receive a link to it. As a result of this operation, these two variables will contain a reference to the same object.

// example 1 (with data type "object") var coord1 = (x: 77, y: 100), coord2 = coord1; coord1.x = 55; // set the x property of the object to a new value coord2.x; // 55, because coord1 and coord2 contain a reference to the same object // example 2 (with an array data type) var coord1 = , coord2 = coord1; coord1 = 55; // set the element with index 0 to a new value coord2; // 55, because coord1 and coord2 contain a reference to the same object // example 3 (with data type "date") var date1 = new Date(2018,00,01), date2 = date1; date2 = date2.setDate(date2.getDate()+7); // increase the date by 7 days date1; // 01/07/2018, because date1 and date2 contain a reference to the same object

Number

The numeric data type in JavaScript is generic. It is used to represent both integers and fractions.

Var int = 5; // integer var float = 5.98; // a fractional number

The format for representing numbers in JavaScript is in accordance with the IEEE 754-2008 standard.

Integers in JavaScript can be specified not only in decimal system notation, but also in octal (0) or hexadecimal system radix (0x) using prefixes specified in parentheses:

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

It is possible to write numbers in exponential form:

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

In addition to numbers, the numeric data type also contains special numeric values:

  • Infinity (positive infinity);
  • -Infinity (negative infinity);
  • NaN (Not a Number).

The special value Infinity means a very large positive number, i.e. a number that cannot be represented in JavaScript because it is too large.

Special meanings -Infinity means, on the contrary, a very large negative number, i.e. a number that cannot be represented by JavaScript because it is also too large.

An example of expressions that will return special numeric values ​​as a result of their calculation:

5/0; // Infinity -5/0; // -Infinity Math.pow(10,399); // Infinity (10 to the power of 399) Math.pow(10,399); // -Infinity (-10 to the power of 399)

The NaN value is returned as a result of performing mathematical operations that JavaScript cannot calculate.

5 - "Hi"; // NaN (subtract a line from the number 5) 1000 / "20px"; // NaN (number divided by string) true * "1rem"; // NaN (boolean value true multiplied by string)

What is very interesting is that the value of NaN in JavaScript is not equal to anything including itself.

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

Boolean type data (Boolean)

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

Var a = true; var b = false;

String

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

A JavaScript string can consist of 0 or more characters.

JavaScript always uses Unicode as its string format.

Creating a string (string literal) is done by enclosing text in single or double quotes.

"JavaScript"; "ECMAScript";

In JavaScript, there is no difference between single and double quotes.

But, in some cases, it makes sense to use single quotes rather than double quotes and vice versa.

For example, when a string contains double quotes, it is more convenient to enclose it in single quotes. This will eliminate the need to escape double quotes in it.

""ECMAScript""; // without escaping (using single quotes) "\"ECMAScript\""; // with escaping

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

"This is a sentence.\nAnd this is also a sentence, but it will start from a new line.";

With strings you can perform the operation of addition (union) or, in other words, concatenation. The "+" operator is used for this. The meaning of this operation is to append the second line to the end of the first.

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

The value is "undefined"

undefined is a special primitive data type that has a single value equal to undefined .

This data type has a declared variable that has not yet been assigned a value.

Var num; // undefined

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

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

"null" value

null is a special primitive data type that has a single value equal to null .

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

Object

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

Creating an object using object literal notation is done as follows:

( name_1: value_1, name_2: value_2, name_3: value_3, ... )

As you can see, the name is separated from the value using a colon, and pairs are separated from each other using a comma.

Moreover, if the value of the pair is a function, then it is called a method of this object. All other pairs, i.e. pairs in which a function is not used as a value are called object properties.

In other words, an object is a data structure consisting of properties and methods.

Var person = ( name: "Vitaly", age: 27, getAge: function () ( return "Age: " + this.age; ) )

Accessing the properties of an object is done through a period or using bracket notation.

// display the value of the age property in the browser console // 1st method (via a dot) console.log(person.age); // Method 2 (using parentheses) console.log(person["age"]); // call the getAge method; the value it returns will be output to the console console.log(person.getAge());

typeof operator

The typeof operator is used to obtain information about the data type of an expression as a string.

The syntax of the typeof operator (option without parentheses):

Typeof expression

Typeof operator syntax (using parentheses):

Typeof(expression)

Var name, age = 37, email = " [email protected]", isLicense = true, interest: null, lastExperience: ( period: "June 2011 - June 2018", place: "ISACA, Moscow", position: "Web designer" ), getExperience: function() ( return lastExperience.period + " ("+ lastExperience.position + " - " + lastExperience.place + ")"; ); typeof name; // "undefined" typeof age; // "number" typeof isLicense; // "boolean" typeof interest; / / "object" (1) typeof lastExperience; // "object" typeof getExperience; // "function" (2) /* (1) is a bug that has been present in the language since its first implementation; it has not been fixed in order to maintain compatibility and this must be taken into account when writing scripts; null is a primitive data type, it is not an object */ /* (2) - it is very convenient that the typeof operator separates functions separately; but a function in JavaScipt is also object; this can be easily verified by executing the following construction: */ typeof getExperience.__proto__.__proto__ // "object" (the function prototype is an object)

Constants

With the release of ECMAScript 6, it became possible to create constants. This is done using the const keyword.

Const COLOR_RED = "#ff0000";

A constant is a variable whose value is protected from change. Those. When you try to change the value, an error will be thrown.

Const COLOR_RED = "#ff0000"; COLOR_RED = "#f44336"; // Uncaught TypeError: Assignment to constant variable.

If, for example, a constant contains an object, then it cannot be changed, or rather a reference to it. But the properties of this object can be changed.

Const COLORS = ( red: "#ff0000", green: "#00ff00", blue: "#00ff00" ) COLORS = ["#ff0000","#00ff00","#00ff00"]; // Uncaught TypeError: Assignment to constant variable. COLORS.green = "#4caf50";

As in any other programming language, data types in JS are divided into:

–literals and variables

–arrays, functions and objects

Literals:

Literals are the most primitive units in any programming language, such as numbers and symbols. In JavaScript, literals are divided into numeric and string:

Numeric literals String literals

4.5e+2 "Data types in JavaScript"

You can use literals in JS code for assignment and comparison operations:

var pi = "PI number";

if(q == "b") q = b + 1;

Variables:

Well, what is a programming language without variables? In general, variables can safely be called the basis of any programming language. Almost no function, no loop or statement can be executed without using variables.

JavaScript allows you to assign not only literal values ​​to this data type, but also an entire array, an entire function, or the name of an object. You can set variables either simply anywhere in the program or using the var operator:

id = window.close();

var arr = new Array();

ob = document.forms;

There are two main types of arrays in JavaScript:

built into the interpreter (document.forms, document.images,...)

user defined

An array is created using the new Array();

a = new Array(); b = new Array(15); c = new Array(15,33,"value 3");

In the first case, variable a is assigned an empty array, in the second, variable b is assigned an array whose first value is the number 15, and finally, in the third case, variable c is assigned an array of 3 values, the third of which is a string literal.

There are several basic methods for processing arrays in JS:

join(); reverse();sort();

Below is a list of the main operators that we will consider:

var; (...); if; while; for; for ... in; break; continue; return.

3. Variables and assignment operator in JavaScript.

The basic assignment operator is the ordinary equalization =, which gives the left operand the value of the right operand.

The remaining operators are abbreviations of the following forms. Abbreviation Operator Meaning

x += y x = x + y

x -= y x = x - y

x *= y x = x * y

x /= y x = x / y

x %= y x = x % y

x>y

x >>>= y x = x >>> y

x &= y x = x & y

x ^= y x = x ^ y

x |= y x = x | y

4. Operators in JavaScript.

Operators are used to control the flow of commands in JavaScript. One object can be divided into several lines, or, conversely, there can be several statements in one line.

You need to know the following, firstly, statement blocks such as function definitions must be enclosed in curly braces. Second, the semicolon serves as a separator for individual statements. If you omit a semicolon, the program's behavior will become unpredictable.

Since JavaScript does not have strict requirements for formatting program text, you can insert line breaks and indentation characters for better readability of the text.

The following are the operators that are used in JavaScript:

break, comment, continue , for , for...in , function , if...else

JavaScript or JS(abbreviated) is not an easy language and novice developers will not learn about it right away. At first they learn the basics and everything seems colorful and beautiful. Going a little deeper, JavaScript arrays, objects, callbacks and everything like that appear, which often blows your mind.

In JavaScript, it is important to properly check the type of a variable. Let's say you want to know whether a variable is an array or an object? How to check this correctly? In this particular case, there are tricks during verification and this post will be about them. Let's get started right away.

Checking the type of a variable

For example, you need to check whether a variable is an object, an array, a string or a number. You can use typeof for this, but it will not always tell the truth and in the example below I will show why.

I wrote this example to clearly show why typeof is not always the right choice.

Var _comparison = ( string: "string", int: 99, float: 13.555, object: (hello: "hello"), array: new Array(1, 2, 3) ); // Returns an array with the object's keys var _objKeys = Object.keys(_comparison); for(var i = 0; i colorArray.length - 1)( i = 0; ) ) Change background

Inside the element.
The element can be inserted anywhere in the document. Inside the tag is code that is executed immediately after being read by the browser, or contains a description of the function that is executed at the time it is called. The function description can be placed anywhere, the main thing is that by the time it is called, the function code has already been loaded.

Typically, JavaScript code is placed in the head of the document (the element) or after the opening tag. If the script is used after the page has loaded, for example, the counter code, then it is better to place it at the end of the document:

document.write("Enter your name");

2. Data types and variables in JavaScript

Computers process information—data. Data can be presented in various forms or types. Most of JavaScript's functionality is implemented through a simple set of objects and data types. String, number, and logic functionality is based on string, numeric, and Boolean data types. Other functionality, including regular expressions, dates, and math operations, is done using the RegExp, Date, and Math objects.

Literals in JavaScript are a special class of data type, fixed values ​​of one of three data types - string, numeric, or boolean:

"this is a string" 3.14 true alert("Hello"); // "Hello" is a literal var myVariable = 15; // 15 is a literal

A primitive data type is an instance certain type data such as string, numeric, boolean, null and undefined.

2.1. Variables in JavaScript

Data processed JavaScript script, are variables. Variables are named containers that store data (values) in computer memory that can change during program execution. Variables have a name, a type, and a value.

The variable name, or identifier, can only include letters a-z, A-Z, numbers 0-9 (the number cannot be the first character in a variable name), the $ symbol (can only be the first character in a variable or function name) and the underscore character _, spaces are not allowed. The length of the variable name is not limited. It is possible, but not recommended, to write variable names in letters of the Russian alphabet; for this they must be written in Unicode.

You cannot use JavaScript keywords as a variable name. Variable names in JavaScript are case sensitive, which means that the variable var message; and var Message; - different variables.

A variable is created (declared) using the var keyword followed by the name of the variable, for example, var message; . You must declare a variable before using it.

A variable is initialized with a value using the assignment operator = , for example, var message="Hellow"; , i.e. a message variable is created and its initial value "Hello" is stored in it. A variable can be declared without a value, in which case it is assigned the default value of undefined . The value of a variable can change during script execution. Different variables can be declared on the same line, separated by a comma:

Var message="Hello", number_msg = 6, time_msg = 50;

2.2. Variable Data Types

JavaScript is an untyped language; the data type for a specific variable does not need to be specified when declaring it. The data type of a variable depends on the values ​​it accepts. The type of a variable can change during data operations (dynamic type casting). Type conversions are performed automatically depending on the context in which they are used. For example, in expressions involving numeric and string values ​​with the + operator, JavaScript converts the numeric values ​​to string values:

Var message = 10 + "days before vacation"; // will return "10 days until vacation"

You can get the data type of a variable using the typeof operator. This operator returns a string that identifies the corresponding type.

Typeof 35; // return "number" typeof "text"; // return "string" typeof true; // return "boolean" typeof ; // return "object" typeof undefined; // will return "undefined" typeof null; // return "object"

All data types in JavaScript are divided into two groups - simple data types (primitive data types) and composite data types (composite data types).

Simple data types include string, numeric, boolean, null, and underfined.

2.2.1. String type

Used to store a string of characters enclosed in double or single quotes. An empty set of characters enclosed in single or double quotes is the empty string. A number enclosed in quotes is also a string.

Var money = ""; // empty string, zero characters var work = "test"; var day = "Sunday"; var x = "150";

You can include a single quote within a double-quoted string, and vice versa. A quotation mark of the same type is escaped using the backslash character \ (called an escape sequence):

Document.writeln("\"Good morning, Ivan Ivanovich!\"\n"); // will display "Good morning, Ivan Ivanovich!"

Strings can be compared and also combined using the concatenation operator + . Thanks to automatic type casting, you can combine numbers and strings. Strings are permanent, once a string is created it cannot be modified, but a new string can be created by concatenating other strings.

2.2.2. Numeric type (number)

Used for numeric values. There are two types of numbers in JavaScript: integers (integer) and floating point numbers (floating-point number). Integer values ​​can be positive, such as 1, 2, negative, such as –1, –2, or zero. 1 and 1.0 are the same value. Most numbers in JavaScript are written in decimal, but octal and hexadecimal systems can also be used.

In the decimal system, the values ​​of numeric variables are specified using Arabic numerals 1, 2, 3, 4, 5, 6, 7, 8, 9, 0.

In octal format, a number is a sequence containing the digits 0 through 7, starting with the prefix 0.

For hexadecimal format, the prefix 0x (0X) is added, followed by a sequence of numbers from 0 to 9 or letters from a (A) to f (F), corresponding to values ​​from 10 to 15.

Var a = 120; // integer decimal numeric value var b = 012; // octal format var c = 0xfff; // hexadecimal format var d = 0xACFE12; // hexadecimal format

Floating point numbers are numbers with a fractional decimal part, or they are numbers expressed in scientific notation. Scientific notation of numbers assumes the following form: a number with a fractional decimal part, followed by the letter e, which can be indicated in both upper and lower case, then an optional + or - sign and an integer exponent.

Var a = 6.24; // real number var b = 1.234E+2; // real number, equivalent to 1.234 X 10² var c = 6.1e-2; // real number, equivalent to 6.1 X 10‾²

2.2.3. Boolean type

This type has two values, true, false. Used to compare and test conditions.

Var answer = confirm("Did you like this article?\n Click OK. If not, click Cancel."); if (answer == true) ( ​​alert("Thank you!"); )

There are also special types of simple values:
null type - this type has a single null value, which is used to represent non-existent objects.

undefined type - the variable type underfined means the absence of the initial value of the variable, as well as a non-existent property of the object.

Composite data types consist of more than one value. These include objects and special types of objects—arrays and functions. Objects contain properties and methods, arrays are an indexed collection of elements, and functions consist of a collection of statements.

2.3. Global and local variables

Variables by scope are divided into global and local. A scope is the part of a script within which a variable name is associated with that variable and returns its value. Variables declared inside the body of a function are called local variables and can only be used within that function. Local variables are created and destroyed along with the corresponding function.

Variables declared inside an element, or inside a function, but without using the var keyword, are called global. They can be accessed as long as the page is loaded in the browser. Such variables can be used by all functions, allowing them to exchange data.

Global variables end up in the global namespace, which is where individual program components interact. It is not recommended to declare variables in this way because similar variable names may already be used by other code, causing the script to crash.

Global space in JavaScript is represented by the global window object. Adding or changing global variables automatically updates the global object. In turn, updating the global object automatically updates the global namespace.

If a global and a local variable have the same name, then the local variable will take precedence over the global one.

Local variables declared within a function in different code blocks have the same scope. However, it is recommended to place all variable declarations at the beginning of the function.