Using JavaScript Operators in Angular

You are currently viewing Using JavaScript Operators in Angular

JavaScript defines a largely standard set of operators. I’ve summarized the most useful in the following Table.

NameDescription
++, — Pre- or post-increment and decrement
+, -, *, /, % Addition, subtraction, multiplication, division, remainder
<, <=, >, >= Less than, less than or equal to, more than, more than or equal to
==, != Equality and inequality tests
===, !== Identity and nonidentity tests
&&, || Logical AND and OR (|| is used to coalesce null values)
= Assignment
+ String concatenation
?: Three-operand conditional statement

Using Conditional Statements

Many of the JavaScript operators are used in conjunction with conditional statements. In this book, I tend to use the if/else and switch statements. The following example shows the use of both, which will be familiar if you have worked with pretty much any programming language.

let name = "Adam";
if (name == "Adam") {
 console.log("Name is Adam");
} else if (name == "Jacqui") {
 console.log("Name is Jacqui");
} else {
 console.log("Name is neither Adam or Jacqui");
}
switch (name) {
 case "Adam":
 console.log("Name is Adam");
 break;
 case "Jacqui":
 console.log("Name is Jacqui");
 break;
 default:
 console.log("Name is neither Adam or Jacqui");
 break;
}

The results from the listing are as follows:

Name is Adam

Name is Adam

The Equality Operator vs. the Identity Operator

The equality and identity operators are of particular note. The equality operator will attempt to coerce (convert) operands to the same type to assess equality. This is a handy feature, as long as you are aware it is happening. The following example shows the equality operator in action.

let firstVal = 5;
let secondVal = "5";
if (firstVal == secondVal) {
 console.log("They are the same");
} else {
 console.log("They are NOT the same");
}

The output from this script is as follows:

They are the same

JavaScript is converting the two operands into the same type and comparing them. In essence, the equality operator tests that values are the same irrespective of their type. To help guard against this kind of error, the TypeScript compiler will generate a warning, although it will still generate the JavaScript code since this type of comparison is legal:

Operator ‘==’ cannot be applied to types ‘number’ and ‘string’.

If you want to test to ensure that the values and the types are the same, then you need to use the identity operator (===, three equal signs, rather than the two of the equality operator), as shown in the following example.

let firstVal = 5;
let secondVal = "5";
if (firstVal === secondVal) {
 console.log("They are the same");
} else {
 console.log("They are NOT the same");
}

In this example, the identity operator will consider the two variables to be different. This operator doesn’t coerce types. The result of this script is as follows:

They are NOT the same



Explicitly Converting Types

The string concatenation operator (+) has higher precedence than the addition operator (also +), which means JavaScript will concatenate variables in preference to adding. This can cause confusion because JavaScript will also convert types freely to produce a result—and not always the result that is expected, as shown in the following example.

let myData1 = 5 + 5;
let myData2 = 5 + "5";
console.log("Result 1: " + myData1);
console.log("Result 2: " + myData2);

The result of this script is as follows:

Result 1: 10

Result 2: 55

The second result is the kind that causes confusion. What might be intended to be an addition operation is interpreted as string concatenation through a combination of operator precedence and overeager type conversion. To avoid this, you can explicitly convert the types of values to ensure you perform the right kind of operation, as described in the following sections.

Converting Numbers to Strings

If you are working with multiple number variables and want to concatenate them as strings, then you can convert the numbers to strings with the toString method, as shown in the following example.

let myData1 = (5).toString() + String(5);
console.log("Result: " + myData1);

Notice that I placed the numeric value in parentheses, and then I called the toString method. This is because you have to allow JavaScript to convert the literal value into a number before you can call the methods that the number type defines. I have also shown an alternative approach to achieve the same effect, which is to call the String function and pass in the numeric value as an argument. Both of these techniques have the same effect, which is to convert a number to a string, meaning that the + operator is used for string concatenation and not addition. The output from this script is as follows:

Result: 55

There are some other methods that allow you to exert more control over how a number is represented as a string. I briefly describe these methods in the following Table. All of the methods shown in the table are defined by the number type.

MethodDescription
toString() This method returns a string that represents a number in base 10.
toString(2)toString(8)
toString(16)
This method returns a string that represents a number in binary, octal, or hexadecimal notation.
toFixed(n) This method returns a string representing a real number with the n digits after the decimal point.
toExponential(n) This method returns a string that represents a number using exponential notation with one digit before the decimal point and n digits after
toPrecision(n) This method returns a string that represents a number with n significant digits, using exponential notation if required.

Converting Strings to Numbers

The complementary technique is to convert strings to numbers so that you can perform addition rather than concatenation. You can do this with the Number function, as shown in the following example.

let firstVal = "5";
let secondVal = "5";
let result = Number(firstVal) + Number(secondVal);
console.log("Result: " + result);

The output from this script is as follows:

Result: 10

The Number function is strict in the way that it parses string values, but there are two other functions you can use that are more flexible and will ignore trailing non-number characters. These functions are parseInt and parseFloat. I have described all three methods in Table.

MethodDescription
Number(str) This method parses the specified string to create an integer or real value.
parseInt(str) This method parses the specified string to create an integer value.
parseFloat(str) This method parses the specified string to create an integer or real value.



This Post Has One Comment

Leave a Reply