© Russ Ferguson and Keith Cirkel 2017
Russ Ferguson and Keith CirkelJavaScript Recipes10.1007/978-1-4302-6107-0_2

2. Working with Expressions

Russ Ferguson and Keith Cirkel2
(1)
Ocean, New Jersey, USA
(2)
London, UK
 

Performing an Addition with the + Operator

Note
String concatenation is covered in more detail in Chapter 3.

Problem

You want to add some numbers together.

Solution

JavaScript has a set of recognizable math operators, including the addition (+) operator, which you can use to add numbers (or variables of numbers) together.

The Code

console.log(2 + 1);
var myNum = 14;
var anotherNum = 22;
console.log(anotherNum + myNum);
console.log(myNum + 0.23);
console.log(anotherNum + 16 + myNum + 14);
console.log('45' + '3'); // the two Strings are concatenated, because + is the concatenation operator
console.log('45' + '6'); // the two Strings are concatenated, because + is the concatenation operator
Listing 2-1.
Performing an Addition with the + Operator
The output is:
3
36
14.23
66
453
456

How It Works

As you can see, JavaScript’s addition operator is simple reflection of the same mathematical operator. You can add number literals together, or variables of numbers, or a mixture. Additions can happen multiple times in one statement. Essentially everything you expect from the Math operator, you can do in JavaScript. It should be noted that adding number variables together does not affect the underlying variable.
If you attempt to add two strings together, you’ll actually get both of those strings combined into one new string, rather than the addition of those numbers. For example, '1' + '1' actually gives you 11, not 2. This is because + is also the string concatenation operator (see Chapter 3 for more info on string concatenation).

Performing a Subtraction with the - Operator

Problem

You want to subtract some numbers from each other.

Solution

JavaScript has a set of recognizable math operators, including the subtraction (-) operator, which you can use to subtract numbers (or variables of numbers) from each other.

The Code

console.log(2 - 1);
var myNum = 14;
var anotherNum = 22;
console.log(anotherNum - myNum);
console.log(myNum - 0.23);
console.log(anotherNum - 16 - myNum - 14);
console.log('45' - '3'); // the two Strings are coerced into Numbers
Listing 2-2.
Performing a Subtraction with the - Operator
The output is:
1
8
13.77
-22
42

How It Works

Just like the mathematical operators in JavaScript, the subtraction operator works pretty much identically to its mathematical equivalent. Importantly: variables you use as operands in the statement will not be modified as part of the operation.
Internally, the subtraction operator also coerces the value using the internal ToNumber function (section 7.1.3 in ES6, section 9.3 in ES5), which has the same effect as using the number constructor (discussed in Chapter 1). In other words, '1' - '1' is the same as '1 - 1'. This is a big difference between how the subtraction and addition operators behave. While subtraction will coerce the values into numbers, addition does not (well, it would do, but when using + with two strings, it actually becomes the string concatenation operator, discussed in Chapter 3).

Performing Multiplication with the * Operator

Problem

You want to multiply some numbers together.

Solution

JavaScript has a set of recognizable mathematical operators, including the multiplication (*) operator, which you can use to multiply numbers (or variables of numbers) together .

The Code

console.log(2 * 1);
var myNum = 14;
var anotherNum = 22;
console.log(anotherNum * myNum);
console.log(myNum * 0.23);
console.log(anotherNum * 16 * myNum * 14);
console.log('45' * '3'); // the two Strings are coerced into Numbers
Listing 2-3.
Performing Multiplication with the * Operator
The output is:
2
308
3.22
68992
135

How It Works

Just like all other mathematical operators, the multiplication operator works pretty much identically to the mathematical equivalent. Importantly, variables you use as operands in the statement will not be modified as part of the operation.
Internally, the multiplication operator also coerces the value using the internal ToNumber function (section 7.1.3 in ES6, section 9.3 in ES5), which has the same effect as using the number constructor (discussed in Chapter 1). In other words, '1' * '1' is the same as 1 * 1.

Performing Division with the / Operator

Problem

You want to divide some numbers.

Solution

JavaScript has a set of recognizable mathematical operators, including the division (/) operator, which you can use to divide numbers (or variables of numbers) together.

The Code

console.log(2 / 1);
var myNum = 14;
var anotherNum = 22;
console.log(anotherNum / myNum);
console.log(myNum / 0.23);
console.log(anotherNum / 16 / myNum / 14);
console.log('45' / '3'); // the two Strings are coerced into Numbers
Listing 2-4.
Performing Division with the / Operator
The output is:
2
1.5714285714285714
60.869565217391305
0.00701530612244898
15

How It Works

Just like the other mathematical operators in JavaScript, the division operator works pretty much identically to the mathematical equivalent. Importantly: any variables you use as operands in the statement will not be modified as part of the operation.
Internally, the division operator also coerces the value using the internal ToNumber function (section 7.1.3 in ES6, section 9.3 in ES5), which has the same effect as using the number constructor (discussed in Chapter 1). In other words, '1' / '1' is the same as 1 / 1.

Getting the Remainder of a Division Operation with the Modulo (% ) Operator

Problem

You want to get the remainder of a division operation (modulus) of some numbers.

Solution

As in many programming languages, JavaScript has a modulo operator that will return the remainder of an Euclidean division. In other words, it will return the remainder of a division that has been divided into whole parts. For example, getting the modulo of 3 and 1 is 0, as 1 divides equally into three parts; however, the modulo for 3 % 2 returns 1, as 2 goes into 3 with 1 remaining.

The Code

console.log(6 % 1); // 0
console.log(6 % 2); // 0
console.log(6 % 3); // 0
console.log(6 % 4); // 2
console.log(6 % 5); // 1
console.log(6 % 6); // 0
var myNum = 14;
var anotherNum = 22;
console.log(anotherNum % myNum);
console.log(myNum % 0.23);
console.log(anotherNum % 16 % myNum % 14);
Listing 2-5.
Getting the Remainder of a Division Operation with the Modulo (%) Operator
The output is:
0
0
0
2
1
0
8
0.1999999999999994
6

How It Works

The modulo operator uses Euclidean division to work out the amount of whole numbers of the right hand operand go into the left hand operand, and retains the remaining amount. This may seem pretty useless at first, but it’s actually a very useful way to work out number properties inside loops, such as odd and even numbers (number % 2) or rows of numbers (number % n). This has such prevalent use in programming that almost all computer languages implement modulo operators as either using the % sign or using the keyword mod.
Internally, the modulo operator also coerces the value using the internal ToNumber function (section 7.1.3 in ES6, section 9.3 in ES5), which has the same effect as using the number constructor (discussed in Chapter 1). In other words, '1' % '1' is the same as 1 % 1.

Determining If a Value Is Less Than Another with the < Operator

Problem

You want to determine if one number is less (smaller) than another number.

Solution

