JavaScript data types. Types of Variables in JavaScript Js Determining the Type of a Variable

Important Notes

null

In JavaScript, besides undefined, there is null . It means "no value". For example, if you create a variable but do not assign a value to it, it will have the value undefined:

Let a; console.log(a); // undefined

There was no significance here unintentionally. Apparently, the time has simply not yet come to give this variable a value.

null is needed to explicitly, intentionally indicate that there is no value. You can say let a = null; . For example, you asked the user to enter information, but he did not enter anything. In this case, it is appropriate to write null to the result.

null , unlike undefined , can be set manually, passed as an argument to a function, and generally used like any other explicit value.

(undefined can also be specified manually, but you should never do this: this value is semantically created only to be generated by the computer, not by the programmer).

You need to be careful when comparing null and undefined:

Typeof null; // "object" (not "null" for historical reasons) typeof undefined; // "undefined" null === undefined; // false null == undefined; // true null === null; // true null == null; // true !null; // true isNaN(1 + null); //false isNaN(1 + undefined); //true

Comparison

In this course, we compare data using three equal signs:

A === b; 12 === 12;

This comparison is direct: are these data absolutely identical?

JavaScript has a relaxed comparison, with two equal signs. They show what happens inside JavaScript when it handles typings:

1 === "1"; // false 1 == "1"; // true true === 1; // false true == 1; // true

Lesson summary

Typing in JavaScript

JavaScript has an understanding of types: numbers, strings, functions, booleans, and so on. typeof returns a string containing the type:

NaN means "not a number", but the type of this value is number .

A variable without a value has the special meaning undefined . The type of such a variable is undefined:

Dynamic and static typing

The code is converted into another form that the computer can run. This process is called compilation, and the period of time during which this process occurs is compilation stage(compile time).

After compilation is completed, the program is run and the period while it is running is called execution stage(run time).

Statically typed languages ​​check types and look for typing errors at compile time.

Dynamically typed languages ​​check types and look for typing errors at runtime.

In other words: static typing means checking types before running a program; dynamic - type checking while the program is running.

Weak and strong typing

JavaScript often converts types automatically:

JavaScript is a weakly typed language. He has an idea of ​​types, but he is relaxed about them and can operate with values, one might say, arbitrarily. The stronger the typing system, the stricter the rules.

Explicit conversions in JavaScript

Optional

Fun

Lesson transcript

In one of the previous lessons we talked about mistakes and how to deal with them. There are several types of errors, and I want to remind you of one specific type. Here is a small fragment of that lesson:

Take a look at this code:

Const length = 12; const num = length(54);

First we created a constant. Remember that this is like giving something a name: in our case, the number 12 is given the name length . In the next line we call the length function and pass it an argument - the number 54. But wait! length is not a function! It's just a number. Numbers are not functions, not boxes that perform some kind of action. And JavaScript will complain about exactly this:

→ node test.js /Users/rakhim/test.js:2 const num = length(-54); ^ TypeError: length is not a function at Object. (/Users/rakhim/test.js:2:13) at Module._compile (module.js:571:32) at Object.Module._extensions..js (module.js:580:10) at Module.load ( module.js:488:32) at tryModuleLoad (module.js:447:12) at Function.Module._load (module.js:439:3) at Module.runMain (module.js:605:10) at run ( bootstrap_node.js:420:7) at startup (bootstrap_node.js:139:9) at bootstrap_node.js:535:3

This Typing error: The object type you used is incorrect. The JavaScript interpreter won't tell you what something is, but he will definitely say what it is not. length is not a function.

A typing error is like asking a cat to do the laundry. Perhaps you wanted to ask your friend about it.

In programming, "typing" is the classification of information. This is a general term and different programming languages ​​handle typing differently. As you already know, JavaScript can distinguish between types. Function is one type, Number is another, and you can't just use Number as a function.

typeof is a special operator that returns the string in which the type is written.

Typeof 42; // "number" typeof 3.14; // "number" typeof NaN; // "number" typeof "Berry"; // "string" typeof true; // "boolean" typeof false; // "boolean"

42 and 3.14 are obviously numbers, several combinations of letters in quotes are a string, and true and false are a Boolean. All these are types in JavaScript - number, string and boolean.

NaN means "not a number", but the type NaN is a "number". Yes, I know. Another weird thing about JavaScript. These are the rules in this language.

Typing is useful. When we try to run a number as if it were a function, JavaScript will start complaining and we will see the error and fix it. If there were no type notation in JavaScript, we would either end up with some anomalous behavior or a mysterious bug. Instead of a clear "length is not a function", we would see something like "I"m sorry Dave, I"m afraid I can"t do that".

What if you create a variable but don't give it any value? What type will be in this case? It's not a number, it's not a string, it's nothing... Because it has no meaning, right?

JavaScript in this case does something in secret from you. A variable without a value actually has a special meaning - "undefined". And the type of such a variable is called "undefined".

Let a; console.log(a); // undefined typeof a; // "undefined"

For example, the number type has many potential values: 1, 2, -10, 69000, and other numbers. And there is only one type of undefined - undefined.

When it comes to typing in programming, it is important to distinguish between two concepts: dynamic vs. static and weak vs. strong.

To understand the difference between dynamic and static typing, we first need to look at how written programs become running programs.

