YouTip LogoYouTip

Js Mistakes

In this chapter, we will discuss common mistakes when using JavaScript. * * * ## Assignment Operator Mistake In JavaScript programs, using the assignment operator's equals sign (=) in an if conditional statement will produce an incorrect result. The correct method is to use the comparison operator's double equals (==). The **if** condition returns **false** (as expected) because x is not equal to 10: The **if** condition returns **true** (not as expected) because the condition statement executes the assignment of 10 to x, and 10 is true: The **if** condition returns **false** (not as expected) because the condition statement executes the assignment of 0 to x, and 0 is false: | ![Image 1: Note](#) | An assignment statement returns the value of the variable. | | --- | ## Common Mistake 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) [Try it Β»](#) In strict comparison, === is the strict equality operator, which checks both the value and type of the expressions. The following if condition returns false: var x = 10; var y = "10"; if (x === y) [Try it Β»](#) This mistake often occurs in switch statements, which use the strict equality operator (===) for comparison: The following example will execute the alert popup: var x = 10; switch(x) { case 10: alert("Hello"); } [Try it Β»](#) The following example will not execute the alert popup due to inconsistent types: var x = 10; switch(x) { case"10": alert("Hello"); } [Try it Β»](#) * * * ## Addition vs. Concatenation **Addition** is adding two **numbers**. **Concatenation** is joining two **strings**. JavaScript uses the + operator for both addition and concatenation. Next, we can see the difference between adding two numbers and concatenating a number with a string through examples: var x = 10 + 5;// The result of x is 15 var x = 10 + "5";// The result of x is "105" [Try it Β»](#) Using variables also yields inconsistent results: 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 Β»](#) * * * ## Floating-Point Number Considerations All data in JavaScript is stored as 64-bit **floating-point numbers (float)**. In all programming languages, including JavaScript, the precision of floating-point numbers is difficult to determine: var x = 0.1; var y = 0.2; var z = x + y// The result of z is 0.30000000000000004 if (z == 0.3)// Returns false [Try it Β»](#) To solve this problem, you can use integer multiplication and division: ### Example var z = (x * 10 + y * 10) / 10;// The result of z is 0.3 [Try it Β»](#) For more information, you can refer to: (#) * * * ## JavaScript String Line Breaks JavaScript allows us to use line breaks in strings: ### Example 1 var x = "Hello World!"; [Try it Β»](#) However, directly using a carriage return in a string will cause an error: ### Example 2 var x = "Hello World!"; [Try it Β»](#) We can view the error message by selecting developer tools or pressing F12: !(#) String line breaks require 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. The original body of the if statement is executed as a separate code block, leading to incorrect output. Due to incorrect semicolon usage, the code block inside the if statement will always execute: if (x == 19); { // code block } [Try it Β»](#) * * * ## Return Statement Considerations JavaScript automatically ends a line at the end by default. 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 a statement, meaning a statement can be split across lines. The following example returns the same result: ### Example 3 function myFunction(a) { var power = 10; return a * power; } [Try it Β»](#) However, the following example will return **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 equivalent to the following code: function myFunction(a) { var power = 10; return; // Semicolon ends the statement, returning undefined a * power;} ### Explanation If it is an incomplete statement, like this: var JavaScript will try to read the statement on the next line: power = 10; But since this 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. | ![Image 3: Note](#) | **Note:** Do not break the return statement across lines. | | --- | * * * ## Using Names as Array Indices Many programming languages allow using names as array indices. Arrays that use names as indices are called associative arrays (or hashes). JavaScript does not support using names to index arrays; it only allows numeric indices. ### Example var person = []; person = "John"; person = "Doe"; person = 46; var x = person.length;// person.length returns 3 var y = person;// person returns "John" [Try it Β»](#) In JavaScript, **objects** use **names as indices**. If you use names as indices, when accessing the array, JavaScript will redefine the array as a standard object. After performing this operation, the array's methods and properties can no longer be used, otherwise an error will occur: ### Example var person = []; person = "John"; person = "Doe"; person = 46; var x = person.length;// person.length returns 0 var y = person;// person returns undefined [Try it Β»](#) * * * ## Do Not Add a Trailing Comma When Defining Array Elements Although adding a comma after the last value in an array is syntactically correct, it may yield different results in different browsers. var colors = [5, 6, 7,]; // The length of this array may be 3 or 4. Correct definition: points = [40, 100, 1, 5, 25, 10]; * * * ## Do Not Add a Trailing Comma When Defining Objects Incorrect definition: websites = {site:"", url:"www.", like:460,} Correct definition: websites = {site:"", url:"www.", like:460} * * * ## Undefined Is Not Null In JavaScript, **null** is for objects, while **undefined** is for variables, properties, and methods. An object can only be null if it is defined; otherwise, it is undefined. If we want to test whether an object exists, it will throw an error if the object is not yet defined. Incorrect usage: if (myObj !== null && typeof myObj !== "undefined") The correct way is to first use typeof to check if 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. 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 Β»](#)
← Character IsdigitJs Strict β†’