JavaScript comes with a specific operator to assert if a number is less than another number, called the less than operator, <.

The Code

if (1 < 2) {
    console.log('1 is a smaller Number than 2')
}
if (2 < 1) {
    console.log('2 is a smaller Number than 1');
}
if (2 < 2) {
    console.log('2 is a smaller Number than 2');
}
var myNum = 14;
var otherNum = -9;
if (myNum < otherNum) {
    console.log('myNum is a smaller Number than otherNum');
}
if (otherNum < myNum) {
    console.log('otherNum is a smaller Number than myNum');
}
var stringNum = '-18'; // note this is a string
if (stringNum < otherNum) {
    console.log('stringNum is a smaller Number than otherNum') ;
}
Listing 2-6.
Determining If a Value Is Less Than Another with the < Operator
The output is:
1 is a smaller Number than 2
otherNum is a smaller Number than myNum
stringNum is a smaller Number than otherNum

How It Works

The less than operator simply asserts that the left hand operand has a smaller numerical value than the right hand operand. If it does, then the expression will return the Boolean true. If the left hand operand’s numerical value is equal to or greater than the right hand operand, then it will return the Boolean false.
Just like pretty much all numerical/mathematical operations in JavaScript, the less than operator coerces both operands to be numbers using the internal ToNumber function (section 7.1.3 in ES6, section 9.3 in ES5), which has the same effect as using the number constructor (discussed in Chapter 1). In other words, '1' < '1' is the same as 1 < 1.

Determining If a Value Is Greater than Another with the > Operator

Problem

You want to determine if one number is greater (bigger) than another number.

Solution

JavaScript comes with a specific operator to assert if a number is greater than another number, called the greater than operator, >.

The Code

if (1 > 2) {
    console.log('1 is a bigger Number than 2')
}
if (2 > 1) {
    console.log('2 is a bigger Number than 1');
}
if (2 > 2) {
    console.log('2 is a bigger Number than 2');
}
var myNum = 14;
var otherNum = -9;
if (myNum > otherNum) {
    console.log('myNum is a bigger Number than otherNum');
}
if (otherNum > myNum) {
    console.log('otherNum is a bigger Number than myNum');
}
var stringNum = '-18'; // note this is a string
if (otherNum > stringNum) {
    console.log('otherNum is a bigger Number than stringNum');
}
Listing 2-7.
Determining If a Value Is Greater Than Another with the > Operator
The output is:
2 is a bigger Number than 1
myNum is a bigger Number than otherNum
otherNum is a bigger Number than stringNum

How It Works

The greater than operator simply asserts that the left hand operand is a greater numerical value than the right hand operand. If it is, then the expression will return the Boolean true. If the left hand operand’s numerical value is equal to or smaller than the right hand operand, then it will return the Boolean false.
Just like pretty much all numerical/mathematical operations in JavaScript, the greater than operator coerces both operands to be numbers using the internal ToNumber function (section 7.1.3 in ES6, section 9.3 in ES5), which has the same effect as using the number constructor (discussed in Chapter 1). In other words, '1' > '1' is the same as 1 > 1.

Determining If a Value Is Less than or Equal to Another with the <= Operator

Problem

You want to determine if one number is less (smaller) than another number, or exactly the same size.

Solution

JavaScript comes with a specific operator to assert if a number is greater than, or equal to another number, called the less than or equal operator, <=.

The Code

if (1 <= 2) {
    console.log('1 is a smaller Number than 2, or equal to 2')
}
if (2 <= 1) {
    console.log('2 is a smaller Number than 1, or equal to 1');
}
if (2 <= 2) {
    console.log('2 is a smaller Number than 2, or equal to 2');
}
var myNum = 14;
var otherNum = -9;
if (myNum <= otherNum) {
    console.log('myNum is a smaller Number than otherNum, or equal to otherNum');
}
if (otherNum <= myNum) {
    console.log('otherNum is a smaller Number than myNum, or equal to myNum');
}
var stringNum = '-18'; // note this is a string
if (stringNum <= otherNum) {
    console.log('stringNum is a smaller Number than otherNum, or equal to otherNum');
}
Listing 2-8.
Determining If a Value Is Less Than or Equal to Another with the <= Operator
The output is:
1 is a smaller Number than 2, or equal to 2
2 is a smaller Number than 2, or equal to 2
otherNum is a smaller Number than myNum, or equal to myNum
stringNum is a smaller Number than otherNum, or equal to otherNum

How It Works

The less than equal operator simply asserts that the left hand operand is a smaller or equal numerical value than the right hand operand. If it is, then the expression will return the Boolean true. If the left hand operand’s numerical value is greater than the right hand operand, then it will return the Boolean false. The crucial difference between this and the less than operator is what Boolean is returned when both operands are equal. In the case of the less than or equal operator, it’s true (whereas the less than operator will return false).
Just like pretty much all numerical/mathematical operations in JavaScript, the less than or equal operator coerces both operands to be numbers using the internal ToNumber function (section 7.1.3 in ES6, section 9.3 in ES5), which has the same effect as using the number constructor (discussed in Chapter 1). In other words, '1' <= '1' is the same as 1 <= 1.

Determining If a Value Is Greater than or Equal to Another with the >= Operator

Problem

You want to determine if one number is greater (bigger) than another number, or exactly the same size.

Solution

JavaScript comes with a specific operator to assert if a number is greater than or equal to another number, called the greater than or equal operator, >=.

The Code

if (1 >= 2) {
    console.log('1 is a bigger Number than 2, or equal to 2')
}
if (2 >= 1) {
    console.log('2 is a bigger Number than 1, or equal to 1');
}
if (2 >= 2) {
    console.log('2 is a bigger Number than 2, or equal to 2');
}
var myNum = 14;
var otherNum = -9;
if (myNum >= otherNum) {
    console.log('myNum is a bigger Number than otherNum, or equal to otherNum');
}
if (otherNum >= myNum) {
    console.log('otherNum is a bigger Number than myNum, or equal to myNum');
}
var stringNum = '-18'; // note this is a string
if (otherNum >= stringNum) {
    console.log('otherNum is a bigger Number than stringNum, or equal to stringNum');
}
Listing 2-9.
Determining If a Value Is Greater Than or Equal to Another with the >= Operator
The output is:
2 is a bigger Number than 1, or equal to 1
2 is a bigger Number than 2, or equal to 2
myNum is a bigger Number than otherNum, or equal to otherNum
otherNum is a bigger Number than stringNum, or equal to stringNum

How It Works

The greater than or equal operator simply asserts that the left hand operand is a greater or equal numerical value than the right hand operand. If it is, then the expression will return the Boolean true. If the left hand operand’s numerical value is smaller than the right hand operand, then it will return the Boolean false. The crucial difference between this and the greater than operator is what Boolean is returned when both operands are equal. In the case of the greater than or equal operator, it’s true (whereas the greater than operator will return false).
Just like pretty much all numerical/mathematical operations in JavaScript, the greater than or equal operator coerces both operands to be numbers using the internal ToNumber function (section 7.1.3 in ES6, section 9.3 in ES5), which has the same effect as using the number constructor (discussed in Chapter 1). In other words, '1' <= '1' is the same as 1 <= 1.

