JavaScript Common Errors
- Previous page JS best practices
- Next page JS performance
This chapter points out some common JavaScript errors.
Unexpected use of assignment operator
If the programmer uses if
Unexpected use of assignment operator in=
)instead of comparison operator(===
),JavaScript programs may produce some unpredictable results.
This if
The statement returns false
(As expected),because x is not equal to 10:
var x = 0; if (x == 10)
This if
The statement returns true
(Maybe not as expected),because 10 is true:
var x = 0; if (x = 10)
This if
The statement returns false
(Maybe not as expected),because 0 is false:
var x = 0; if (x = 0)
Assignment always returns the value of the assignment.
Expected loose comparison
In loose comparison, data type is not important. This if
The statement returns true
:
var x = 10; var y = "10"; if (x == y)
In strict comparison, data type is indeed important. This if
The statement returns false
:
var x = 10; var y = "10"; if (x === y)
A common mistake is to forget to use switch
The statement uses strict comparison:
This switch
The statement will display a prompt box:
var x = 10; switch(x) { case 10: alert("Hello"); }
This switch
The statement will not display a prompt box:
var x = 10; switch(x) { case "10": alert("Hello"); }
Confusing addition and concatenation
AdditionforNumeric.
Cascading (Concatenation)forString.
In JavaScript, both operations use the same +
Operator.
Therefore, adding numbers as numbers will produce different results from adding numbers as strings:
var x = 10 + 5; // The result in x is 15 var x = 10 + "5"; // The result in x is "105"
It is difficult to predict the result when two variables are added:
var x = 10; var y = 5; var z = x + y; // The result in z is 15 var x = 10; var y = "5"; var z = x + y; // The result in z is "105"
Misleading floating-point
All numbers in JavaScript are stored as 64-bitFloating-point numbers (Floats).
All programming languages, including JavaScript, have difficulties in handling floating-point values:
var x = 0.1; var y = 0.2; var z = x + y // The result in z will not be 0.3
To solve the above problem, please use multiplication and division operations:
Example
var z = (x * 10 + y * 10) / 10; // The result in z will be 0.3
Line breaks in JavaScript strings
JavaScript allows you to wrap a statement into two lines:
Example 1
var x = "Hello World!";
But, it's not correct to wrap lines in the middle of a string:
Example 2
var x = "Hello World!";
If you need to wrap lines in a string, you must use the backslash:
Example 3
var x = "Hello \ World!";
Misplaced semicolon
Because of a misplaced semicolon, this code block will always execute regardless of the value of x:
if (x == 19); { // code block }
Line breaks in return statements
Closing statements at the end of a line is the default behavior of JavaScript.
That's why the following two examples return the same result:
Example 1
function myFunction(a) { var power = 10 return a * power }
Example 2
function myFunction(a) { var power = 10; return a * power; }
JavaScript also allows you to wrap a statement into two lines.
That's why Example 3 will also return the same result:
Example 3
function myFunction(a) { var power = 10; return a * power; }
But, if you put return
What will happen if the statement is wrapped into two lines?
Example 4
function myFunction(a) { var power = 10; return a * power; }
This function will return undefined
!
Why? Because JavaScript assumes that you mean:
Example 5
function myFunction(a) { var power = 10; return; a * power; }
Explanation
If a statement is incomplete:
var
JavaScript will complete this statement by reading the next line:
power = 10;
But since this statement is complete:
return
JavaScript will automatically close this statement:
return;
This happens because, in JavaScript, using semicolons to close (end) statements is optional.
JavaScript closes return
Statement, because it is a complete statement itself.
So, never put return
Statements are wrapped in line breaks.
Access arrays through named indices
Many programming languages support arrays with named indices.
Array with named indices is called an associative array (or hash).
JavaScript Not supportedArray with named indices.
In JavaScript,ArrayUsingNumeric indices:
Example
var person = []; person[0] = "Bill"; person[1] = "Gates"; person[2] = 46; var x = person.length; // person.length will return 3 var y = person[0]; // person[0] will return "Bill"
In JavaScript,ObjectsUsingNamed indices.
If you use named indices, JavaScript will redefine the array as a standard object when accessing the array.
After automatic redefinition, array methods or properties will produce undefined or incorrect results:
Example
var person = []; person["firstName"] = "Bill"; person["lastName"] = "Gates"; person["age"] = 46; var x = person.length; // person.length will return 0 var y = person[0]; // person[0] will return undefined
Use commas to end the definition
Trailing commas in object and array definitions are legal in ECMAScript 5.
Object instance:
person = {firstName:"Bill", lastName:"Gates", age:62,}
Array instance:
points = [35, 450, 2, 7, 30, 16,];
Warning!!
Internet Explorer 8 will crash.
JSON does not allow trailing commas.
JSON:
person = {firstName:"Bill", lastName:"Gates", age:62}
JSON:
points = [35, 450, 2, 7, 30, 16];
Undefined is not Null
JavaScript objects, variables, properties, and methods can be undefined.
Additionally, the value of an empty JavaScript object can be null
.
This might make it a bit difficult to test if the object is empty.
You can test if the type is undefined
To test if an object exists:
Example
if (typeof myObj === "undefined")
But you cannot test whether the object is null
because if the object is undefined, an error will be thrown:
Incorrect:
if (myObj === null)
To solve this problem, you must test whether the object is null
Instead of undefined.
But this will still cause an error:
Incorrect:
if (myObj !== null && typeof myObj !== "undefined")
Therefore, before testing non-null, you must first test undefined:
Correct:
if (typeof myObj !== "undefined" && myObj !== null)
expect block scope
JavaScript does notcreates a new scope for each code block.
Many programming languages are like this, but JavaScript Not at all.
believes that this code will return undefined
is a common mistake for new JavaScript developers:
Example
for (var i = 0; i < 10; i++) { // Code block } return i;
- Previous page JS best practices
- Next page JS performance