Chapter 1: Values, Types and Operators

Réussis tes devoirs et examens dès maintenant avec Quizwiz!

Template literals

Backtick-quoted strings, usually called template literals, can do a few more tricks. Apart from being able to span lines, they can also embed other values. `half of 100 is ${100 / 2}` When you write something inside ${} in a template literal, its result will be computed, converted to a string, and included at that position. The example produces "half of 100 is 50". This is exactly how it is produced without the dollar sign.

Logical Operators

Boolean values with three operators: and, or and not. The && operator represents logical and. It is a binary operator, its result is true only if both the values given to it are true. console.log(true && false) //--> false console.log(true && true) //--> true The || operator denotes logical or. It produces true if either of the values given to it is true. console.log(false || true) //-> true console.log(false || false) // -> false ! Not is written as an exclamation mark (!). It is a unary operator that flips the value given to it --- !true produces false and ! false gives true.

Values

Every value has a type that determines its role. Some values are numbers, pieces of text, and functions. You don't have to gather building material for your values or pay for them. You just call for one, and woosh, you have it. As soon as you no longer use a value, it will dissipate, leaving behind its bits to be recycled as building material for the next generation of values. Fortunately, this is a problem (run out of memory) only if you need them all simultaneously.

Automatic type conversion

In the Introduction, I mentioned that JavaScript goes out of its way to accept almost any program you give it, even programs that do odd things. This is nicely demonstrated by the following expressions: console.log(8 * null) // → 0 console.log("5" - 1) // → 4 console.log("5" + 1) // → 51 console.log("five" * 2) // → NaN The program cannot compute a calculation on a written value. console.log(false == 0) // → true

Special Numbers

Infinity Negative Infinity NaN "not a number" is a value of the number type that yields a meaningful result from numeric operations such as 0/0 or Infinity - Infinity.

How is data stored?

Is stored as long sequences of bits and is thus fundamentally alike. A typical modern computer has more than 30 billion bits in its volatile data storage. Nonvolatile storage (the hard disk or equivalent) tends to have yet a few orders of magnitude more. To be able to work with such quantities of bits without getting lost, we must separate them into chunks that represent pieces of information. That is called values.

Boolean values

It is often useful to have a value that distinguishes between only two possibilities, like "yes" and "no" OR "on" and "off"

Newlines

