JavaScript Misunderstanding


In this chapter, we will discuss the misunderstanding of using JavaScript.


Common Errors of Assignment Operators

In a JavaScript program, if you use the equal sign (=) of the assignment operator in the if conditional statement, an error result will be generated. The correct way is to use the two equal signs (==) of the comparison operator.

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

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

 Try It! 

The if conditional statement returns true (not what we expected) because the execution of the conditional statement assigns a value of 10 to x, and 10 is true:

var x = 0;
if (x = 10)

 Try It! 

The if conditional statement returns false (not what we expected) because the execution of the conditional statement assigns a value of 0 to x, and 0 is false:

var x = 0;
if (x = 0)

Try It! 

NoteThe assignment statement returns the value of the variable.

Common Errors of Comparison Operators

In conventional comparisons, the data type is ignored, and the following if conditional statement returns true:

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

 Try It! 

In strict comparison operations, === is the identity operator, and the value and type of the expression are checked at the same time. The following if conditional statement returns false:

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

 Try It! 

This kind of error often appears in switch statements, which use the identity operator (===) for comparison:

The following example will execute the alert pop-up window:

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

 Try It! 

The following instances will not execute the alert popup due to inconsistent types:

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

 Try It! 


Addition and Concatenation Notes

Addition is the addition of two numbers.

The Concatenation is the connection of two strings.

Both addition and concatenation in JavaScript use the + operator.

Next, we can view the difference between the addition of two numbers and the connection of numbers and strings through examples:

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

 Try It! 

The results of using variable addition are also inconsistent:

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

var x = 10;
var y = "5";
var z = x + y; // the result of z is "105"

 Try It! 


Precautions for Using Floating-Point Data

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

All programming languages, including JavaScript, are difficult to determine the accuracy of floating-point data:

var x = 0.1;
var y = 0.2;
var z = x + y // The result of z is 0.30000000000000004
if (z == 0.3) // return false

 Try It! 

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

Example

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

Try It! 

For more information, please refer to: Precision problems and solutions in JavaScript


JavaScript String Branch

JavaScript allows us to use line-breaking statements in strings:

Example 1

var x =
"Hello World!";

 Try It! 

However, using carriage return and line feed directly in the string will result in an error:

Example 2

var x = "Hello
World!";

 Try It! 

We can select the development tool or press F12 to view the error message:

Screenshot 2021-12-06 164056.png

String breaks 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 method body, and the method body of the original if statement is executed as an independent code block, resulting in incorrect output results.

Because of the wrong semicolon, the code block in the if statement will be executed:

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

 Try It! 


Precautions for The Use of The Return Statement

By default, JavaScript automatically ends at the last line of the code.

The following two examples return the same result (one with a semicolon and 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 end a statement.

The following example returns the same result:

Example 3

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

Try It! 

However, the following instance results will return undefined :

Example 4

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

 Try It! 

Why is there such a result? Because in JavaScript, the code of example 4 is consistent with the following code:

function myFunction(a) {
    var
    power = 10;
    return; // End of semicolon, return undefined
    a * power;
}

Explaination

If it is an incomplete statement, as shown below:

var

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

power = 10;

But since such a statement is complete:

return

JavaScript will automatically close the statement:

return;

In JavaScript, the semicolon is optional.

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

NoteNote: There is no need to break the return statement.

Use Names to Index In The Array

Many programming languages allow the use of names as indexes in arrays.

Arrays that use names as indexes are called associative arrays (or hashes).

JavaScript does not support using names to index arrays, 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, an object using the name as an index .

If you use the name as the index, when accessing the array, JavaScript will redefine the array as a standard object.

After performing this operation, the methods and attributes of the array 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! 


Define the Array Elements Without Adding A Comma At The End

Adding a comma after the last value of the array has no problem with the syntax, but different browsers may get different results.

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

The correct way to define:

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

Define the Object Without Adding A Comma At The End

The wrong way to define:

websites = { site : "TutorialFish.com" , url : "www.tutorialfish.com" , like : 460 ,} 

The correct way to define:

websites = { site : "TutorialFish.com" , url : "www.tutorialfish.com" , like : 460 } 

Undefined is Not Null

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

An object can be null only if it is defined, otherwise it is undefined.

If we want to test whether the object exists, an error will be thrown when the object is not yet defined.

Wrong usage:

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

The correct way is that we need to use typeof first to detect whether the object is defined:

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

Block Scope

In each code block, JavaScript does not create a new scope. Generally, the scope of each code block is global.

The variable i of the following code returns 10 instead of undefined:

Example

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

Try It!