📜 ⬆️ ⬇️

Expressive JavaScript: Values, Types and Operators

Content




Under the surface of the machine moves the program. Without effort, it expands and shrinks. Being in great harmony, the electrons are scattered and collected. Forms on the monitor - only ripples on the water. The essence remains hidden inside ...

Master Yuan-Ma, Book Programming

In the computer world there is only data. You can read data, change data, create new ones - but there is nothing but data. All data is stored as long sequences of bits, they are similar to each other.
')
Bits are two-state entities, usually described as zeros and ones. In the computer, they live in the form of high and low electric charges, a strong or weak signal, or a shiny and matte area on the CD surface. Each piece of information can be represented as a sequence of zeros and ones, that is, a bit.

For example, number 13. Instead of a decimal system consisting of 10 digits, you have a binary system with two digits. The value of each position of the number doubles when moving from right to left. The bits that make up the number 13, along with their weights:

0 0 0 0 1 1 0 1 128 64 32 16 8 4 2 1 


It turns out the binary number is 00001101, or 8 + 4 + 1, which is 13.

Values.


Imagine the ocean bit. A typical modern computer stores more than 30 billion bits in RAM. Permanent memory (hard disk) is usually a few more orders of magnitude.


To work with them and not get lost, you can divide them into pieces, representing units of information. In JavaScript, these units are called quantities. All their meanings consist of bits, but they play different roles. Each value has a type that determines its role. There are six basic types in total: numbers, strings, booleans, objects, functions, and undefined values.

To create a value, you need to specify its name. It's comfortable. You do not need to collect building materials or pay for them. You just need to call - and op-pa, ready. They are not created from air - every quantity is stored somewhere, and if you want to use a huge amount of them, you may run out of bits. Fortunately, it is only if you need them all at the same time. When you do not need a value, it is dissolved, and the bits it uses are recycled as building material for new values.

In this chapter, we familiarize ourselves with the atoms of JavaScript programs — simple types of values ​​and operators that apply to them.

Numbers


Values ​​of numeric types, this is a surprise - numbers. In JavaScript, they are written as

 13 


Use this entry in the program, and it will bring to life in the computer memory a string of bits representing the number 13.

JavaScript uses a fixed number of bits (64) to store numerical values. The number of quantities that can be expressed using 64 bits is limited — that is, the numbers themselves are also limited. For N decimal digits, the number of numbers that they can write is 10 to the power of N. Similarly, 64 bits can express 2 to the power of 64 numbers. This is quite a lot.

Previously, computers had less memory, and then groups of 8 or 16 bits were used to store numbers. It was easy to accidentally exceed the maximum number for such small numbers — that is, use a number that did not fit into this set of bits. Today computers have a lot of memory, you can use pieces of 64 bits each, and that means that you need to worry about this only if you work with astronomical numbers.

True, not all numbers less than 2 ^ 64 fit into the JavaScript number. Negative numbers are also stored in these bits - so one bit stores the sign of the number. In addition, we need to be able to store fractions. For this part of the bit is used to store the position of the decimal point. The real maximum for numbers is about 10 ^ 15, which is generally still quite a lot.

Fractions are written using a point.

 9.81 


Very large or small numbers are written with a scientific note with the letter “e” (exponent), followed by a degree:

 2.998e8 


This is 2.998 Ă— 10 ^ 8 = 299800000.

Calculations with integers (also called integer) smaller than 10 ^ 15 are guaranteed to be accurate. Fractional calculations are usually not. Just as the number π (pi) cannot be represented exactly with the help of a finite number of digits, so many fractions cannot be represented in the case when we have only 64 bits. Bad, but it interferes in very specific cases. It is important to keep this in mind and treat fractions as approximate values.

Arithmetic


The main thing you can do with numbers is arithmetic calculations. Additions and multiplications use two numbers and produce the third. How it is written in javascript:

 100 + 4 * 11 


The symbols + and * are called operators. The first is addition, the second is multiplication. Place the operator between two values ​​and get the value of the expression.

And in the example, it turns out to “add 4 and 100 and then multiply the result by 11" or is the multiplication performed first? As you might have guessed, multiplication is done first. But as in mathematics, this can be changed using parentheses:

 (100 + 4) * 11 


For subtraction, the - operator is used, and for division - /