Newlines (the characters you get when you press Enter) may be included without escaping only when the string is quoted with backticks (\'). A quote that is preceded by a backslash will not end the string but be part of it. When an n character occurs after a backslash, it is interpreted as a newline. "This is the first line\nAnd this is the second" The actual text contained is this: This is the first line And this is the second Similarly, a t after a backslash means a tab character. This is how the string "A newline character is written like "\n"." can be expressed: "A newline character is written like \"\\n\"." The backlash occurs after parenthesis and before the last one.

Unary operators

Not all operators are symbols. Some are written as words. One example is the typeof operator, which produces a string value naming the type of the value you give it. console.log(typeof 4.5) // → number console.log(typeof "x") // → string We will use console.log in example code to indicate that we want to see the result of evaluating something. One value.

Binary operators

Operators that use two values.

Empty values

Special values: NULL and undefined. to denote the absence of a meaningful value. treating them as mostly interchangeable.

String that concatenates

Strings cannot be divided, multiplied, or subtracted, but the + operator can be used on them. It does not add, but it concatenates—it glues two strings together. The following line will produce the string "concatenate": "con" + "cat" + "e" + "nate" String values have a number of associated functions (methods) that can be used to perform other operations on them. This will be later discussed.

Ternary operator/ conditional operator

The last logical operator I will discuss is not unary, not binary, but ternary, operating on three values. It is written with a question mark and a colon, like this: console.log(true ? 1 : 2); // → 1 console.log(false ? 1 : 2); // → 2 The value on the left of the question mark "picks" which of the other two values will come out. When it is true, it chooses the middle value, and when it is false, the value on the right. Got it!

Short-circuiting of logical operators

The logical operators && and || handle values of different types in a peculiar way. They will convert the value on their left side to Boolean type in order to decide what to do, but depending on the operator and the result of that conversion, they will return either the original left-hand value or the right hand value. The || operator denotes logical or. It produces true if either of the values given to it is true: console.log(false || true) //-> true console.log(false || false) // -> false The || operator, for example, will return the value to its left when that can be converted to true and will return the value on its right otherwise. This has the expected effect when the values are Boolean, and does something analogous for values of other types. console.log(null || "user") // → user console.log("Agnes" || "user") // → Agnes We can use this functionality as a way to fall back on a default value. If you have a value that might be empty, you can put || after it with a replacement value. If the initial value can be converted to false, you'll get the replacement instead. The && operator works similarly, but the other way around. When the value to its left is something that converts to false, it returns that value, and otherwise it returns the value on its right. Another important property of these two operators is that the part to their right is evaluated only when necessary. In the case of true || X, no matter what X is—even if it's a piece of program that does something terrible—the result will be true, and X is never evaluated. The same goes for false && X, which is false and will ignore X. This is called short-circuit evaluation. The conditional operator works in a similar way. Of the second and third value, only the one that is selected is evaluated.

Arithmetic

The main thing to do with numbers is arithmetic. Take the value of numbers to produce a new number Operators: * + () - / %

Can a console.log ever have both a binary and a unary operator?

The minus operator can be used both as a binary operator and as a unary operator. console.log(- (10 - 2)) // → -8

Precedence of Arithmetic Operators

The order of arithmetic operators to compute without parenthesis. multiplication and division and remainder, addition and subtraction.

Comparison operators with Boolean Values

The way strings are ordered is roughly alphabetic, but not really what you'd expect to see in a dictionary: uppercase letters are always "less" than lowercase ones, so "Z" < "a", and nonalphabetic characters (!, -, and so on) are also included in the ordering. When comparing strings, JavaScript goes over the characters from left to right, comparing the Unicode codes one by one. Other similar operators are >= (greater than or equal to), <= (less than or equal to), == (equal to), and != (not equal to). console.log("Itchy" != "Scratchy") // → true console.log("Apple" == "Orange") // → false Only one value that is not equal to itself, and that is NaN ("not a number"). console.log(NaN == NaN) 16 // → false NaN is supposed to denote the result of a nonsensical computation, and as such, it isn't equal to the result of any other nonsensical computations.

Escaping

To make it possible to include such characters in a string, the following notation is used: whenever a backslash (\) is found inside quoted text, it indicates that the character after it has a special meaning. This is called escaping the character.

Strings

To represent text. Strings are written by enclosing their content in quotes. JavaScript's representation uses 16 bits per string element, which can describe up to 2 to the 16 different characters. A lot of bits. Based on the Unicode standard, the string assigns a number to virtually every character you would ever need: If we have a number for every character, a string can be described by a sequence of numbers. Emoji, take up two "character positions" in JavaScript strings.

Avoid Automatic Type Conversions by

To test whether something refers to the precise value false, there are two additional operators by avoiding automatic type conversions: === and !== The rules for converting strings and numbers to Boolean values state that 0, NaN, and the empty string ("") count as false, while all the other values count as true. Because of this, expressions like 0== false and ""== false are true. The first tests whether a value is precisely equal to the other, and the second tests whether it is not precisely equal. So "" === false is false as expected. But when you're certain the types on both sides will be the same, there is no problem with using the shorter operators.

Numbers

Values of the number type are, unsurprisingly, numeric values. JavaScripts uses a fixed number of bits, namely 64 of them, to store a single number value. Fractional numbers are written by using a dot: 9.81. For decimal digits, the amount of numbers that can be represented is 10 to the negative N. Also, Pi cannot be precisely expressed by a finite number of decimal digits, many numbers lose some precision when only 64 bits are available to store them. The important thing is to be aware of it and treat fractional digital numbers as approximations, not as precise values. For a negative sign in a number, the data stores one bit. In addition, some of the bits are used to store the position of the decimal point. The actual maximum whole number that can be stored is more in the range of 9 quadrillion (15 zeros). For very big or very small numbers, you may also use scientific notation by adding an e (for exponent), followed by the exponent of the number: Numbers that are whole can be calculated is also called integers.

Boolean type

Values that are produced in written words: either true or false: Comparison Here is one way to produce Boolean values: console.log(3 > 2) // → true console.log(3 < 2) // → false The > and < signs are the traditional symbols for "is greater than" and "is less than", respectively. They are binary operators. Applying them results in a Boolean value that indicates whether they hold true in this case. Strings can be compared in the same way. console.log ("Aardvark" < "Zoroaster") // → true

Summary

We looked at four types of JavaScript values in this chapter: numbers, strings, Booleans, and undefined values. Such values are created by typing in their name (true, null) or value (13 , "abc"). You can combine and transform values with operators. We saw binary operators for arithmetic (+, -, *, /, and %), string concatenation (+), comparison (==, !=, ===, !==, <, >, <=, >=), and logic (&&, ||), as well as several 20 unary operators (- to negate a number, ! to negate logically, and typeof to find a value's type) and a ternary operator (?:) to pick one of two values based on a third value. This gives you enough information to use JavaScript as a pocket calculator, but not much more. The next chapter will start tying these expressions together into basic programs.

Exercise from above

When an operator is applied to the "wrong" type of value, JavaScript will quietly convert that value to the type it needs, using a set of rules that often aren't what you want or expect. For instance: The null in the first expression becomes 0, and the "5" in the second expression becomes 5 (from string to number). And vise versa: Yet in the third expression, + tries string concatenation before numeric addition, so the 1 is converted to "1" (from number to string). In contrast: When something that doesn't map to a number in an obvious way (such as "five" or undefined) is converted to a number, you get the value NaN. This may occur from an accidental type of conversion.

Results from Arithmetic Operators

When comparing values of the same type using ==, the outcome is easy to predict: you should get true when both values are the same. But when the types differ, it just tries to convert one of the values to the other value's type. However, when null or undefined occurs on either side of the operator, it produces true only if both sides are one of null or undefined. For instance: console.log(null == undefined); // → true console.log(null == 0); // → false Because zero is a value and not an empty value. To test whether a value has a real value instead of null or undefined, you can compare it to null with the == (or !=) operator.

Bits

are any kind of two-valued things, usually described as zeros and ones. We can express the number 13 in bits: 0: 128 0: 64 0: 32 0: 16 1: 8 1: 4 0: 2 1: 1 So the binary number 00001101 or 8 + 4 + 1 is 13.

Precedence of Order of Boolean Operators

||, &&, then the comparison operators (>, ==, and so on), and then the rest. 1 + 1 == 2 && 10 * 10 > 50 2 == 2 && 100 > 50


Ensembles d'études connexes

Module 9 - The Art of Ancient Rome Part II

View Set

HESI - OB, Artificial Rupture of Membranes

View Set

7.3 - Climate change mitigation strategies

View Set

Làm gì mà + tính từ + thế / ເຮັດຫຍັງຈິ່ງ + ຄຳຄຸນນາມ + ແທ້

View Set

Chapter 42: The Child with a Psychosocial Disorder - ML5

View Set

COSC 1336 - MPL Ch 4 and 5 (Python)

View Set