Easy Tutorial
❮ Jsref Replace Js Htmldom ❯

JavaScript Common Pitfalls

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


Misuse of Assignment Operators

In JavaScript programs, if you use the assignment operator (=) in an if condition, it will produce an incorrect result. The correct method is to use the comparison operator (==) with two equal signs.

if condition returns false (as expected) because x is not equal to 10:

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

if condition returns true (not as expected) because the condition assigns 10 to x, and 10 evaluates to true:

var x = 0;
if (x = 10)

if condition returns false (not as expected) because the condition assigns 0 to x, and 0 evaluates to false:

var x = 0;
if (x = 0)

| | The assignment statement returns the value of the variable. | | --- | --- |

Common Errors with Comparison Operators

In regular comparisons, data types are ignored. The following if condition returns true:

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

In strict comparison, the === operator checks both the value and the type. The following if condition returns false:

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

This error often occurs in switch statements, which use the === operator for comparison:

The following example will execute the alert:

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

The following example, due to type inconsistency, will not execute the alert:

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

Addition and Concatenation Considerations

Addition is the sum of two numbers.

Concatenation is the joining of two strings.

JavaScript uses the + operator for both addition and concatenation.

We can see the difference between adding two numbers and concatenating a number with a string in the following examples:

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

Using variables also results in different outcomes:

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

Floating Point Data Considerations

All data in JavaScript is stored as 64-bit floating-point numbers (float).

All programming languages, including JavaScript, struggle with 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

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

Example

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

For more details, refer to: JavaScript Precision Problems and Solutions


JavaScript String Line Breaks

JavaScript allows us to use line breaks in strings:

Example 1

var x = "Hello World!";

However, direct carriage returns in strings will cause errors:

Example 2

var x = "Hello World!";

You can check for errors using your development tools or by pressing F12:

String line breaks require the backslash (), as shown:

Example 3

var x = "Hello \World!";

Incorrect Use of Semicolons

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

Due to the semicolon error, the code block in the if statement will always execute:

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

Return Statement Considerations

JavaScript automatically ends statements at the end of a line.

The following two examples return the same result (one has a semicolon, the other does not):

Example 1

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

Example 2

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

JavaScript can also represent a statement across multiple lines.

The following example returns the same result:

Example 3

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

However, the following example returns undefined:

Example 4

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

This happens because in JavaScript, the semicolon is optional. Since return is a complete statement, JavaScript automatically closes the return statement.

| | Note: Avoid line breaks in return statements. | | --- | --- |


Using Names as Array Indexes

Many programming languages allow using names as array indexes.

Arrays with named indexes are called associative arrays (or hashes).

JavaScript does not support arrays with named indexes; it only allows numeric indexes.

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"

In JavaScript, objects use named indexes.

If you use names as indexes, JavaScript redefines the array as a standard object, and array methods and properties will no longer work:

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

Trailing Commas in Array Definitions

Adding a trailing comma at the end of an array element may cause inconsistencies across different browsers.

var colors = [5, 6, 7,]; // The length of the array might be 3 or 4.

The correct way to define an array is:

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

Trailing Commas in Object Definitions

Incorrect way to define an object:

websites = {site:"tutorialpro.org", url:"www.tutorialpro.org", like:460,}

Correct way to define an object:

websites = {site:"tutorialpro.org", url:"www.tutorialpro.org", like:460}

Undefined vs Null

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

An object must be defined to be null; otherwise, it is undefined.

To test if an object exists, using the incorrect method may throw an error if the object is not defined:

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

The correct way is to first check if the object is defined using typeof:

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

Block Scope

JavaScript does not create a new scope within each code block; typically, all blocks share the same global scope.

The variable i in the following code returns 10, not undefined:

Example

for (var i = 0; i < 10; i++) {
    // some code
}
return i;
❮ Jsref Replace Js Htmldom ❯