Variable types in javascript. Data Types

Last update: 03/26/2018

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

    String: represents a string

    Number: represents a numeric value

    Boolean: represents the Boolean value true or false

    undefined : indicates that the value is not set

    null : indicates an undefined value

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

Numeric data

Numbers in JavaScript can take two forms:

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

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

For example:

Var x = 45; var y = 23.897;

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

Strings

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

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

Var companyName = "Horns and Hooves Bureau";

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

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

Type Boolean

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

Var isAlive = true; var isDead = false;

null and undefined

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

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

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

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

object

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

Var user = ();

An object can have various properties and methods:

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

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

Weak typing

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

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

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

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

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

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

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

typeof operator

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

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

Lesson #3
Data types in JavaScript

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

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

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

typeof operator

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

Alert(typeofVariablename);

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

Data type: number

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

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

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

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

Data type: string

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

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

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

Data type: logical data type (boolean)

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

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

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

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

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

Data type: undefined

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

Var myUndefined; alert(typeof myUndefined);

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

Accessing a variable's value

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

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

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

A variable is a named memory location in which you can both store some information and retrieve it from it.

Declaring (creating) variables is done using the var keyword.

// message - variable name var message;

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

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

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

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

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

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

Var price = 78.55, quantity = 10, message;

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

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

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

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

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

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

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

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

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

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

But creating variables in this way is not recommended.

Data Types

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

Variables containing primitive data types store their value explicitly.

There are 5 primitive data types in JavaScript:

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

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

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

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

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

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

Number

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

Var int = 5; // integer var float = 5.98; // 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 number system, but also in octal (0) or hexadecimal number system (0x) using the prefixes specified in parentheses:

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

Numbers can be written 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

The numeric data type contains, in addition to numbers, 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, the result of which will be: special numeric values ​​returned:

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

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

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

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

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

Boolean data type

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

Var a = true; var b = false;

String

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

A JavaScript string can be 0 or more characters long.

JavaScript always uses Unicode as its string format.

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

"JavaScript"; "ECMAScript";

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

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

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

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

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

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

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

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

The value is "undefined"

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

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

Var num; // undefined

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

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

"null" value

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

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

Object

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

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

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

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

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

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

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

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

// display the value of the age property in the browser console // 1st way (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; // "number" typeof interest; / "object" (1) typeof lastExperience; // "object" typeof getExperience; // "function" (2) /* (1) - this is a bug that has been present in the language since its first implementation; 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 selects functions separately, but a function in JavaScipt is also a function; 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";

In almost any programming language there are various variable types and JavaScript there are no surprises here. As a rule, this is a standard set of types: integer ( integer), real ( double), string ( string), boolean( boolean) and array ( array). Let's look at each one variable type in JavaScript more details.

First, let's immediately note that a variable of any type begins with the keyword " var", and only the value of the variable determines the type of the variable. Moreover, the type of the variable in JavaScript can be changed at any point in the program.

Let's start with the simplest one - a whole type that is familiar to us from the previous article. The integer type is a regular integer, such as -100, -34, 0, 15, 259, and so on. Accordingly, an integer type is created by assigning an integer value to a variable, for example, like this:

Var number = -323;

The next type of variable is the real type, or, as it is commonly called, double. Type double- these are real numbers, that is, absolutely any numbers except imaginary ones (if you don’t know what imaginary numbers are, then don’t pay attention to it). For example, -3.4, -1.032, 35.599212, 0.0001. As with other types, to create a real variable you must initialize the variable to one of these values. Here's an example:

Var number = 32.3291;

Please note that the integer part is not separated from the fractional part " comma" (as is customary with us), and " dot".

The next variable type is string. String type in JavaScript is used very often, no less often than others, if not more. A string type is any kind of string. For example, this is: "string", "732", "My name"s Michael". Please note that the string is specified in quotes. In particular, the string "732" is different from the number 732. The string is created in the same way as the others types in JavaScript:

Var str = "some string";

Another type of variable is Boolean. The type of this variable can contain one of two values: true(true) or false(lie). The variable is used in conditional statements, which we'll talk about later. In the meantime, an example of creating a Boolean variable:

Var bool = true;

And the last type is an array. The most complex type of all, however, it is very important and is present in almost all programming languages. This is a type that contains several different variables, and possibly even different types. An array is created in JavaScript Thus:

Var array = new Array(3, 7, 12, true, 4.5, "some string", true);

The example creates an array of 7 values ​​that can be read or overwritten. The question arises: how to access an array element. Very simple! The syntax for accessing an array element is as follows: array_name[element_number]. Please note that the numbering in the array starts with " 0 ". Therefore the element with the value " 3 " is the element numbered " 0 ". As an example, I will show how you can display an array element in a browser window and overwrite it.

Document.write(array);
array = array + 1;
document.write(array);

I advise you to run this script to finally understand arrays, because without this type of variable programming is unthinkable, even in JavaScript.

This is all JavaScript variable types.

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. 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 time 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 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. The 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 the 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 a single quote, instead of marking the end of a 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 a primitive 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 distinguish them in your program.) Both 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.