The code you write is usually converted into a form that a computer can run. This process is called compilation, and the period of time during which this occurs is called the “compilation stage” or compile time.

After compilation is completed and the program is launched, a time countdown begins, which is called the “execution stage” or run time.

Some languages ​​check types and look for typing errors at compile time. They have static typing.

Other languages ​​check types and look for typing errors at runtime. This typing is dynamic.

In other words: static typing means checking types before running the program, dynamic typing means checking types when the program is running.

C#, C++, Java, Go are statically typed languages. If in one of these languages ​​you create a number and try to operate on it as a function, you will get a compile-time error and the program won't run - it won't even get to that stage because the typing error will be caught before execution. during compilation.

JavaScript, Ruby, PHP are dynamically typed languages. As you saw earlier, if you use the wrong type, your program will run, and the error will only be discovered when that particular line of code is executed. Here types are checked at runtime.

Actually, in JavaScript usually there is no compilation, but that is a topic for another lesson.

Dynamic typing is no worse or better than static typing. Both methods have their advantages and disadvantages. Dynamically typed languages ​​are usually easier to learn and write programs in, but as you can imagine, this potentially increases errors and bugs.

Now let's talk about weak and strong typing. Look at this JavaScript code:

4 + "7"; // "47" 4 * "7"; // 28 2 + true; // 3 false - 3; // -3

Hmmm... This... Ok, what's going on here? Adding the number 4 to the string "7" gives us the string "47". JavaScript converts the number 4 into the string "4" and concatenates the two strings - sticking them together. JavaScript just takes it upon itself to assume that this is what we wanted. It's stupid to blame him - what did we really want? Adding a number to a string makes no sense. Any other language like Ruby or Python would simply complain and do nothing.

The product of the number 4 with the string "7", as you can see, is 28, according to JavaScript. In this case, he converted the string "7" into the number 7 and performed the usual multiplication.

JavaScript does this all the time. It knows about the types of different values, but when the types don't match, it tries to guess and convert one type to another without warning you. Sometimes it's useful, sometimes it's mind-blowing. This happens because JavaScript is a weakly typed language. He has an idea of ​​types, but he's like, "It's just a game, why are you mad?"

This concept has nothing in common with dynamic and static typing, the point of which is WHEN to check types. Strong vs weak is HOW SERIOUSLY to type check.

In contrast to dynamism and staticity, the power of typing is a spectrum. PHP's typing is a little stronger. Python is even stronger. And they are all dynamically typed languages.

JavaScript does a lot of implicit conversions, but it also gives us the tools to do explicit conversions ourselves. We can convert strings to numbers, numbers to strings, booleans to strings, and so on:

Number("590"); // 590 Number("aaa!!"); // NaN Boolean(1); // true Boolean(0); // false String(true); // "true" String(false); // "false" String(44843); // "44843"

One might assume that implicit conversion from type to type is not a good idea. Implicit means hidden, and hidden means difficult to understand and prone to error. The behavior of the program becomes less obvious. You write less code, yes, but the code is more fragile and less understandable.

The syntax rules for creating variable names in JavaScript are:

  • The following symbols are used for variable names: a-z, A-Z, numbers, the $ symbol, and the underscore (_).
  • The variable name cannot begin with a number.
  • JavaScript is case sensitive, something to keep in mind when programming. itcounter and it C ounter are different variables.
  • JavaScript has no restrictions on the length of a variable name.

Examples of correct variable names:

  • itcounter
  • $_itcounter
  • it_counter

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

You can include a double quote in a string created with a single 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 display a quote 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 $stroka_2 variable, but then assigned it the value of the $stroka_1 variable.

Concatenating Strings

Very often you need to combine several lines into one. For example, our last example is too cumbersome.

Combining (concatenating) 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 + "
" + $stroke_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 simply 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 $stroka_1 variable is in quotes, which means it is a text variable. Then we add the text and numeric variables 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. Everything is simple, there are only two values: true and false, that is, true (true) and false (false).

This data type is used in comparison operations. Here are 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 weird post, I know. But the $count variable will be equal to 2. In a mathematical context, the value of true = 1 and the value of false = 0.

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

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

In this example, a message will be displayed on the screen because the condition of the if statement ($count == 100) is true. If you change the value of the $count variable 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 looked at string, numeric and Boolean (logical) types. Here is a broader list of simple types:

  • string - string variable.
  • number - numeric variable.
  • boolean - Boolean variable.
  • null is a special value for “nothing”.
  • undefined - type “no value assigned”.

The value of a null variable forms its own separate null type, consisting of the only possible null value. null is a special value that has the meaning of "nothing" or "the value is 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 of the typeof statement could be:

  • typeof $count
  • typeof($count)