Determining If a Value Is Equivalent to Another Using the == Operator

Problem

You want to loosely determine the equality of two values—to assert that are identical values, while not necessarily being the same type.

Solution

JavaScript’s abstract equality operator, ==, compares the two operands for equality, while coercing the types of each operand to be the same.

The Code

if (3 == 3) {
    console.log('3 is (abstractly) equal to 3');
}
if (3 == 2) {
    console.log('3 is (abstractly) equal to 2' );
}
if ('hello' == 'hello') {
    console.log('"hello" is (abstractly) equal to "hello"');
}
if ('hello' == 'hi') {
    console.log('"hello" is (abstractly) equal to "hi"');
}
if ('3' == 3) {
    console.log('"3" is (abstractly) equal to 3');
}
if (false == false) {
    console.log('false is (abstractly) equal to false');
}
if (true == true) {
    console.log('true is (abstractly) equal to true');
}
if (false == true) {
    console.log('false is (abstractly) equal to true');
}
if (false == 0) {
    console.log('false is (abstractly) equal to 0');
}
if (true == 1) {
    console.log('true is (abstractly) equal to 1');
}
var myObject = {};
var otherObject = {};
if (myObject == myObject) {
    console.log('myObject is (abstractly) equal to myObject');
}
if (myObject == otherObject) {
    console.log('myObject is (abstractly) equal to otherObject');
}
if (myObject == {}) {
    console.log('myObject is (abstractly) equal to {}');
}
var myArray = [];
var otherArray = [];
if (myArray == myArray) {
    console.log('myArray is (abstractly) equal to myArray');
}
if (myArray == otherArray) {
    console.log('myArray is (abstractly) equal to otherArray');
}
if (myArray == []) {
    console.log('myArray is (abstractly) equal to []');
}
Listing 2-10.
Determining If a Value Is Equivalent to Another Using the == Operator
The output is :
3 is (abstractly) equal to 3
"hello" is (abstractly) equal to "hello"
"3" is (abstractly) equal to 3
false is (abstractly) equal to false
true is (abstractly) equal to true
false is (abstractly) equal to 0
true is (abstractly) equal to 1
myObject is (abstractly) equal to myObject
myArray is (abstractly) equal to myArray

How It Works

The abstract equality operator works similarly to the strict equality operator, but it does not fail after type checking, instead, it coerces types to match. If the types of both operands match, it simply performs a strict equality check, but if they don’t, then it will attempt to coerce them using the rules in Figure 2-1 (the X axis being the right hand operand, the Y axis being the left hand operand, and the resulting cell being the type that both operands are coerced into) .
A315054_1_En_2_Fig1_HTML.jpg
Figure 2-1.
Abstract equality type coercions
After coercing the types to be the same (where possible), it will then behave the same as a strict equality check; if the types are not the same, it will return the Boolean false. If they are numbers of the same size, strings of the same content, Booleans of the same value, or objects/arrays that point to the same reference in memory, then the strict equality operator returns the Boolean true. If they don’t match any of these criteria, then it will return the Boolean false, with the exception of NaN, which you will need to use Number.isNaN() for (as discussed in Chapter 1).
Because of the added complexity in an abstract equality operator versus a strict equality operator, it is always recommended to use the strict version, unless you absolutely have a reason to use the abstract one. Also remember you can cast values to different types yourself using the constructor methods mentioned throughout Chapter 1.

Determining If a Value Is Strictly Equal to Another Using the === Operator

Problem

You want to determine the equality of two values—to assert that they are identical values.

Solution

JavaScript’s strict equality operator, ===, compares the two operands for equality.

The Code

if (3 === 3) {
    console.log('3 is equal to 3');
}
if (3 === 2) {
    console.log('3 is equal to 2');
}
if ('hello' === 'hello') {
    console.log('"hello" is equal to "hello"');
}
if ('hello' === 'hi') {
    console.log('"hello" is equal to "hi"');
}
if ('3' === 3) {
    console.log('"3" is equal to 3');
}
if (false === false) {
    console.log('false is equal to false');
}
if (true === true) {
    console.log('true is equal to true');
}
if (false === true) {
    console.log('false is equal to true');
}
if (false === 0) {
    console.log('false is equal to 0');
}
if (true === 1) {
    console.log('true is equal to 1');
}
var myObject = {};
var otherObject = {};
if (myObject === myObject) {
    console.log('myObject is equal to myObject');
}
if (myObject === otherObject) {
    console.log('myObject is equal to otherObject');
}
if (myObject === {}) {
    console.log('myObject is equal to {}');
}
var myArray = [];
var otherArray = [];
if (myArray === myArray) {
    console.log('myArray is equal to myArray');
}
if (myArray === otherArray) {
    console.log('myArray is equal to otherArray');
}
if (myArray === []) {
    console.log('myArray is equal to []');
}
Listing 2-11.
Determining If a Value Is Strictly Equal to Another Using the === Operator
The output is:
3 is equal to 3
"hello" is equal to "hello"
false is equal to false
true is equal to true
myObject is equal to myObject
myArray is equal to myArray

How It Works

The strict equality operator first checks that both operands are the same type (e.g., they are both numbers). If they are not the same type, it will return the Boolean false. If they are numbers of the same size, strings of the same content, Booleans of the same value, or objects/arrays that point to the same reference in memory, then the strict equality operator returns the Boolean true. If they don’t match any of these criteria, then it will return the Boolean false. This makes it the best way to determine the equality of two values. There is one exception to this rule—and that is the literal value NaN, if either (or both) of the operands is NaN then it will return the Boolean false. Quizzically, this makes the statement NaN === NaN return the Boolean false. If you want to assert that something is NaN, you’ll need to use Number.isNaN(), as discussed in Chapter 1. See Figure 2-2 for an illustration of this flow .
A315054_1_En_2_Fig2_HTML.jpg
Figure 2-2.
Strict equality check flow illustration

Determining If a Value Is Not Equivalent to Another Using the != Operator

Problem

You want to loosely determine the inequality of two values—to assert that are not identical values, even when coerced to be the same type.

Solution

JavaScript’s abstract inequality operator, !=, compares the two operands for inequality, while coercing the types of each operand to be the same.

The Code