When operators are used without brackets, the order of their execution is determined by their priority. Operators * and / priority are the same, higher than that of + and -, which are equal in priority to each other. When calculating operators with equal priority, they are calculated from left to right:

 1 - 2 + 1 

calculated as (1 - 2) + 1

While there is no need to worry about priorities. If in doubt, use brackets.

There is another operator that you do not immediately recognize. The% symbol is used to get the remainder. X% Y is the remainder of dividing X by Y. 314% 100 gives 14, and 144% 12 gives 0. Operator priority is the same as multiplication and division. It is often referred to as “modulo division”, although more correctly “with the remainder”.

Special numbers


In JavaScript, there are three special values ​​that are considered numbers, but do not behave like ordinary numbers.

These are Infinity and -Infinity , which represent positive and negative infinity. Infinity - 1 = Infinity, and so on. Do not rely heavily on calculations with infinities, they are not too strict.

The third number: NaN . Indicates “not a number” (not a number), although it is a numeric value. You can get it after calculating the type of 0/0, Infinity - Infinity, or other operations that do not lead to accurate meaningful results.

Strings


The next base data type is strings. They are used to store text. They are written in quotes:

 “ ,   ” '  ,  ' 


You can use both double and single quotes - the main thing is to use them together. Almost everything can be enclosed in quotes and make a string out of it. But some characters cause problems. For example, it is difficult to enclose quotes in quotes. A line break is also impossible just to conclude in them - the line should go in one line.

For the conclusion of special characters the backslash \ is used. It means that the character following it has a special meaning - this is called an “escape character”. \ ”Can be enclosed in double quotes. \ n stands for a line break, \ t means a tab.

The line “Between the first and second \ nsymbol will be small” will actually look like this:

        


If you need to include a backslash in the string, it should also be escaped: \\. The instruction “Newline character is“ \ n ”” will need to be written like this:

 "   –  \"\\n\"" 


Strings cannot be divided, multiplied and added. However, the + operator can be used with them, which will connect them with each other. The following expression will produce the word "connection":

 "" + "" + "" + "" 


There are many ways to manipulate strings, which we discuss in chapter 4.

Unary operators


Not all operators are written in characters — some words. One of these operators is typeof , which gives the name of the type of value to which it is applied.

 console.log(typeof 4.5) // → number console.log(typeof "x") // → string 


We will use the console.log call in the examples when we want to see the result on the screen. How exactly the result will be displayed depends on the environment in which you run the script.

Previous operators worked with two values, however typeof uses only one. Operators working with two quantities are called binary, and with one they are called unary. The minus (subtraction) can be used both as unary and binary.

 console.log(- (10 - 2)) // → -8 


Boolean values


Often you need a value that simply shows one of two possibilities — such as “yes” and “no”, or “on” and “off”. For this, JavaScript has a Boolean type, which has only two values ​​- true and false (true and false).

Comparisons


One way to get boolean values ​​is:

 console.log(3 > 2) // → true console.log(3 < 2) // → false 


The signs <and> traditionally denote "less" and "more." These are binary operators. As a result of their use, we get a Boolean value that indicates whether the inequality is true.

Lines can be compared in the same way:

 console.log("" < "") // → true 


Lines are compared alphabetically: uppercase letters are always “less than” lowercase letters. The comparison is based on the Unicode standard. This standard assigns a number to almost any character from any language. While comparing strings, JavaScript runs along their characters from left to right, comparing the number codes of these characters.

Other similar operators are> = (greater or equal), <= (less or equal), == (equal),! = (Not equal).

 console.log("" != "") // → true 


In JavaScript, there is only one value that is not equal to itself — NaN (“not a number”).

 console.log(NaN == NaN) // → false 


NaN is the result of any meaningless calculation, so it is not equal to the result of some other meaningless calculation.

There are operations that can be performed with the Boolean values ​​themselves. JavaScript supports three logical operators: and, or, no.

The && operator is a logical “and”. It is binary, and its result is true only if both quantities to which it is applied are also true.

 console.log(true && false) // → false console.log(true && true) // → true 


Operator || - logical "or". Returns true if one of the values ​​is true.

 console.log(false || true) // → true console.log(false || false) // → false 


“No” is recorded with the exclamation mark “!”. This is a unary operator that reverses the given value. ! true turns out false! false turns out true.

