Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

JavaScript Common Mistakes

JavaScript Common Mistakes

In this chapter, we will discuss common mistakes in using JavaScript.


Assignment Operator Mistakes

In a JavaScript program, if you use the assignment operator's single equal sign (=) in an if condition, it will produce an incorrect result. The correct approach is to use the comparison operator's double equal sign (==).

if The conditional statement returns false (as expected) because x is not equal to 10:

var x = 0;
if (x == 10)

Try it »

if The conditional statement returns true (not as expected) because the condition assigns 10 to x, and 10 is true:

var x = 0;
if (x = 10)

Try it »

if The conditional statement returns false (not as expected) because the condition assigns 0 to x, and 0 is false:

var x = 0;
if (x = 0)

Try it »

Note An assignment statement returns the value of the variable.

Common Comparison Operator Mistakes

In a regular comparison, data types are ignored, so the following if statement returns true:

var x = 10;
var y = "10";
if (x == y)

Try it »

In a strict comparison, === is the identity operator, which checks both the value and the type of the expression, so the following if statement returns false:

var x = 10;
var y = "10";
if (x === y)

Try it »

This mistake often occurs in switch statements, which use the identity operator (===) for comparison:

The following example will execute an alert pop-up:

var x = 10;
switch(x) {
    case 10: alert("Hello");
}

Try it »

The following example will not execute an alert pop-up because the types do not match:

var x = 10;
switch(x) {
    case "10": alert("Hello");
}

Try it »


Addition and Concatenation Cautions

Additionare twoDigitadded together.

Connectionare twoStringto connect locally.

Both addition and concatenation in JavaScript use the + operator.

Next, we can look at examples to see the difference between adding two numbers and concatenating a number with a string:

var x = 10 + 5; // x is 15
var x = 10 + "5"; // x is "105"

Try it »

Adding variables can also give inconsistent results:

var x = 10;
var y = 5;
var z = x + y; // z is 15

var x = 10;      

var y = "5";      

var z =   x + y;             // z 的结果为 "105"

Try it »


Floating-Point Data Cautions

All numbers in JavaScript are stored as 64-bitfloating-point numbers (float) values.

All programming languages, including JavaScript, have difficulty determining the precision of floating-point data:

var x = 0.1;
var y = 0.2;
var z = x + y // z is 0.30000000000000004
if (z == 0.3) // returns false

Try it »

To solve the above problem, you can use integer multiplication and division:

Example

var z = (x * 10 + y * 10) / 10; // z is 0.3

Try it »

For more information, refer to:Precision Issues and Solutions in JavaScript


JavaScript String Line Breaks

JavaScript allows us to break a line within a string:

Example 1

var x =
"Hello World!";

Try it »

However, using a direct carriage return or line break inside a string will cause an error:

Example 2

var x = "Hello
World!";

Try it »

We can see the error message by selecting developer tools or pressing F12:

To break a line in a string, you need to use a backslash (), as shown below:

Example 3

var x = "Hello \
World!";

Try it »


Incorrect Use of Semicolons

In the following example, the if statement loses its body, and the original body of the if statement is executed as a separate block of code, leading to an incorrect output.

Because of the incorrect use of a semicolon, the code block in the if statement will always execute:

if (x == 19);
{
    // code block 
}

Try it »


return Statement Cautions

By default, JavaScript automatically ends a statement at the end of a line.

The following two examples return the same result (one with a semicolon, one without):

Example 1

function myFunction(a) {
    var power = 10 
    return a * power
}

Try it »

Example 2

function myFunction(a) {
    var power = 10;
    return a * power;
}

Try it »

JavaScript can also use multiple lines to represent one statement; that is, a statement can span lines.

The following examples return the same result:

Example 3

function myFunction(a) {
    var
    power = 10; 
    return a * power;
}

Try it »

However, the following example returns undefined:

Example 4

function myFunction(a) {
    var
    power = 10; 
    return
    a * power;
}

Try it »

Why does this happen? Because in JavaScript, the code in example 4 is identical to the following code:



function myFunction(a) {

    var

    power = 10;  

    return;       // 分号结束,返回 undefined

    a * power;

}

Parsing

If a statement is incomplete, as shown below:



var

JavaScript will try to read the statement on the second line:



power = 10;

But because such a statement is complete:



return

JavaScript will automatically close the statement:



return;

In JavaScript, semicolons are optional.

Since return is a complete statement, JavaScript will close the return statement.

Note **Note:** Do not break a line after a return statement.

Using Names as Array Indexes

Many programming languages allow names to be used as array indexes.

An array that uses names as indexes is called an associative array (or hash).

JavaScript does not support using names as array indexes; only numeric indexes are allowed.

Example

var person = [];
person[0] = "John";
person[1] = "Doe";
person[2] = 46;
var x = person.length; // person.length returns 3
var y = person[0]; // person[0] returns "John"

Try it »

In JavaScript, object Use names as indexes。

If you use names as indexes, when you access the array, JavaScript will redefine the array as a standard object.

After doing this, the array's methods and properties can no longer be used, otherwise an error will occur:

Example

var person = [];
person["firstName"] = "John";
person["lastName"] = "Doe";
person["age"] = 46;
var x = person.length; // person.length returns 0
var y = person[0]; // person[0] returns undefined

Try it »


Do Not Add a Trailing Comma When Defining Array Elements

Adding a comma after the last value of an array may be syntactically valid, but can produce different results in different browsers.

var colors = [5, 6, 7,]; //这样数组的长度可能为3 也可能为4。

Correct way to define:



points = [40, 100, 1, 5, 25, 10];


Do Not Add a Trailing Comma When Defining Objects

Incorrect way to define:



websites = {site:"Runoob Tutorial", url:"www.runoob.com", like:460,}

Correct way to define:



websites = {site:"Runoob Tutorial", url:"www.runoob.com", like:460}


Undefined Is Not Null

In JavaScript, null is used for objects, undefined is used for variables, properties, and methods.

An object can be null only if it has been defined; otherwise it is undefined.

If we want to test whether an object exists, an error will be thrown if the object has not been defined.

Incorrect usage:



if (myObj !== null && typeof myObj !== "undefined") 

The correct way is to first use typeof to check whether the object is defined:



if (typeof myObj !== "undefined" && myObj !== null) 


Block scope

JavaScript does not create a new scope for each code block; generally the scope of each block is global.

In the following code, the variable i returns 10, not undefined:

Example

for (var i = 0; i < 10; i++) {
    // some code
}
return i;

Try it »