if (3 != 3) {
    console.log('3 is not equal to 3');
}
if (3 != 2) {
    console.log('3 is not equal to 2');
}
if ('hello' != 'hello') {
    console.log('"hello" is not equal to "hello"');
}
if ('hello' != 'hi') {
    console.log('"hello" is not equal to "hi"');
}
if ('3' != 3) {
    console.log('"3" is not equal to 3');
}
if (false != false) {
    console.log('false is not equal to false');
}
if (true != true) {
    console.log('true is not equal to true');
}
if (false != true) {
    console.log('false is not equal to true');
}
if (false != 0) {
    console.log('false is not equal to 0');
}
if (true != 1) {
    console.log('true is not equal to 1');
}
var myObject = {};
var otherObject = {};
if (myObject != myObject) {
    console.log('myObject is not equal to myObject');
}
if (myObject != otherObject) {
    console.log('myObject is not equal to otherObject');
}
if (myObject != {}) {
    console.log('myObject is not equal to {}');
}
var myArray = [];
var otherArray = [];
if (myArray != myArray) {
    console.log('myArray is not equal to myArray');
}
if (myArray != otherArray) {
    console.log('myArray is not equal to otherArray');
}
if (myArray != []) {
    console.log('myArray is not equal to []');
}
Listing 2-12.
Determining If a Value Is Not Equivalent to Another Using the != Operator
The output is:
3 is not (abstractly) equal to 2
"hello" is not (abstractly) equal to "hi"
false is not (abstractly) equal to true
myObject is not (abstractly) equal to otherObject
myObject is not (abstractly) equal to {}
myArray is not (abstractly) equal to otherArray
myArray is not (abstractly) equal to []

How It Works

The abstract inequality operator works almost identically to the abstract equality operator, except that it returns the opposing Boolean value. It performs the same type coercions as mentioned in Table 2-1. After coercing the types to be the same (where possible), it will then behave the same as a strict inequality check; if the types are not the same, it will return the Boolean true. If they are numbers of the same size, strings of the same content, Booleans of the same value, or objects/arrays that point to the same reference in memory, then the strict equality operator returns the Boolean false. If they don’t match any of these criteria, then it will return the Boolean true, with the exception of NaN, which you will need to use Number.isNaN() for (as discussed in Chapter 1).
Table 2-1.
Return Values for the typeof Operator
Operand Type
Return Value
String literal (“” or ‘’)
"string"
Number literal
"number"
Boolean literal (true or false)
"Boolean"
Undefined literal
"undefined"
Null literal
"null"
Symbol
"symbol"
Function
"function"
Anything else
"object"
Because of the added complexity in an abstract inequality operator versus a strict inequality operator, it is always recommended to use the strict version, unless you absolutely have a reason to use the abstract one. Also remember that you can cast values to different types yourself, using the constructor methods mentioned throughout Chapter 1.

Determining If a Value Is Strictly Not Equal to Another Using the !== Operator

Problem

You want to determine the inequality of two values - to assert that are not identical values.

Solution

JavaScript’s Strict Inequality Operator, !==, compares the two operands it is given for inequality .

The Code

if (3 !== 3) {
    console.log('3 is not equal to 3');
}
if (3 !== 2) {
    console.log('3 is not equal to 2');
}
if ('hello' !== 'hello') {
    console.log('"hello" is not equal to "hello"');
}
if ('hello' !== 'hi') {
    console.log('"hello" is not equal to "hi"');
}
if ('3' !== 3) {
    console.log('"3" is not equal to 3');
}
if (false !== false) {
    console.log('false is not equal to false');
}
if (true !== true) {
    console.log('true is not equal to true');
}
if (false !== true) {
    console.log('false is not equal to true');
}
if (false !== 0) {
    console.log('false is not equal to 0');
}
if (true !== 1) {
    console.log('true is not equal to 1');
}
var myObject = {};
var otherObject = {};
if (myObject !== myObject) {
    console.log('myObject is not equal to myObject');
}
if (myObject !== otherObject) {
    console.log('myObject is not equal to otherObject');
}
if (myObject !== {}) {
    console.log('myObject is not equal to {}');
}
var myArray = [];
var otherArray = [];
if (myArray !== myArray) {
    console.log('myArray is not equal to myArray');
}
if (myArray !== otherArray) {
    console.log('myArray is not equal to otherArray');
}
if (myArray !== []) {
    console.log('myArray is not equal to []');
}
Listing 2-13.
Determining If a Value Is Strictly Not Equal to Another Using the !== Operator
The output is:
3 is not equal to 2
"hello" is not equal to "hi"
"3" is not equal to 3
false is not equal to true
false is not equal to 0
true is not equal to 1
myObject is not equal to otherObject
myObject is not equal to {}
myArray is not equal to otherArray
myArray is not equal to []

How It Works

The Strict Inequality Operator works almost identically to the Strict Equality operator, except that the Boolean values are reversed. It checks that both operands are the same type (e.g. they are both numbers), if they are not the same type, it will return the Boolean true. If they are numbers of the same size, Strings of the same content, Booleans of the same value, or Objects/Arrays that point to the same reference in memory, then the Strict Equality Operator returns the Boolean false. If they don’t match any of these criteria, then it will return the Boolean true. This makes it the best way to determine the inequality of two values. Similarly to the Strict Equality Operator, if either (or both) of the operands is NaN then it will return the Boolean true, meaning NaN !== NaN return the Boolean true. If you want to assert that something is not NaN, you’ll need to use Number.isNaN() as discussed in Chapter 1. Refer to Figure 2-3 for an illustration of this flow.
A315054_1_En_2_Fig3_HTML.jpg
Figure 2-3.
Strict inequality check flow illustration

Using the Increment (++ ) Operator to Increase the Value of a Number Variable

Problem

You want a simple way to increment a number by 1, for example, while iterating over an array in a for loop.

Solution

Because it is such a common task to perform in programming, JavaScript comes with the increment operator (++). You can use the increment operator with a variable to set the value to value + 1. It comes in two flavors—prefix (putting the ++ before the value) and postfix (putting the ++ after the value), and they have some subtle differences .

The Code

var myVar = 1;
++myVar; // increments myVar to 2
console.log(myVar); // logs 2
console.log(++myVar); // Increments myVar to 3, logs 3
console.log(myVar); // logs 3
myVar = 1;
myVar++; // increments myVar to 2
console.log(myVar); // logs 2
console.log(myVar++); // logs 2, increments myVar to 3
console.log(myVar); // logs 3
Listing 2-14.
Using the Increment (++) Operator to Increase the Value of a Number Variable
The output is:
2
3
3
2
2
3

How It Works

The increment operators take the variable from the statement, adds one to it, and then sets the variable to the new value. The difference between postfix and prefix operators comes from how the interpreter treats them. The postfix operation is treated as a “left hand side expression,” which puts its code equivalent to value += 1. The prefix operation is treated as a “unary expression,” which is an expression with one operand, a standalone operation. It puts its code equivalent to something like value = value + 1.
The practical difference between these is that the postfix operation (coincidentally to its name) will return the original value, and then increment it after the statement has been parsed, while the prefix operation increments the value, and then returns it. Unless you have a specific reason to use the postfix operator, it is always recommended to use the prefix operator. If you ever try to assign a value upon increment using the postfix operator, it will assign the previous value, not the incremented version .

