In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
How to avoid the 9 mistakes often made by JavaScript developers, many novices are not very clear about this. In order to help you solve this problem, the following editor will explain it in detail. People with this need can come and learn. I hope you can get something.
JavaScript is a scripting language that adds functionality and interaction to web pages, which is easy to understand for beginners who use different programming languages. With some tutorials, you can start using it right away.
But many beginners will make some common mistakes. We will introduce 9 common mistakes (or bad practices) and their solutions to help you become a better JavaScript developer.
Confuse the assignment operator (=) with the equality operator (=, = =)
As the name suggests, the assignment operator is used to assign values to variables. Developers often confuse it with the equality operator.
For example:
Const name = "javascript"; if ((name = "nodejs")) {console.log (name);} / / output-nodejs
In this case, instead of comparing the name variable with the nodejs string, you assign nodejs to the name and output the nodejs to the console.
In JavaScript, two equal signs (= =) and three equal signs (=) are comparison operators.
For the above code, you can compare values using the following methods:
Const name = "javascript"; if (name = = "nodejs") {console.log (name);} / no output / / OR if (name = "nodejs") {console.log (name);} / / no output
The difference between the two comparison operators is that the two equal signs perform a loose comparison and the three equal signs perform a strict comparison.
When comparing roughly, only the values are compared. But strictly speaking, values and data types are to be compared.
The following code better explains this:
Const number = "1"; console.log (number = = 1); / / true console.log (number = 1); / / false
Assign the variable number a value of 1. If you compare number with a double equal sign, it returns true because both values are 1.
However, in the case of three equal signs, false is returned because each value has a different data type.
The expected callback is synchronized
In JavaScript, the callback method is used to handle asynchronous operations. However, Promises and async/await are the preferred methods for handling asynchronous operations, because multiple callbacks can lead to callback hell.
Callbacks are out of sync. After delaying the completion of the operation, they are called as a function.
For example, the global setTimeout receives the callback function as the first parameter and the duration (in milliseconds) as the second parameter:
Function callback () {console.log ("I am the first");} setTimeout (callback, 300); console.log ("I am the last"); / / output / / I am the last / / I am the first
After 300ms, the callback function is called. But the rest of the code runs before it's finished, so the last console.log will run first.
A common mistake made by developers is to misunderstand that callbacks are synchronous, for example, thinking that a value of the callback function is used for other operations.
The mistake is:
Function addTwoNumbers () {let firstNumber = 5; let secondNumber; setTimeout (function () {secondNumber = 10;}, 200); console.log (firstNumber + secondNumber);} addTwoNumbers (); / / NaN
Output NaN because the secondNumber is uncertain. When you run firstNumber+secondNumber, there is still no secondNumber defined, because the setTimeout function performs a callback after 200ms.
The best way is to execute the rest of the code in the callback function:
Function addTwoNumbers () {let firstNumber = 5; let secondNumber; setTimeout (function () {secondNumber = 10; console.log (firstNumber + secondNumber);} addTwoNumbers (); / / 15this reference error
This is a concept that is often misunderstood in JavaScript. To use this in JavaScript, you need to understand what it does. This here is different from this in other languages.
The following is an example of common errors about this:
Const obj = {name: "JavaScript", printName: function () {console.log (this.name);}, printNameIn2Secs: function () {setTimeout (function () {console.log (this.name);}, 2000);},}; obj.printName (); / / JavaScript obj.printNameIn2Secs (); / / undefined
The first result is JavaScript, because this.name correctly points to the object's name property. The second result is undefined because this does not refer to the properties of the object (including name).
The reason is that this depends on the object that is calling the function. Each function has a this variable, but its direction is determined by the object that calls this.
The this of bj.printName () points directly to obj. The this of obj.printNameIn2Secs points directly to obj. However, this does not point to any object in the callback function setTimeout, because no object calls it.
If an object calls setTimeout, it executes obj.setTimeout... . Because there is no object to call this function, the default object (that is, window) is used.
There is no name on window, so undefined is returned.
The best way to retain this references in setTimeout is to use the bind, call, apply, or arrowhead features (introduced in ES6). Unlike regular functions, arrow functions do not create their own this.
So, the following code retains the this reference:
Const obj = {name: "JavaScript", printName: function () {console.log (this.name);}, printNameIn2Secs: function () {setTimeout () = > {console.log (this.name);}, 2000);},}; obj.printName (); / / JavaScript obj.printNameIn2Secs (); / / JavaScript ignores the variability of objects
Reference data types in JavaScript objects are not like raw data types such as strings, numbers, and so on. For example, in key-value pair objects:
Const obj1 = {name: "JavaScript",}; const obj2 = obj1; obj2.name = "programming"; console.log (obj1.name); / / programming
Obj1 and obj2 point to the same address in memory.
In the array:
Const arr1 = [2,3,4]; const arr2 = arr1; arr2 [0] = "javascript"; console.log (arr1); / / ['javascript', 3,4]
One of the mistakes developers often make is to ignore this feature of JavaScript, which can lead to unexpected errors.
If this happens, any attempt to access the original property will return undefined or throw an error.
The best way is to always create a new reference when you want to copy an object. To achieve this, the extension operator (introduced in ES6...) is a perfect solution.
For example, in key-value pair objects:
Const obj1 = {name: "JavaScript",}; const obj2 = {... obj1}; console.log (obj2); / / {name: 'JavaScript'} obj2.name = "programming"; console.log (obj.name); / /' JavaScript'
In the array:
Const arr1 = [2Jing 3jue 4]; const arr2 = [... arr1]; console.log (arr2); / / [2Med 3Jing 4] arr2 [0] = "javascript"; console.log (arr1); / / [2Med 3Jing 4]
Save arrays and objects to browser for storage
When using JavaScript, developers may want to use localStorage to preserve values. However, a common mistake is to save arrays and objects directly in localStorage. LocalStorage only accepts strings.
JavaScript converts the object to a string for preservation. The result is that the object is saved as [Object Object] and the array is saved as a comma-separated string.
For example:
Const obj = {name: "JavaScript"}; window.localStorage.setItem ("test-object", obj); console.log (window.localStorage.getItem ("test-object")); / / [Object Object] const arr = ["JavaScript", "programming", 45]; window.localStorage.setItem ("test-array", arr); console.log (window.localStorage.getItem ("test-array")); / / JavaScript, programming, 45
When you save these objects, it is difficult to access them. For example, for an object, accessing it through .name results in an error. Because [Object Object] is now a string and does not contain the name attribute.
By using JSON.stringify (converting objects to strings) and JSON.parse (converting strings to objects), you can better save locally stored objects and arrays. Objects can be easily accessed in this way.
The correct version of the above code is:
Const obj = {name: "JavaScript"}; window.localStorage.setItem ("test-object", JSON.stringify (obj)); const objInStorage = window.localStorage.getItem ("test-object"); console.log (JSON.parse (objInStorage)); / / {name: 'JavaScript'} const arr = ["JavaScript", "programming", 45]; window.localStorage.setItem ("test-array", JSON.stringify (arr)); const arrInStorage = window.localStorage.getItem ("test-array") Console.log (JSON.parse (arrInStorage)); / / JavaScript, programming, 45
Do not use default values
Setting default values for dynamic variables is a good way to prevent unexpected errors. Here is an example of a common mistake:
Function addTwoNumbers (a, b) {console.log (a + b);} addTwoNumbers (); / / NaN
Because an is undefined and b is also undefined, the result is NaN. You can use default values to prevent similar errors, such as:
Function addTwoNumbers (a, b) {if (! a) a = 0; if (! b) b = 0; console.log (a + b);} addTwoNumbers (); / / 0
In addition, the default values can be used in ES6 as follows:
Function addTwoNumbers (a = 0, b = 0) {console.log (a + b);} addTwoNumbers (); / / 0
This example is small, but emphasizes the importance of default values.
In addition, if no expectation is provided, the developer can provide an error or warning message.
Variable naming error
Yes, developers will still make this mistake. Naming is difficult, but developers have no other choice. Annotations, like naming variables, are a good habit of programming.
For example:
Function total (discount, p) {return p * discount}
The variable discount is fine, but what about p or total? What is it, total? Preferably:
Function totalPrice (discount, price) {return discount * price}
It is important to name variables properly because other developers may use this code base at a particular time and in the future.
Naming variables properly makes it easy for contributors to understand how the project works.
Check Boolean value
Const isRaining = false if (isRaining) {console.log ('It is raining')} else {console.log ('It is not raining')} / / It is not raining
In the above example, it is a common way to check Boolean values, but there are still errors when testing some values.
In JavaScript, comparing 0 with false returns true, and comparing 1 with true returns true. That is to say, if isRaining is 1, then it is true.
This often causes errors in objects, such as:
Const obj = {name: 'JavaScript', number: 0} if (obj.number) {console.log (' number property exists')} else {console.log ('number property does not exist')} / / number property does not exist
Despite the existence of the number attribute, obj.number returns 0, which is a false value, so the else code is executed.
So, unless you determine the range of values to use, you should test Boolean values and properties in the object:
If (a = = false)... If (object.hasOwnProperty (property)). Confusing additions and connections
In JavaScript, the plus sign (+) has two functions: addition and concatenation. Addition is for numbers, while concatenation is for strings. Some developers often misuse this operator.
For example:
Const num1 = 30; const num2 = "20"; const num3 = 30; const word1 = "Java" const word2 = "Script" console.log (num1 + num2); / / 3020 console.log (num1 + num3); / / 60 console.log (word1 + word2); / / JavaScript
When you add a string to a number, JavaScript converts the number into a string. When the numbers are added, the mathematical operation is carried out.
Summary
In addition to the ones listed above, there must be more mistakes (minor or big ones). So, you need to know the latest language developments.
Learning and avoiding these mistakes will help you build better and more reliable Web applications and tools.
Is it helpful for you to read the above content? If you want to know more about the relevant knowledge or read more related articles, please follow the industry information channel, thank you for your support.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.