JavaScript Primer: Using JavaScript Operators

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

Listing 5-23. Checking to See Whether an Object Has a Property in the jsdemo.html File <!DOCTYPE HTML>

<html>

<head>

<title>Example</title>

<script src=”angular.js”></script>

<script type=”text/javascript”>

var myData = {

name: “Adam”,

weather: “sunny”,

};

var hasName = “name” in myData;

var hasDate = “date” in myData;

console.log(“HasName: ” + hasName);

console.log(“HasDate: ” + hasDate);

</script>

</head>

<body>

This is a simple example

</body> </html>

In this example, I test for a property that exists and one that doesn’t. The value of the hasName variable will be true, and the value of the hasDate property will be false, as follows:

HasName: true

HasDate: false

1. Using JavaScript Operators

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

2. 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. Listing 5-24 shows the use of both (which will be familiar if you have worked with pretty much any programming language).

Listing 5-24. Using the if/else and switch Conditional Statements in the jsdemo.html File

<!DOCTYPE HTML>

<html>

<head>

<title>Example</title>

<script src=”angular.js”></script>

<script type=”text/javascript”>

var name = “Adam”;

if (name == “Adam”) {

console.log(“Name is Adam”);

} else if (name == “Dacqui”) {

console.log(“Name is Dacqui”);

} else {

console.log(“Name is neither Adam or Dacqui”);

}

switch (name) {

case “Adam”:

console.log(“Name is Adam”);

break;

case “Dacqui”:

console.log(“Name is Dacqui”);

break;

default:

console.log(“Name is neither Adam or lacqui”);

break;

}

</script>

</head>

<body>

This is a simple example

</body>

</html>

The results from the listing are as follows:

Name is Adam

Name is Adam

2. The Equality Operator vs. the Identity Operator

The equality and identity operators are of particular note. The equality operator will attempt to coerce operands to the same type in order to assess equality. This is a handy feature, as long as you are aware it is happening. Listing 5-25 shows the equality operator in action.

Listing 5-25. Using the Equality Operator in the jsdemo.html File

<!DOCTYPE HTML>

<html>

<head>

<title>Example</title>

<script src=”angular.js”></script>

<script type=”text/javascript”>

var firstVal = 5;

var secondVal = “5”;

if (firstVal == secondVal) {

console.log(“They are the same”);

} else {

console.log(“They are NOT the same”);

}

</script>

</head>

<body>

This is a simple example

</body>

</html>

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. 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 equals signs, rather than the two of the equality operator), as shown in Listing 5-26.

Listing 5-26. Using the Identity Operator in the jsdemo.html File

<!DOCTYPE HTML>

<html>

<head>

<title>Example</title>

<script src=”angular.js”></script>

<script type=”text/javascript”>

var firstVal = 5;

var secondVal = “5”;

if (firstVal === secondVal) {

console.log(“They are the same”);

} else {

console.log(“They are NOT the same”);

}

</script>

</head>

<body>

This is a simple example

</body>

</html>

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

They are NOT the same

JavaScript primitives are compared by value, but JavaScript objects are compared by reference. Listing 5-27 shows how JavaScript handles equality and identity tests for objects.

Listing 5-27. Performing Equality and Identity Tests on Objects in the jsdemo.html File

<!DOCTYPE HTML>

<html>

<head>

<title>Example</title>

<script src=”angular.js”></script>

<script type=”text/javascript”>

var myData1 = {

name: “Adam”,

weather: “sunny”,

};

var myData2 = {

name: “Adam”,

weather: “sunny”,

};

var myData3 = myData2;

var testl = myDatal == myDatal;

var test2 = myData2 == myData3;

var test3 = myDatal === myDatal;

var test4 = myData2 === myData3;

console.log(“Test 1: ” + test1 + ” Test 2: ” + test2);

console.log(“Test 3: ” + test3 + ” Test 4: ” + test4);

</script>

</head>

<body>

This is a simple example

</body>

</html>

The results from this script are as follows:

Test 1: false Test 2: true

Test 3: false Test 4: true

Listing 5-28 shows the same tests performed on primitives.

Listing 5-28. Performing Equality and Identity Tests on Objects in the jsdemo.html File

<!DOCTYPE HTML>

<html>

<head>

<title>Example</title>

<script src=”angular.js”></script>

<script type=”text/javascript”>

var myData1 = 5;

var myData2 = “5”;

var myData3 = myData2;

var test1 = myData1 == myData2;

var test2 = myData2 == myData3;

var test3 = myDatal === myData2;

var test4 = myData2 === myData3;

console.log(“Test 1: ” + test1 + ” Test 2: ” + test2);

console.log(“Test 3: ” + test3 + ” Test 4: ” + test4);

</script>

</head>

<body>

This is a simple example

</body>

</html>

The results from this script are as follows:

Test 1: true Test 2: true

Test 3: false Test 4: true

Tip AngularJS extends the built-in comparison support with the angular.equals method, which takes two objects or values as its arguments and will return true if they pass the identity comparison (===) or if both arguments are objects and all of their properties pass the identity comparison. I tend not to use this method, so I have not included a demonstration in this chapter.

3. Explicitly Converting Types

The string concatenation operator (+) has a higher precedence than the addition operator (also +), which means that 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 Listing 5-29.

Listing 5-29. String Concatentation Operator Precedence in the jsdemo.html File

<!DOCTYPE HTML>

<html>

<head>

<title>Example</title>

<script src=”angular.js”></script>

<script type=”text/javascript”>

var myDatal = 5 + 5;

var myData2 = 5 + “5”;

console.log(“Result 1: ” + myData1);

console.log(“Result 2: ” + myData2);

</script>

</head>

<body>

This is a simple example

</body>

</html>

The result from 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 over-eager 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.

3.1. 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 Listing 5-30.

Listing 5-30. Using the number.toString Method in the jsdemo.html File

<!DOCTYPE HTML>

<html>

<head>

<title>Example</title>

<script src=”angular.js”></script>

<script type=”text/javascript”>

var myDatal = (5).toString() + String(5);

console.log(“Result: ” + myData1);

</script>

</head>

<body>

This is a simple example

</body>

</html>

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 Table 5-4. All of the methods shown in the table are defined by the number type.

3.2. 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 Listing 5-31.

Listing 5-31. Converting Strings to Numbers in the jsdemo.html File

<!DOCTYPE HTML>

<html>

<head>

<title>Example</title>

<script src=”angular.js”></script>

<script type=”text/javascript”>

var firstVal = “5”;

var secondVal = “5”;

var result = Number(firstVal) + Number(secondVal);

console.log(“Result: ” + result);

</script>

</head>

<body>

This is a simple example

</body>

</html>

The output from this script is as follows:

Result: 10

The Number method is strict in the way that is 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 5-5.

Source: Freeman Adam (2014), Pro AngularJS (Expert’s Voice in Web Development), Apress; 1st ed. edition.

Leave a Reply

Your email address will not be published. Required fields are marked *