Using the Decrement (-- ) Operator to Decrease the Value of a Number Variable

Problem

You want a simple way to decrement a number by 1, for example, while iterating over an array in a for loop.

Solution

Just like the commonly used increment operator, JavaScript also comes with the complementary decrement operator. It uses two dashes (--) either as a prefix operator (before variable or literal) or postfix operator (after variable or literal) to decrement the given number by 1.

The Code

var myVar = 3;
--myVar; // decrements myVar to 2
console.log(myVar); // logs 2
console.log(--myVar); // decrements myVar to 1, logs 1
console.log(myVar); // logs 1
myVar = 3;
myVar--; // decrements myVar to 2
console.log(myVar); // logs 2
console.log(myVar--); // logs 2, decrements myVar to 1
console.log(myVar); // logs 1
Listing 2-15.
Using the Decrement (--) Operator to Decrease the Value of a Number Variable
The output is:
2
1
1
2
2
1

How It Works

Decrement operators work in the same way as the increment operators, except they subtract 1 rather than add 1. The same rules around postfix and prefix operators apply here too, so once again be very careful and if in doubt, use the prefix operator (--value). Using the postfix operator will not assign the incremented value to a variable, but instead assign the old value, and then increment the number.

Using the Unary Addition (+) Operator to Coerce an Object to a Number

Problem

You need an easy and concise way to convert a numeric string into an actual number, for later number-based operations.

Solution

The addition (+) operator is actually used in a few different ways. While its main use may be adding two numbers together, it can also be used as a unary operator (that is, it only has one operand) to coerce a value into a number.

The Code

console.log( + "42" ); // Coerces String to the Number 42
console.log( + '3.142' ); // Coerces String to the Number 3.142
console.log( + "-1e3" ); // Coerces String to the Number -1000
var myNum = '1.231'; // The String '1.231'
console.log( + myNum ); // Coerces String to the Number 1.231
console.log( + {} ); // NaN (Not a Number)
console.log( + 'foo' ); // NaN (Not a Number)
console.log( + + + + '1' ); // Operator can be repeated (value is the Number 1)
Listing 2-16.
Using the Unary Addition (+) Operator to Coerce an Object to a Number
The output is:
42
3.142
-1000
1.231
NaN
NaN
1

How It Works

The JavaScript interpreter specifically picks up the + sign with no preceding value as a “unary + operator” (section 12.4.9 of the ES6 spec, or section 11.4.6 of the ES5 spec). When found, it takes the value following it and tries to convert it to a numeric value. If it is unable to, it will convert it into the NaN (Not a Number) object .
Internally, it coerces the value using the internal ToNumber function (section 7.1.3 in ES6, section 9.3 in ES5), which has the same effect as using the number constructor (discussed in Chapter 1). In other words, +4 is the same as Number(4). Because of this similarity, it is probably better to just use the number constructor syntax (Chapter 1), as it reads much easier.

Using the Unary Subtraction (-) Operator to Flip the Sign of a Number

Problem

You have a number that is positive or negative, and you want to change it to the opposing sign.

Solution

The subtraction (-) operator also doubles up as a unary operator (that is, it only has one operand) to flip the sign of a number. It also will coerce any given values to numbers before flipping their sign.

The Code

console.log( - 1 ); // The Number -1
console.log( - -1 ); // The Number 1 (+1)
console.log( - 1e3 ); // The Number -1000
console.log( - '123' ); // The Number -123
console.log( - '-123' ); // The Number 123
console.log( - {} ); // NaN (Not a Number)
console.log( - 'foo' ); // NaN (Not a Number)
console.log( - - - - 1 ); // Operator can be repeated (value is the Number -1)
Listing 2-17.
Using the Unary Negation (-) Operator to Flip the Sign of a Number
The output is:
-1
1
-1000
-123
123
NaN
NaN
1

How It Works

The JavaScript interpreter specifically picks up the - sign with no preceding value as a “unary - operator” (section 12.4.10 of the ES6 spec, or section 11.4.7 of the ES5 spec). When found, it takes the value and simply flips the sign from a + to a -, or a - to a +.(-)
Internally, it coerces the value using the internal ToNumber function (section 7.1.3 in ES6, section 9.3 in ES5), which has the same effect as using the number constructor (discussed in Chapter 1). It does this before it swaps the sign, so can be useful to swap signs on implicit numbers (e.g., numerical strings).

Using the Logical NOT (!) Operator to Toggle a Boolean Value

Problem

You want a simple way to toggle the value of a Boolean, from either true to false, or from false to true.

Solution

The logical NOT operator is a unary expression (that is, it only has one operand), which allows you to toggle Boolean values between true and false. It has the added ability of coercing implicit Boolean values to Booleans before flipping them (for example, a number of 0 or 1).

The Code

console.log( ! true ); // False
console.log( ! false ); // True
console.log( ! 0 ); // True
console.log( ! 1 ); // False
console.log( ! ! 1 ); // Can be used multiple times to flip values again, this value is True
Listing 2-18.
Using the Logical Negation (!) Operator to Toggle a Boolean Value
The output is:
false
true
true
false
true

How It Works

The first thing the logical NOT operator does is convert the value into a Boolean using the ToBoolean internal function (discussed in Chapter 1 in much more detail, and section 7.1.2 of the ES6 spec or section 9.2 of the ES5 spec). After it has done this, it very simply converts a value of true to false and false to true.
The logical NOT operator can be seen in the wild mostly inside if statements, as it is a easy way to assert something is the Boolean opposite of its value, which makes it ideal for control flow. Of all of the unary operators that exist, it is safe to say that the logical NOT operator is the most widely used .

Deleting an Object, Property, or Array Element with the Delete Operator

Problem

You need to delete a property on an object or array and remove the property name from the list of keys in the object or array.

Solution

The delete unary operator (that is, it only has one operand) is the way to remove properties from objects or arrays.

The Code

var house = { floors: 3, bedrooms: 4, garden: true };
console.log( 'House has', house.floors , 'floors' );
console.log( delete house.floors ); // delete returns true
console.log( delete house.floors ); // delete returns true
console.log( 'House has', house.floors , 'floors' );
console.log( delete house );
var primes = [ 2, 3, 5, 7, 11 ];
console.log( delete primes[11] ); // delete returns false
console.log( delete primes[2] ); // delete returns true
console.log( primes );
console.log( delete primes );
Listing 2-19.
Deleting an Object, Property, or Array Element with the Delete Operator
The output is:
House has 3 floors
true
true
House has undefined floors
false
true
true
2, 3, undefined, 7, 11 // this may be logged as [2, 3, 3: 7, 4: 11] in some consoles, but it represents the same values
false // You may see true here if using eval() or using a console that uses it (for example Firefox's)