When using logical and arithmetic operators it is not always clear when brackets are needed. In practice, you can deal with this, knowing that || priority is lower than all, then goes &&, then comparison operators, then all the rest. Such an order was chosen so that minimum expressions can be used in the following type of expressions:

 1 + 1 == 2 && 10 * 10 > 50 


The last logical operator is not unary and not binary - it is triple. It is written with a question mark and a colon:

 console.log(true ? 1 : 2); // → 1 console.log(false ? 1 : 2); // → 2 


This is a conditional operator whose value to the left of the question mark selects one of two values ​​separated by a colon. When the value on the left is true, select the first value. When false, the second.

Undefined values


There are two special values, null and undefined, which are used to indicate the absence of a meaningful value. By themselves, they do not carry any information.

Many operators that do not return a value return undefined simply to return something. The difference between undefined and null appeared in the language by chance, and usually does not matter.

Automatic type conversion


Earlier, I mentioned that JavaScript allows you to run any, sometimes very strange program. For example:

 console.log(8 * null) // → 0 console.log("5" - 1) // → 4 console.log("5" + 1) // → 51 console.log("" * 2) // → NaN console.log(false == 0) // → true 


When the statement is applied to the “wrong” type of values, JavaScript quietly converts the value to the desired type using a set of rules that do not always meet your expectations. This is called coercion. In the first expression, null turns into 0, and “5” becomes 5 (from a string to a number). However, in the third expression, + performs concatenation (union) of strings, because of which 1 is converted to “1 '(from number to string).

When something non-obvious turns into a number (for example, “five” or undefined), the value NaN is returned. Subsequent arithmetic operations with NaN again get NaN. If you get this value, look for where the random type conversion occurred.

When comparing values ​​of the same type through ==, it is easy to predict that you should get true if they are the same (except in the case of NaN). But when the types are different, JavaScript uses a complex and confusing set of rules for comparisons. Usually he tries to convert the type of one of the values ​​to the type of the other. When a null or undefined occurs on one side of the statement, it returns true if both sides are null or undefined.

 console.log(null == undefined); // → true console.log(null == 0); // → false 


The last example demonstrates a useful technique. When you need to check if a value has a real value instead of null or undefined, you simply compare it with null with == or! =.

But what if you need to compare something with the exact value? The rules for converting types to boolean values ​​say that 0, NaN and the empty string “” are considered false, and all others are true. Therefore, 0 == false and “” == false. In cases where you do not need automatic type conversion, you can use two more operators: === and! ==. The first one checks that the two values ​​are absolutely identical, the second one is vice versa. And then the comparison “” === false returns false.

I recommend using three-character comparison operators to protect against unexpected type conversions, which can lead to unpredictable consequences. If you are sure that the types of compared values ​​will match, you can safely use short operators.

Short calculation of logical operators


The logical operators && and || working with values ​​of different types in a very strange way. They convert the value on the left side of the operator to a boolean in order to understand what to do next, but depending on the operator and the result of this conversion, they return either the original value from the left or the right side.

For example, || returns the value from the left side when it can be converted to true - otherwise it returns the right side.

 console.log(null || "user") // → user console.log("Karl" || "user") // → Karl 


Such an operator || allows you to use it as a rollback to the default value. If you give it an expression that can return an empty value on the left, then the value on the right will serve as a replacement for this case.

The && operator works in a similar way, but vice versa. If the value on the left is converted to false, it returns this value; otherwise, the value on the right.

Another important property of them - the expression in the right side is calculated only when necessary. In case of true || X doesn't matter what X is. Even if it's some kind of horrible expression. The result is always true and X is not calculated. It also works false && X - X is simply ignored. This is called a short calculation.

The condition operator works the same. The first expression is always evaluated, and from the second and third values, only the one that is selected as a result.

Total


We looked at four types of JavaScript values: numbers, strings, booleans, and undefined.

These values ​​are obtained when we write their names (true, null) or values ​​(13, “eprst”). They can be combined and modified using operators. For arithmetic there are binary operators (+, -, *, /, and%), string concatenation (+), comparison (==,! =, ===,! ==, <,>, <=,> =) , and logical operators (&&, ||), as well as several unary operators (- for a negative value, for logical negation, and typeof for determining the type of value).

This knowledge allows you to use JavaScript as a calculator, but only. In the next chapter, we will link these simple values ​​together to make simple programs.

Source: https://habr.com/ru/post/240223/


All Articles