forked from chuanxshi/javascript-patterns
-
Notifications
You must be signed in to change notification settings - Fork 0
/
avoiding-implied-typecasting.html
44 lines (36 loc) · 1.31 KB
/
avoiding-implied-typecasting.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
<!doctype html>
<html lang="en">
<head>
<title>JavaScript Patterns</title>
<meta charset="utf-8">
</head>
<body>
<script>
/* Title: Implied Typecasting
* Description: avoid implied typecasting
*/
var zero = 0;
/* antipattern
* JavaScript implicitly typecasts variables when you compare them.
* That's why comparisons such as false == 0 or "" == 0 return true.
*/
if (zero == false) {
// this block is executed...
}
// preferred
/* To avoid confusion caused by the implied typecasting,
* always use the === and !== operators that check both the values and the type of the expressions you compare
*/
if (zero === false) {
// not executing because zero is 0, not false
}
/* NOTE: There's another school of thought that subscribes to the opinion that it's redundant to use === when == is
* sufficient. For example, when you use typeof you know it returns a string, so there's no reason to use strict
* equality. However, JSLint requires strict equality; it does make the code look consistent and reduces the mental
* effort when reading code. ("Is this == intentional or an omission?")
*/
// References
// http://net.tutsplus.com/tutorials/javascript-ajax/the-essentials-of-writing-high-quality-javascript/
</script>
</body>
</html>