How It Works

delete works by removing a property from an object or array. It is important to note that delete does not work on variables or declared functions—that is, it cannot delete things that are not properties of objects or arrays.
A common misconception around delete is that it is useful for freeing up memory. Delete does not free up any memory as a direct result of its operation. For example, if you have an object that is referenced elsewhere in your code, as well as in an object you are deleting from, then the object still has a hard reference, and therefore will not be freed. The only way delete will ever appear to be freeing memory is if the deleted property was the only hard reference to an object, function, or array. Consider the code in Listing 2-20.
var license1234 = { id: 1234, expiry: '2022-01-01' };
var person = { name: 'Bob', license: license1234 }; // person's 'license' property is linked to 'license1234'
console.log( delete person.license ); // Removes the 'license' property from  the 'person' object
console.log( license1234.id ); // License 1234 still exists, as it is referenced by the variable 'license1234', and so no memory has been freed by deleting it from the 'person' object.
Listing 2-20.
Deleting an Object, Property, or Array Element with the Delete Operator
The output is:
true
1234
As you can see, no memory is freed by using the delete operator, as the license1234 variable still exists and is referencing the same object. Any memory freed by the delete operator is merely a side-effect. In fact, there is no way in JavaScript to manually free memory. You can set variable values to undefined to “dereference” their existing values, but this is not a guaranteed way of freeing memory. JavaScript’s GC (Garbage Collector) is the only way memory is freed, and it automatically runs when the particular implementation detects there is “garbage” or no-longer-referenced objects to be removed from memory. This is done using the mark-and-sweep algorithm. Using this algorithm, each object will be marked as “in use” and therefore referenced by other objects. When no references can be made the object is not considered to be in use, and at that time memory is then released .

Evaluating an Expression Without a Return Value with the Void Operator

Problem

You want to evaluate an expression, but explicitly ignore its return value, instead returning undefined.

Solution

The void operator is another unary operator (that is, it only has one operand), which allows you to evaluate an expression and explicitly return undefined from the expression. Simply prefix any expression with void and the expression will return undefined.

The Code

console.log( void( 0 ) ); // returns Undefined
var object = { one: 1, two: 2 };
delete object.one; // returns true
console.log( void( delete object.one ) ); // returns Undefined
console.log( object.two ); // returns the Number 2
console.log( void( object.two ) ); // returns Undefined
function addNumbers(a, b) {
    return a + b
}
console.log( addNumbers(1, 2) ); // returns 3
console.log( void( addNumbers(1, 2) ) ); // returns Undefined
Listing 2-21.
Evaluating an Expression Without a Return Value with the Void Operator
The output is:
undefined
undefined
2
undefined
3
undefined

How It Works

The JavaScript interpreter reads the void keyword and executes the expression after it. It explicitly always returns undefined, unless of course the remaining expression throws an Error.
While this has pretty limited utility, it can be useful in some cases. One case, for example, is when using arrow function syntax (described in Chapter 13), which uses the last expressions value as the implicit return value. You can use void to always ensure you’re returning undefined.
Another example of real-world usage you may frequently see are developers using void 0 in place of undefined. This is due to a bug in the ES3 spec (and therefore older browsers) allowing the undefined literal value to be overridden. Because undefined was not guaranteed to be the undefined literal value, some developers chose to program defensively, and use void 0 as a syntactical replacement, which is guaranteed to be undefined. Generally this should be avoided, as today almost all browsers follow the ES6 or ES5 spec, which explicitly tell implementers that the undefined value is not writable (ES6 section 18.1.3, ES5 section 15.1.1.3).

Determining the Type of a Variable with the typeof Operator

Caution
Symbols are an ES6 feature. Older browsers still in use, such as Internet Explorer 11 and below, or Safari 7 and below, do not support this feature.

Problem

You want to be able to determine the type of a literal value.

Solution

The typeof unary operator (that is, it only has one operand) is the easiest way to determine the type of some literal values. Unfortunately, it does not work with all values, but literals do work.

The Code

console.log( typeof 0 ); // "number"
console.log( typeof Infinity ); // "number"
console.log( typeof NaN ); // "number"
console.log( typeof 'Hi' ); // "string"
console.log( typeof "Hi" ); // "string"
console.log( typeof true ); // "boolean"
console.log( typeof false ); // "boolean"
console.log( typeof undefined ); // "undefined"
console.log( typeof new Symbol() ); // "symbol" - (careful, only in ES6)
console.log( typeof {} ); // "object"
console.log( typeof [] ); // "object"
console.log( typeof new Date() ); // "object"
console.log( typeof /^$/ ); // "object"
console.log( typeof null ); // "object"
console.log( typeof new String() ); // "object"
console.log( typeof new Number() ); // "object"
console.log( typeof typeof {} ); // "string"
Listing 2-22.
Determining the Type of a Variable with the typeof Operator
The output is:
number
number
number
string
string
boolean
boolean
undefined
symbol
object
object
object
object
object
object
object
string

How It Works

The typeof operator checks predefined internal values using the specification (ES6 section 12.4.6, ES5 section 11.4.3). If the operand given is a literal value with a defined typeof value, then the operator returns that value. If not, the operator returns "object". The return value of typeof is always a string, hence typeof typeof will always evaluate to a string. See Table 2-1 for a summary of return types.

Using instanceof to Determine If a Variable Is an Instance of an Object

Note
Instances and the prototype chain are covered in more detail in Chapter 18.
Caution
Symbols are an ES6 feature. Older browsers still in use, such as Internet Explorer 11 and below, or Safari 7 and below, do not support this feature.

Problem

You want to be able to check if a non-literal value inherits from an object, such as the date constructor .

Solution

The typeof operator only asserts against literal values, which makes it useless for asserting against more complex objects, such as the Date object. Instead, the instanceof can be used to determine if a variable or object is an instance of a particular constructor.

The Code