So, run the code from the last example and look at the result. The type of the variable null will be object. This is a bug in the language and will probably never be fixed due to the need to keep existing JavaScript scripts compatible with new versions of the language.

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

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<= _objKeys.length - 1; i++) { // выведем в консоль тип каждой переменной console.log(typeof _comparson[_objKeys[i]]); }

Result of executing the code:

String number number object object

Right? - Of course not. There are two problems. Each of them will be described in detail and a solution proposed.

First problem: float number, output as number

Comparison.float is not a number and number should be a float (floating point number). To fix this, you can create a function with a check as in the code below.

Var_floatNumber = 9.22; var _notFloatNumber = 9; console.log(isFloat(_floatNumber)); console.log(isFloat(_notFloatNumber)); console.log(isFloat("")); function isFloat(n)( return Number(n) === n && n % 1 !== 0; )

The isFloat() function checks that all values ​​are floating point. First, it is checked whether the variable is equal to n number (Number(n) === n) and if yes, then another check is made for division with a remainder and if there is a remainder, then a boolean ( true or false) result (n % 1 !== 0).

In the example above it returns true, false And false. The first meaning is float type, the second one is not - it's a regular number and the last one is just an empty string that doesn't fit the rules.

Second problem: the array was defined as an object

In the very first example, the array was displayed as an object and this is not very good, since sometimes you need to use exactly this type and nothing else.

There are several ways to check if a variable is an array type.

First option (good option). We check whether data belongs to an array using instanceof().

Var data = new Array("hello", "world"); var isArr = data instanceof Array;

Second option (good option). The Array.isArray() method returns a boolean value that will depend on whether the variable is an array or not ().

Var data = new Array("hello", "world"); var isArr = Array.isArray(data);

Third option (the best, but long). For convenience, you can make this method a function. Using Object we do . If the result of Object.prototype.toString.call(data) is not equal, then the variable is not an array ().

Var data = new Array("hello", "world"); var isArr = Object.prototype.toString.call(data) == ""; console.log(isArr);

The last result in the form of a convenience function:

Function isArray(data) ( return Object.prototype.toString.call(data) == "" )

Now you can call the isArray() functions and set an array or something else as an argument and see the result.

Afterword

The recording turned out to be quite large than originally intended. But I'm pleased with it because it quite succinctly and clearly describes the difficulties when checking variables in JavaScript and how to get around them.

If you still have any questions, write them below to this entry. I'll be happy to help.

Data types

Data types in JavaScript can be divided into two categories: simple types and objects. The simple types in JavaScript include numbers, text strings, and logical (or boolean) values.

The special values ​​null and undefined are elementary values, but they are not numbers, strings, or booleans. Each of them defines only one value of its own special type.

Any value in JavaScript that is not a number, string, boolean, or the special value null or undefined is an object. An object(i.e., a member of an object data type) is a collection of properties, each of which has a name and a value (either a simple type such as a number or string, or an object type).

A regular JavaScript object is an unordered collection of named values. Additionally, JavaScript has a special type of object known as array A that represents an ordered collection of numbered values. JavaScript has special syntactic constructs for working with arrays.

JavaScript defines another special type of object known as a function. Function is the object that the executable code is associated with. A function can be called to perform a specific operation and return a calculated value. Like arrays, functions behave differently than other kinds of objects, and JavaScript defines a special syntax for working with them. One of the most important things about functions in JavaScript is that they are real values, and JavaScript programs can manipulate them like regular objects.

Functions that are written to initialize newly created objects (with the new operator) are called designers. Each constructor defines object class- a set of objects initialized by this constructor. Classes can be thought of as subtypes of an object type.

In addition to classes Array And Function There are three other useful classes defined in the core JavaScript language. Class Date defines objects that represent dates. Class RegExp defines objects that represent regular expressions (a powerful pattern matching tool). And the Error class defines objects that represent syntax and run-time errors that can occur in JavaScript programs. It is possible to define your own object classes by declaring appropriate constructor functions.

Numbers

Unlike many programming languages, JavaScript does not differentiate between integer and floating-point values. All numbers in JavaScript are represented by real values ​​(floating point). JavaScript uses a standard-defined 64-bit format to represent numbers IEEE 754. This format is capable of representing numbers in the range of ±1.8 x 10308 to ±5 x 10 -324.

In JavaScript, decimal integers are written as a sequence of digits. In addition to decimal integer literals, JavaScript recognizes hexadecimal values. Hexadecimal literals begin with the character sequence "0x" followed by a string of hexadecimal digits. A hexadecimal digit is one of the numbers 0 to 9 or the letters A to F, representing values ​​10 to 15:

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

Real number literals must have a decimal point—traditional real number syntax is used to define such literals. A real value is represented as the integer part of the number, followed by the decimal point and the fractional part of the number.

Real number literals can also be represented in scientific notation: a real number followed by the letter e (or E), followed by an optional plus or minus sign and an integer exponent. This form of notation denotes a real number multiplied by 10 to the power determined by the value of the exponent:

Var a = 16.75; var b = 2e4; // 2 * 10^4 = 20,000

Arithmetic operations

Number manipulation in JavaScript is done using arithmetic operators. These operators include: the addition operator +, the subtraction operator -, the multiplication operator *, the division operator /, and the modulo % operator (returns the remainder of division).

In addition to these simple arithmetic operators, JavaScript supports more complex mathematical operations through functions and constants available as object properties Math:

Math.pow(2,53) // 2 to the power of 53 Math.round(.6) // Round to the nearest integer (result 1.0) Math.ceil(.6) // Round up (result 1.0) Math.floor( .6) // Round down (result 0) Math.abs(-5) // Modulus of number (result 5) Math.max(x,y,z) // Return the largest argument Math.min(x,y,z ) // Returns the smallest argument\ Math.random() // Pseudo-random number x, where 0

Arithmetic operations in JavaScript do not raise an error in the event of overflow, underflow, or division by zero. If the result of an arithmetic operation is greater than the largest representable value (overflow), the special value "infinity" is returned, which in JavaScript is denoted as Infinity. Likewise, if the absolute value of a negative result is greater than the largest representable value, the value "negative infinity" is returned, which is denoted by -Infinity.

These special values ​​for infinity behave exactly as you would expect: adding, subtracting, multiplying, or dividing infinity by any value results in infinity (possibly with the opposite sign).

Missing occurs when the result of an arithmetic operation is closer to zero than the minimum possible value. In this case, the number returned is 0. If loss of significant bits occurs in a negative result, a special value known as a "negative zero" is returned. This special value is virtually indistinguishable from ordinary zero, and JavaScript programmers rarely need to highlight it.

Dividing by zero is not considered an error in JavaScript: it simply returns infinity or negative infinity. However, there is one exception: the operation of dividing zero by zero does not have a clearly defined meaning, so the result of such an operation returns a special value “not-a-number”, which is denoted as NaN. NaN is also returned when attempting to divide infinity by infinity, take the square root of a negative number, or perform an arithmetic operation on non-numeric operands that cannot be converted to numbers.

JavaScript has predefined global variables Infinity and NaN that store the values ​​of positive infinity and "not a number". In the ECMAScript 3 standard, these variables are read/write and can be changed in programs. The ECMAScript 5 standard corrects this oversight and requires these variables to be read-only.

date and time

Basic JavaScript provides a Date() constructor for creating objects that represent a date and time. These Date objects have methods for performing simple calculations involving dates. The Date object is not a fundamental data type like numbers.

// Several versions of the overloaded Date() constructor new Date(); new Date(milliseconds); new Date(date_string); new Date(year, month, day, hours, minutes, seconds, ms)

The Date() constructor with no arguments creates a Date object with a value equal to the current date and time. If a single numeric argument is passed to the constructor, it is used as the internal numeric representation of the date in milliseconds, similar to the value returned by the getTime() method. When a single string argument is passed, it is treated as a string representation of the date in the format accepted by the Date.parse() method.

In addition, the constructor can be passed two to seven numeric arguments that specify individual date and time fields. All arguments except the first two - the year and month fields - may be missing. Please note: these date and time fields are set based on local time, not local time UTC (Universal Coordinated Time). Alternatively, the static Date.UTC() method can be used. Date() can also be called as a function (without the new operator). When called this way, Date() ignores any arguments passed and returns the current date and time.

Arguments passed to the Date() constructor
Argument Designation
milliseconds The number of milliseconds between the desired date and midnight January 1, 1970 (UTC). For example, passing the number 5000 as an argument will create a date that represents five seconds after midnight on January 1, 1970.
date_string A single argument that specifies the date and (optionally) time as a string. The string must be in a format that Date.parse() can understand.
year Year in four digits. For example, 2001 for 2001. For compatibility with earlier implementations of JavaScript, 1900 is added to the argument if the argument value is between 0 and 99.
month Month, specified as an integer from 0 (January) to 11 (December).
day Day of the month, specified as an integer from 1 to 31. Note that the smallest of this argument is 1, and the remaining arguments are 0. Optional argument.
watch Hours, specified as an integer from 0 (midnight) to 23 (11 pm). Optional argument.
minutes Minutes in hours, specified as an integer from 0 to 59. Optional argument.
seconds Seconds in minutes, specified as an integer from 0 to 59. Optional argument.
ms Milliseconds in a second, specified as an integer from 0 to 999. Optional argument.

The Date object has no writable or readable properties; instead, date and time values ​​are accessed through methods. Most Date object methods have two forms: one for working with local time, the other for working with universal time (UTC or GMT). If the method name contains the string "UTC", it works with universal time.

Date object methods can only be called on objects of type Date, and will throw a TypeError exception if called on objects of another type.

Date object methods
Method Description
getDate(), getUTCDate(), setDate(), setUTCDate() Returns/sets the day of the month from a Date object according to local or universal time.
getDay(), getUTCDay() Returns the day of the week from a Date object according to local or universal time.
getFullYear(), getUTCFullYear(), setFullYear(), setUTCFullYear() Returns/sets the year of a date in full four-digit format in local or universal time.
getHours(), getUTCHours(), setHours(), setUTCHours() Gets/sets the hour field in a Date object in local or universal time.
getMilliseconds(), getUTCMilliseconds(), setMilliseconds(), setUTCMilliseconds() Gets/sets the milliseconds field in a Date object in local time or universal time.
getMinutes(), getUTCMinutes(), setMinutes(), setUTCMinutes() Gets/sets the minutes field in a Date object in local or universal time.
getMonth(), getUTCMonth(), setMonth(), setUTCMonth() Gets/sets the month field in a Date object in local or universal time.
getSeconds, getUTCSeconds(), setSeconds, setUTCSeconds() Gets/sets the seconds field in a Date object in local or universal time.
getTime(), setTime() Gets/sets the internal representation (milliseconds) of a Date object. Note that this value is not time zone specific, so a separate getUTCTime() method is not needed.
getTimezoneOffset() Returns the difference in minutes between the local and universal date representations in minutes. Note that the value returned depends on whether the specified date is in daylight saving time.
getYear(), setYear() Gets/sets the year field in a Date object. Deprecated, it is recommended to use the getFullYear() and setFullYear() methods instead..
toDateString() Returns a string representing a date from Date for the local time zone.
toGMTString() Converts a Date to a string using the GMT time zone. Deprecated, the toUTCString() method is recommended instead.
toISOString() Converts Date to a string using the ISO-8601 standard, which combines date/time and UTC formats.
toJSON() Serializes a Date object into JSON format using the toISOString() method.
toLocaleDateString() Returns a string representing a date from Date in the local time zone, according to local date formatting conventions.
toLocaleString() Converts Date to a string according to the local time zone and local date formatting conventions.
toLocaleTimeString() Returns a string representing the time from Date in the local time zone, based on local time formatting conventions.
toString() Converts Date to a string according to the local time zone.
toTimeString() Returns a string representing the time from Date in the local time zone.
toUTCString() Converts a Date to a string using Universal Time.
valueOf() Converts a Date object to its internal millisecond format.

In addition to the listed instance methods, the Date object defines three static methods. These methods are called through the Date() constructor itself, rather than through individual Date objects:

Date.now()

Returns the current time in milliseconds.

Date.parse()

Parses a string representation of a date and time and returns the internal representation of that date in milliseconds.

Date.UTC()

Returns a representation of the specified UTC date and time in milliseconds.

The Date object is a data type built into the JavaScript language. Date objects are created using the new Date() syntax introduced earlier.

Once a Date object is created, you can use its many methods. Many of the methods allow you to get and set the year, month, day, hour, minute, second, and millisecond fields according to either local time or UTC (universal time, or GMT) time. The toString() method and its variants convert dates into human-readable strings.

getTime() and setTime() convert the number of milliseconds that have passed since midnight (GMT) January 1, 1970, to and from the Date object's internal representation. In this standard millisecond format, the date and time are represented as one unit, making the date very simple arithmetically. The ECMAScript standard requires that a Date object can represent any date and time with millisecond precision within 100 million days before and after 01/01/1970. This range is ±273,785 years, so the JavaScript clock will work correctly up to 275,755 years.

Examples of using the Date object

There are many known methods that allow you to work with the created Date object:

// Gets the current date and time d = new Date(); // Shows the date document.write("Today: " + d.toLocaleDateString() + "."); // Shows the time document.write("Time: "+ d.toLocaleTimeString()); // Day of the week var dayOfWeek = d.getDay(); // Today is a day off? var weekend = (dayOfWeek == 0) || (dayOfWeek == 6);

Below is a simple example of a clock using a Date object. This uses the setTimeout() method to update the clock every second:

Function timer() ( // Find element h1 in the document h1 = document.getElementsByTagName("h1"); // Set the date var date = new Date(); var hours = date.getHours(); var minutes = date.getMinutes (); var seconds = date.getSeconds(); if (hours

The page markup is quite simple and includes the timer() function in the onload() event handler of the body element:

Strings

A string is an immutable, ordered sequence of 16-bit values, each of which typically represents a Unicode character. Strings in JavaScript are a data type used to represent text. The length of a string is the number of 16-bit values ​​it contains. Numbering of characters in strings (and elements in arrays) in JavaScript starts from zero: the first 16-bit value is at position 0, the second at position 1, etc. An empty string is a string whose length is 0.

JavaScript does not have a special type to represent a single element of a string. To represent a single 16-bit value, a string with a length of 1 is simply used.

To include a string literal in a JavaScript program, simply enclose the string characters in paired single or double quotes (" or "). Double quote characters can be contained in strings delimited by single quote characters, and single quote characters can be contained in strings delimited by double quote characters. Below are some examples of string literals:

Var str = ""; // Empty string str = "simple string"; str = "string with "quotes" inside"; str = "This string literal has two strings";

In ECMAScript 3, string literals must be written on one line of the program and cannot be split into two lines. However, in ECMAScript 5, string literals can be split across multiple lines by ending each line except the last with a backslash character (\). None of the backslash characters, nor the following line feed characters, will be included in the string literal. To include a newline character in a string literal, you must use the character sequence \n (as shown above).

The backslash character (\) has a special purpose in JavaScript strings. Together with the characters that follow it, it denotes a character that cannot be represented within a string in other ways. For example, \n is escape sequence, indicating a newline character.

Another example is the sequence \", which represents the single quote character. This escape sequence is needed to include a single quote character in a string literal enclosed in single quotes. Now it becomes clear why we call these escape sequences - here the backslash character allows you to control the interpretation of the character single quote. Instead of marking the end of the line, we use it as an apostrophe:

Var str = "\"JavaScript\" is an interpreted programming language";

The table below lists JavaScript escape sequences and the characters they represent. The two escape sequences are general; they can be used to represent any character by specifying the character's Latin-1 or Unicode code as a hexadecimal number. For example, the sequence \xA9 denotes a copyright symbol, which in Latin-1 encoding has the hexadecimal code A9. Similarly, an escape sequence starting with \u characters denotes an arbitrary Unicode character specified by four hexadecimal digits. For example, \u03c0 represents the symbol π.

JavaScript escape sequences
Subsequence Represented symbol
\0 NUL character (\u0000)
\b Reverse movement (\u0008)
\t Horizontal tab (\u0009)
\n Line feed (\u000A)
\v Vertical tab (\u000B)
\f Page translation (\u000C)
\r Carriage return (\u000D)
\" Double quote (\u0022)
\" Single quote (\u0027)
\\ Backslash (\u005C)
\xZZ Latin-1 character specified by two hexadecimal digits ZZ
\uxZZZZ Unicode character specified by four hexadecimal digits ZZZZ

If the "\" character is preceded by any character other than those listed in this table, the backslash is simply ignored (though future versions may, of course, define new escape sequences). For example, \# is the same as #. Finally, as noted above, the ECMAScript 5 standard allows you to add a backslash character before the line break in multiline string literals.

Working with Strings

One of the built-in features of JavaScript is the ability to concatenate strings. If the + operator is applied to numbers, they are added, and if applied to strings, they are combined, with the second line added to the end of the first. For example:

Var str = "Hello, " + "world!"; // This produces the string Hello, world! // Concatenation of a string with a variable var name = "Alexander"; str = "Welcome, " + name + "!";

Strings in JavaScript are represented by an object String, which has one constructor in which a string is passed. When the String() function is called as a constructor (with the new operator), it returns a String object containing the string s or a string representation of s. The String() constructor, called without the new operator, converts s to an elementary string value and returns the converted value:

New String(s); // Constructor function String(s); // Conversion function

The String object has a single property - length, which returns the number of characters in the string.

The following table lists the methods of the String object:

String class methods
Method Description Usage example
charAt() Extracts the character at the specified position from a string. The number of the first character in the line is zero. var str = "Hello, world!"; document.write(str.charAt(4)); // Result "o"
charCodeAt() Returns the code of the character located at the specified position. (The Unicode code of the nth character in the line is a 16-bit integer between 0 and 65535.) var str = "Hello, world!"; document.write(str.charCodeAt(4)); // Result 111 - character code "o"
concat() Concatenates one or more values ​​with a string. concat() converts all of its arguments to strings (if needed) and appends them in order to the end of the string. Returns the resulting concatenated string. // Get one string (new String()).concat("We are glad", "welcome", "you to our website");
indexOf(substring, start) Searches a string from beginning to end to see if it contains the searched substring. The search begins at the "start" position in the string, or at the beginning of the string if the "start" argument is not specified.

If the substring is found, String.indexOf() returns the position of the first character of the first occurrence of the substring in the string. Character positions in a line are numbered starting from zero. If the substring is not found in the string, String.indexOf() returns -1.

var str = "Hello, world!"; if (str.indexOf("world", 0) != -1) document.write("The substring \"world\" was found in the source string.");
lastIndexOf() Searches for a character or substring in a string from the end. var str = "Hello, world!"; document.write("Position of the last letter "o" in the source string: " + + str.lastIndexOf("o")); // Result 8
localeCompare() Compares strings taking into account the order of characters in national alphabets. Returns a number indicating the result of the comparison. If the string is "less than" the target string, localeCompare() returns a negative number. If the string is "greater than" the target string, the method returns a positive number. If the strings are identical or indistinguishable according to regional collation conventions, the method returns 0.

When operators are applied to strings, comparisons are made only by the Unicode codes of those characters; The current region's sort order is not taken into account. Sorting done this way is not always correct.

The ECMAScript standard does not specify how region-specific comparisons should be performed; it simply states that the function follows the sort order defined by the operating system.

var str1 = "String1"; var str2 = "String2"; if (str1.localeCompare(str2) != 0) document.write("Strings are not identical");
match() Performs a pattern search using a regular expression. var str = "1 plus 2 equals 3".match(/\d+/g); // Return an array ("1", "2", "3")
replace() The replace() method performs a find and replace operation on a string. It searches a string for one or more substrings that match a regular expression and replaces them.

If the global attribute "g" is specified in the regular expression, replace() replaces all substrings found. Otherwise, the method replaces only the first substring found.

The ECMAScript v3 standard specifies that the second argument of the replace() method can be a function rather than a string. In this case, the function will be called for each match found, and the string it returns will be used as the replacement text.

var str = "javascript is an interpreted programming language."; // Ensure the correct case of letters in the word "JavaScript" str = str.replace(/JavaScript/i, "JavaScript");
search() The search() method searches for a substring in a string that matches the regular expression regexp and returns the position of the first character of the substring found, or -1 if no match is found.

The method does not perform a global search, ignoring the "g" flag. It also ignores the regexp.lastIndex property and always searches from the beginning of the string, hence always returning the position of the first match found in the string.

var str = "JavaScript is an interpreted programming language."; i = str.search("language"); // Result 30 (position of the word "language" in the source string)
slice() The slice() method returns a string containing a fragment, or a substring of a string, but does not modify the string.

The first argument is the index in the line at which the fragment should begin. If this argument is negative, it denotes the position measured from the end of the string. That is, -1 corresponds to the last character, -2 to the second from the end, etc.

The second argument is the character index of the source string immediately after the end of the extracted fragment. If not specified, the fragment includes all characters from the beginning to the end of the line. If this argument is negative, it denotes the position counted from the end of the line.

var str = "abvgdezzik"; str1 = str.slice(0,4); // Return "abvg" str2 = str.slice(2,4); // Return "vg" str3 = str.slice(4); // Return "dezzik" str4 = str.slice(3,-1); // Return "where" str5 = str.slice(3,-2); // Return "where" str6 = str.slice(-4,-2); // Return "zhz"
split() Splits a string into an array of strings at the specified delimiter string.

The split() method creates and returns an array of substrings of the specified string, and the size of the returned array does not exceed the specified limit (passed in the second argument). These substrings are created by searching the string for text matching the delimiter (first argument) from start to finish, and splitting the string before and after the found text. Bounding text is not included in any of the returned rows.

// The split() method is most useful when working // with highly structured strings var str = "1:2:3:4:5"; str.split(":"); // Return ["1","2","3","4","5"] str = "a||b||c"; str.split("||"); // Return ["a","b","c"] // To split the string into an array of characters, // take the empty string as a delimiter str = "hello"; str.split(""); // Return ["h","e","l","l","o"] str.split("",3); // Return ["h","e","l"]
substr() The substr() method extracts and returns a substring of a string, but does not modify the string. Note that the substr() method specifies the desired substring using character position and length. This provides a convenient alternative to the String.substring() and String.splice() methods, in which a substring is specified by two character positions. However, it should be noted that the method is not standardized in ECMAScript and is therefore considered obsolete. var str = "abvgdezzik"; str = str.substr(2,5); // Result "where"
substring() The String.substring() method returns a substring of a string containing the characters between positions from (first argument) to (second argument). The character at position "from" is included in the substring, but the character at position "to" is not included. var str = "abvgdezzik"; str = str.substring(2,7); // Result "where"
toLowerCase() Returns a copy of the string with all characters converted to lowercase. var str = "JavaScript"; str = str.toLowerCase(); // Result "javascript"
toString() Returns a primitive string value. Calling this method is rarely needed. A TypeError exception is thrown if a method is called on an object that is not a String object.
toUpperCase() Returns a copy of the string with all characters converted to uppercase. var str = "JavaScript"; str = str.toUpperCase(); // Result "JAVASCRIPT"
trim() Returns a copy of the string with all leading and trailing whitespace characters removed.
valueOf() Returns a primitive string value (similar to toString(), rarely used).

Since the early days of JavaScript, the String class has defined several methods that return a string modified by adding HTML tags to it. These methods were never standardized in ECMAScript, but they allow you to dynamically generate HTML markup in both client- and server-side JavaScript scripts. If you're willing to use custom techniques, you can create the HTML markup for the hyperlink in green bold font as follows:

Because these methods are not standardized, there are no separate reference articles for them.

Boolean values

A logical value tells whether something is true or false. The Boolean data type has only two valid Boolean values. These two values ​​are represented by the literals true and false.

Boolean values ​​typically represent the result of comparison operations performed in JavaScript programs. For example:

This expression tests whether the value of the variable a is equal to the number 4. If so, the result of this comparison will be the Boolean value true. If the value of a is not 4, the result of the comparison will be false.

Boolean values ​​are commonly used in JavaScript control constructs. For example, the if/else statement in JavaScript performs one action if a boolean value is true and another action if false. Typically, the comparison that produces a boolean value is directly combined with the instruction in which it is used. The result looks like this:

If (a == 4) ( // ... ) else ( // ... )

Any value in JavaScript can be converted to a boolean value. The following values ​​result in a boolean value (and then behave as) false:

Undefined null 0 -0 NaN "" // empty string

All other values, including all objects (and arrays), result in (and act as) true when converted. The value false and the six values ​​that are converted to that value are sometimes called false, and all the others are called true. In any context where the JavaScript interpreter expects to receive a boolean value, false values ​​are interpreted as false and true values ​​are interpreted as true.

Boolean values ​​have a toString() method that can be used to convert those values ​​to "true" or "false" strings, but they have no other useful methods.

Null and undefined values

The null keyword in JavaScript has a special purpose and is typically used to indicate the absence of a value. The typeof operator for a null value returns the string "object", which indicates that the null value is a special "empty" object. However, in practice, null is usually considered the only member of its own type and can be used to indicate the absence of a value, such as a number, string, or object. Most other programming languages ​​have values ​​similar to null in JavaScript: you may know them as null or nil.

JavaScript has another value that indicates the absence of a value. An undefined value indicating the complete absence of any value. It is returned when accessing a variable that has never been assigned a value, a non-existent object property, or an array element. Additionally, undefined is returned by functions that do not have a return value, and is assigned to function parameters for arguments that were not passed to the call.

The identifier undefined is the name of a predefined global variable (not a keyword like null) that is initialized with the value undefined. In ECMAScript 3, undefined is a read/write variable that can be assigned any other value. This issue was fixed in ECMAScript 5, and in JavaScript implementations that follow this standard, the undefined variable is read-only. The typeof operator on an undefined value returns the string "undefined", indicating that the value is the only member of a special type.

Despite these differences, both null and undefined indicate the absence of a value and are often used interchangeably. The equality operator == considers them equal. (You can use the identity operator === to differentiate them in your program.) Both of these are false values—in a Boolean context, they are interpreted as false. Neither null nor undefined have any properties or methods. In practice, an attempt to use. or to access a property or method of these values ​​raises a TypeError.

The value undefined can be considered as a sign of an unexpected or erroneous absence of a value, and null as a sign of a normal or quite expected absence of a value. If your program needs to assign one of these values ​​to a variable or property, or pass one of these values ​​to a function, it is almost always preferable to use null.

Immutable simple values ​​and references to mutable objects

There are fundamental differences between simple values ​​(undefined, null, booleans, numbers, and strings) and objects (including arrays and functions) in JavaScript. Simple values ​​are immutable: a simple value cannot be changed. This is obvious for numbers and booleans - there is no point in changing the value of a number.

However, for strings this is less obvious. Since strings are arrays of characters, it would be natural to expect that it would be possible to change characters at one position or another in a string. JavaScript doesn't actually allow you to do this, and all string methods that appear to return a modified string actually return a new string value. For example:

Var str = "simple string"; str.slice(8,14); console.log(str); // Displays a "simple string" // To explicitly change the string you need to use the assignment str = str.slice(8,14); console.log(str); // Display "string"

In addition, values ​​of simple types are compared by value: two quantities are considered the same if they have the same value. For numbers, booleans, null and undefined this seems obvious: there is no other way to compare them. However, for strings this statement does not seem so obvious. When comparing two string values, JavaScript considers them the same if and only if they are the same length and contain the same characters in the corresponding positions.

Objects are different from simple types. First, they are mutable - their values ​​can be changed:

Var o = ( x:1 ); // Initial value of the object o.x = 2; // Change by changing the property value o.y = 3; // Change by adding a new property var a = ; // Arrays are also mutable objects a = 0; // Change the value of the first element of the array a = 4; // Add a new element (index 3 corresponds to the fourth position in the array)

Objects are not compared by value: two objects are not considered equal, even if they have the same set of properties with the same values. And two arrays are not considered equal even if they have the same set of elements in the same order.

To emphasize the difference from simple JavaScript types, objects are sometimes called reference types. Following this terminology, the values ​​of objects are references, and objects can be said to be compared by reference: the values ​​of two objects are considered equal if and only if they refer to the same object in memory.

Var a = ; // Variable a refers to an empty array. var b = a; // Now b refers to the same array. b = 1; // Modify the array using a reference in the variable b. console.log(a === b); // Return "true" console.log("a = " + a); // Changing object b changes object a

As the example above suggests, assigning an object (or array) to a variable actually assigns a reference: it does not create a new copy of the object. If your program needs to create a new copy of an object or array, you will need to explicitly copy the object's properties or array elements.

As computer programs operate, they manipulate values ​​such as the number 7 or the text "HelloWorld!" Each value that can be represented and processed in a programming language belongs to a specific data type. A data type defines the types of values ​​that are used in a programming language.

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

  • string- text strings (usually they are simply called strings)
  • number- numbers
  • boolean- logical (Boolean) values

Two special values ​​also belong to simple types:

  • null
  • undefined

Composite data types include:

  • function- functions
  • array- arrays
  • object- objects

Difference between simple and compound types

The difference between simple and composite types occurs when values ​​are copied.

When a variable (function parameter, property, or array element) is assigned a value of a simple type, such as a number, the value itself (in this case, the number) is written to the variable. When you assign one variable (with a value of a simple type) to another variable, the value is copied. As a result, each variable has its own copy of the value and changes in one of the variables do not affect the value of the other:

Var num1 = 10; var num2 = num1; // Copy the value alert("num1: " + num1 + // 10 "\nnum2: " + num2); // 10 num1 = 15; // Change the value alert("num1: " + num1 + // 15 "\nnum2: " + num2); // 10

When a variable (function parameter, property, or array element) is assigned a value of a complex type, such as an object, a reference to the value (in this case, a reference to the object) is written to the variable. When you 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 any changes made to the value of one of the variables will affect the other variable:

Var o1 = (x:10); var o2 = o1; // Copy the link to the object alert("o1.x: " + o1.x + // 10 "\no2.x: " + o2.x); // 10 o2.x = 15; // Change the value alert("o1.x: " + o1.x + // 15 "\no2.x: " + o2.x); // 15

null and undefined

The null type has only one value - null . The value null is a reference to an empty object and has a special purpose - it is usually used to initialize a variable to which the object will later be assigned.

The undefined type has only one value - undefined . The value undefined indicates that there is no value to begin with. You can get the undefined value as follows:

  • When accessing a variable that has been declared but not initialized.
  • When accessing a non-existent property of an object.
  • When accessing a non-existent array element.
  • When accessing function parameters that were not initialized with arguments when the function was called.
  • Returned by functions that do not have a return value.
  • Returned by the typeof operator if the operand is a non-existent variable.
var bar; document.write(bar); Try »

The identifier undefined is the name of a predefined global variable that is initialized with the value undefined . The undefined variable is read-only.

Wrapper objects

Whenever a program attempts to access a property or method of a value of a primitive type, the interpreter temporarily converts the primitive value to an object of the appropriate type. Temporary objects into which values ​​of a primitive type are converted are called wrapper objects. These objects are used by the interpreter to access the desired property or method. Immediately after calling a property or method, the wrapper object is destroyed. Wrapper objects are created only for values ​​of type number , string , and boolean . The values ​​null and undefined do not have wrapper objects: any attempt to access the properties of these values ​​will generate an error.

If you try to set a new property for a wrapper object, the new property will not be saved, since the wrapper object is destroyed immediately after it has completed its work:

Var str = "text"; str.len = 5; // Set a property with a value. Immediately after this, the object is destroyed alert(str.len); // undefined, since the previous wrapper object has already been destroyed

Wrapper objects can simply be seen as a convenience implementation for working with values ​​of a primitive type and not thought about at all.

OS