var myDate = new Date();
if (myDate instanceof Date) {
    console.log('myDate is a Date instance');
}
if (myDate instanceof Array) {
    console.log('myDate is an Array instance');
}
if (myDate instanceof Symbol) {
    console.log('myDate is a Symbol instance');
}
if (myDate instanceof Object) {
    console.log('myDate is an Object instance');
}
var mySymbol = new Symbol();
if (mySymbol instanceof Date) {
    console.log('mySymbol is a Date instance');
}
if (mySymbol instanceof Array) {
    console.log('mySymbol is an Array instance');
}
if (mySymbol instanceof Symbol) {
    console.log('mySymbol is a Symbol instance');
}
if (mySymbol instanceof Object) {
    console.log('mySymbol is an Object instance');
}
var myArray = new Array();
if (myArray instanceof Date) {
    console.log('myArray is a Date instance');
}
if (myArray instanceof Array) {
    console.log('myArray is an Array instance');
}
if (myArray instanceof Symbol) {
    console.log('myArray is a Symbol instance');
}
if (myArray instanceof Object) {
    console.log('myArray is an Object instance') ;
}
var myObject = new Object();
if (myObject instanceof Date) {
    console.log('myObject is a Date instance');
}
if (myObject instanceof Array) {
    console.log('myObject is an Array instance');
}
if (myObject instanceof Symbol) {
    console.log('myObject is a Symbol instance');
}
if (myObject instanceof Object) {
    console.log('myObject is an Object instance');
}
Listing 2-23.
Using instanceof to Determine If a Variable Is an Instance of an Object
The output is:
myDate is a Date instance
myDate is an Object instance
mySymbol is a Symbol instance
mySymbol is an Object instance
myArray is an Array instance
myArray is an Object instance
myObject is an Object instance

How It Works

The instanceof unary operator checks to see if the left hand operator is an instance of the right hand operator. It knows if a particular object has been instantiated by a constructor because of a piece of JavaScript internals known as the prototype.
JavaScript’s prototype allows objects to inherit properties and methods from constructors. Constructors define a .prototype property that is an object of properties and functions to assign to new objects. When a constructor gets called with the new keyword (e.g., new Date()), it creates a new object, whose __proto__ property is set to a reference of the constructor’s .prototype property. instanceof essentially asserts that the left hand operand’s __proto__ property is equal to the right hand’s .prototype property. But it goes further than that, because instanceof will also check the constructor’s __proto__ property, and that constructor’s __proto__ property, and so on. This is called the “prototype chain,” and it means that you can assert against an object’s ancestry. As a side note, all non-literal values have an ancestry starting with object, which is why all constructors and instances will assert that they are instances of object. This may seem like a complex topic, and that’s because it is—but it’s covered in much more detail later in the book .

Finding Properties in an Object with the in Operator

Note
Enumerability and defining object meta properties are discussed more in Chapter 9.
Note
Instances and the prototype chain are covered in more detail in Chapter 18.

Problem

You want to determine if an object contains (in itself or as part of its prototype) a particular property or function.

Solution

JavaScript’s in operator is a great way to check for the existence of property names inside an object or its ancestor objects (the prototype chain).

The Code

var house = { bedrooms: 4, floors: 3 };
if ('bedrooms' in house) {
    console.log('house has a "bedrooms" property');
}
if ('floors' in house) {
    console.log('house has a "floors" property');
}
if ('style' in house) {
    console.log('house has a "style" property');
} else {
    console.log('house does not have a "style" property');
}
var bedroomPropertyName = 'bedrooms' ;
if (bedroomPropertyName in house) {
    console.log('house has a ' +  bedroomPropertyName + ' property');
}
var qualifiers = ['First', 'Second', 'Third', 'DNF'];
if (0 in qualifiers) {
    console.log('qualifiers has a "0" item');
}
if (3 in qualifiers) {
    console.log('qualifiers has a "3" item');
}
if (8 in qualifiers) {
    console.log('qualifiers has an "8" item');
} else {
    console.log('qualifiers does not have an "8" item');
}
var myDate = new Date();
if ('setDay' in myDate) {
    console.log('myDate has a "setDay" method');
}
Listing 2-24.
Finding Properties in an Object with the in Operator
The output is:
house has a "bedrooms" property
house has a "floors" property
house does not have a "style" property
house has a bedrooms property
qualifiers has a "0" item
qualifiers has a "3" item
qualifiers does not have an "8" item

How It Works

The in operator checks for the existence of a property inside of an object, even if that property is not enumerable (enumerability refers to if a property appears in loops, it is discussed much more in Chapter 8) or even if is set to the undefined literal .
It will also check for properties or methods that it has inherited from constructors it has been created from (the same kind of ancestry pattern we see in instanceof). These might not be directly attached to the object, but will be part of the Object’s prototype. For more on how JavaScript’s prototype works, read ahead to Chapter 18.

Using Logical AND (&&) for Combining Boolean Expressions in an if Statement, with Short-Circuit Evaluation

Problem

You want to combine a set of expressions in an if statement, ending the evaluation of all statements upon the first false one.

Solution

The logical AND operator (&&) is an incredibly useful tool for short-circuit evaluation of a series of expressions. It will executes each expression, continuing if the expression is true, until the first expression that returns false, and will exit early at that point. This is useful for combining Boolean expressions in a useful and performant way.

The Code

var myBoolean = true, otherBoolean = true;
if (myBoolean && otherBoolean) {
    console.log('Both operands were true');
} else {
    console.log('One or both operands were false') ;
}
myBoolean = false;
if (myBoolean && otherBoolean) {
    console.log('Both operands were true');
} else {
    console.log('One or both operands were false');
}
myBoolean = true;
otherBoolean = false;
if (myBoolean && otherBoolean) {
    console.log('Both operands were true');
} else {
    console.log('One or both operands were false');
}
var house = { bedrooms: 4, floors: 3 };
if (house.bedrooms && house.bedrooms > 3) {
    console.log('House has more than 3 bedrooms');
}
if (house.floors && house.bedrooms && house.bedrooms > house.floors) {
    console.log('House has more bedrooms than floors') ;
}
Listing 2-25.
Using Logical AND (&&) Short-Circuit Evaluation in an if Statement
The output is:
Both operands were true
One or both operands were false
One or both operands were false
House has more than 3 bedrooms
House has more bedrooms than floors

How It Works

The JavaScript interpreter will separate each expression on either side of the logical AND operator and run them serially (in sequence, one after the other). If an expression returns false, it will exit the entire statement early and return false. If it gets to the end of all expressions—each one returning true—then the entire statement will return true.
Short-circuit evaluation is the crux of control flow in almost any programming language. It keeps things performant by ending at the first false expression, which means developers seeking for performant control flow can easily order their expressions from most performant to least. JavaScript performance is not something this book will dive into, as it’s a vast topic in and of itself, but there are many great books you can read on the topic of performance .

Using Logical OR (||) Short-Circuit Evaluation in an if Statement

Problem

You want to combine a set of expressions in an if statement, ending the evaluation of all statements upon the first true one.

Solution

The logical OR OPERATOR (||) is pretty much the antithesis of the logical AND operator. It will execute each expression continuing if the expression is false, until the first expression that returns true, and will exit early at that point. This is useful for combining Boolean expressions in a useful and performant way .

The Code

var myBoolean = true, otherBoolean = true;
if (myBoolean || otherBoolean) {
    console.log('Both operands were true');
} else {
    console.log('One or both operands were false');
}
myBoolean = false;
if (myBoolean || otherBoolean) {
    console.log('Both operands were true');
} else {
    console.log('One or both operands were false');
}
myBoolean = true;
otherBoolean = false;
if (myBoolean || otherBoolean) {
    console.log('Both operands were true');
} else {
    console.log('One or both operands were false');
}
var house = { bedrooms: 4, floors: 3, driveway: 1 };
if (house.floors === 4 || house.bedrooms === 4) {
    console.log('House has either 4 floors OR 4 bedrooms');
}
if (house.streetParking || house.garage || house.driveway) {
    console.log('House has some parking space');
}
Listing 2-26.
Using Logical OR (||) Short-Circuit Evaluation in an if Statement
The output is:
Both operands were true
Both operands were true
Both operands were true
House has either 4 floors OR 4 bedrooms
House has some parking space

How It Works

The JavaScript interpreter will separate each expression on either side of the logical OR operator and run them serially (in sequence, one after the other). If an expression returns true, it will exit the entire statement early and return true. If it gets to the end of all expressions—each one returning false—then the entire statement will return false. This is effectively the opposite behavior of the logical AND operator.
Short-circuit evaluation is the crux of control flow in almost any programming language. It keeps things performant by ending at the first true expression, which means developers seeking for performant control flow can easily order their expressions from most performant to least. JavaScript performance is not something this book will dive into, as it’s a vast topic in and of itself, but there are many great books you can read on the topic of performance.

Simplifying Variable Assignments Using the Conditional (?) Operator

Problem

You want a more concise way of assigning a variable to a value based on a condition and using an if/else is too complex for simple variable assignment. A terser way accomplish the same goals is preferable.

Solution

The conditional ternary (that is, it takes three expressions) operator (?) is a quick-fire way to assign a variable based on a condition. Simply begin a variable assignment as you would normally, followed by a condition, followed by two potential values. This is better than than the overly verbose if(condition) { value } else { otherValue }.

The Code

var retake = false;
var passMark = retake ? 180 : 150;
console.log('The pass mark is ' + passMark);
var retake = true;
var passMark = retake ? 180 : 150;
console.log('The pass mark is ' + passMark);
var score = 180, retake = true;
var passFail = retake ? (score >= 180 ? 'pass' : 'fail') : (score >= 150 ? 'pass': 'fail');
console.log('You scored ' + score + ' which is a ' + passFail);
var score = 150, retake = false;
var passFail = retake ? (score >= 180 ? 'pass' : 'fail') : (score >= 150 ? 'pass': 'fail');
console.log('You scored ' + score + ' which is a ' + passFail) ;
var score = 150, retake = true;
var passFail = retake ? (score >= 180 ? 'pass' : 'fail') : (score >= 150 ? 'pass': 'fail');
console.log('You scored ' + score + ' which is a ' + passFail);
var score = 120;
var grade =  score >= 180 ? 'A' :
             score >= 150 ? 'B' :
             score >= 120 ? 'C' :
             score >= 100 ? 'D' :
             score >= 80 ? 'E' :
             'F';
var anOrA = (grade === 'B' || grade === 'C' || grade === 'D') ? 'a' : 'an';
console.log('You scored ' + score + ' which is ' +  anOrA + ' ' + grade);
var score = 40;
var grade =  score >= 180 ? 'A' :
             score >= 150 ? 'B' :
             score >= 120 ? 'C' :
             score >= 100 ? 'D' :
             score >= 80 ? 'E' :
             'F';
var anOrA = (grade === 'B' || grade === 'C' || grade === 'D') ? 'a' : 'an';
console.log('You scored ' + score + ' which is ' +  anOrA + ' ' + grade);
Listing 2-27.
Simplifying Variable Assignments Using the Conditional (?) Operator
The output is:
The pass mark is 150
The pass mark is 180
You scored 180 which is a pass
You scored 150 which is a pass
You scored 150 which is a fail
You scored 120 which is a C
You scored 40 which is an F

How It Works

The conditional ternary operator uses a ? to denote that the left hand expression should be treated as a conditional expression, then the remaining two expressions—separated by :—will be used based on the resulting conditional value. If the conditional expression returns true, the value left of the : is used. If the conditional expression returns false, the value right of the : is used. It behaves exactly like an if/else statement that assigns one value, in that the conditional is coerced using the same ToBoolean internal function, and the resulting expressions will become the variable’s value.
Because each operand can be a full expression you can also create complex expressions, such as combining short-circuit evaluation or multiple conditional ternary operators—as demonstrated in the examples—this can become messy very quickly. As a good rule of thumb, use this only for setting single values based on a single condition; if you find yourself nesting conditional ternary operators, it is most likely going to be clearer as an if statement .

Specifying Multiple Expressions Using the Comma Operator

Problem

You want to be able to specify multiple expressions in one statement, for example inside a for loop, a variable declaration, or a conditional ternary operator.

Solution

The comma operator has some caveats but is a great way to express multiple expressions in a single statement, which has various uses.

The Code

var names = ['bob', 'jim', 'sue'],
    greetings = { warm: 'hello' },
    count = names.length;
// Here the comma operator is used in the last statement
// of a for loop to mutate two numbers at once
for (var i = 0, n = names.length; i < count; ++i, --n) {
    console.log(greetings.warm + ' ' + names[i] + ' (' + n + ' people left)');
}
// vs:
for (var i = 0, n = names.length; i < count; ++i) {
    --n;
    console.log(greetings.warm + ' ' + names[i] + ' (' + n + ' people left)');
}
// Here, the comma operator can be used in a while loop
// which clarifies what the while loop is searching for
// in a cleaner way:
function findFirstParentTag(position, tag) {
    while (position = position.parent(), position.tagName !== tag);
    return position;
}
// vs:
function findFirstParentTag(position, tag) {
    position = position.parent();
    while (position.tagName !== tag) {
        position = position.parent();
    }
    return position;
}
// Confusing use of the operator to assign variables:
var a = (1, 2, 3, 4); // 'a' is set to 4, as that is the last evaluated statement
Listing 2-28.
Specifying Multiple Expressions Using the Comma Operator
The output is
hello bob (3 people left)
hello jim (2 people left)
hello sue (1 people left)
hello bob (2 people left)
hello jim (1 people left)
hello sue (0 people left)

How It Works

The JavaScript interpreter treats the comma operator as a separation of expressions. It works similarly to the semicolon (which explicitly closes a statement). It has limited use, and in fact it can be quite confusing to use. It works best inside for and while loops (as demonstrated).
Another popular use of the comma operator is attempting to use them in place of semicolons. Many large libraries, such as Zepto.JS, feature little to no semicolons in their source code, and rely on the comma operator instead, as they believe this reads better. This is completely not recommended, as it is trivially easy to get stung by doing this, especially because JavaScript has a feature called ASI (automatic semicolon insertion), which will cause the parser to automatically insert semicolons in your code to close of statements, sometimes in undesirable places. This book doesn’t cover ASI rules simply because if you stick to the best practice of using semicolons, your code will work .
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.22.74.160