45 Practical Tips JavaScript Programmers Should Know_javascript tips
As you know, JavaScript is the number one programming language in the world. It is the language of the Web, the language of mobile hybrid apps (such as PhoneGap or Appcelerator), and the server-side language (such as NodeJS or Wakanda), and has many other implementations. At the same time, it is also the enlightenment language for many novices, because it can not only display a simple alert message on the browser, but also can be used to control a robot (using nodebot, or nodruino). Developers who master JavaScript and can write organized, standardized and performantly efficient code have become sought after in the talent market.
It should be noted that the code snippets in this article were tested on the latest Google Chrome (version number 30), which uses the V8 JavaScript engine (V8 3.20.17.15).
1 – Don’t forget to use the var keyword when assigning a value to a variable for the first time
Assigning a value to an undefined variable will result in the creation of a global variable. Avoid global variables.
2 – Use === instead of ==
== (or !=) operator will automatically perform type conversion when needed. The === (or !==) operation does not perform any conversion. It compares values and types, and is also considered faster than ==.
[10] === 10 // is false
[10] == 10 // is true
'10' == 10 // is true
'10' === 10 // is false
[] == 0 // is true
[] === 0 // is false
'' == false // is true but true == "a" is false
'' === false // is false
3 – Use closures to implement private variables
function Person(name, age) {
this.getName = function() { return name; };
this.setName = function(newName) { name = newName; } ;
this.getAge = function() { return age; };
this.setAge = function(newAge) { age = newAge; };
//Not initialized in the constructor Attributes
var occupation;
this.getOccupation = function() { return occupation; };
this.setOccupation = function(newOcc) { occupation =
newOcc; };
}
4 – Use semicolons at the end of statements
Using semicolons at the end of statements is a good practice. You won't be warned if you forget to write it, because in most cases the JavaScript interpreter will add the semicolon for you.
5 – Create the constructor of the object
this.firstName = firstName;
this.lastName = lastName;
}
var Saad = new Person("Saad", "Mousliki");
6 – Use typeof, instanceof and constructor carefully
typeof arr; // return "object"
arr instanceof Array // true
arr.constructor(); / /[]
7 – Create a Self-calling Function
This is often called a Self-Invoked Anonymous Function or immediate call Function expression (IIFE-Immediately Invoked Function Expression). This is a function that is automatically executed immediately after creation, usually as follows:
(function(){
// some private code that will be executed automatically
})();
(function(a,b){
var result = a b;
return result;
})(10,20)
8- Get a random item from the array
var randomItem = items[Math.floor( Math.random() * items.length)];[code]
9 – Get a random number in a specific range
This code snippet is very useful when you want to generate test data Useful, such as a random salary value between the minimum and maximum values.
[code]var x = Math.floor(Math.random() * (max - min 1)) min;
10 – generated between 0 and the set maximum value An array of numbers
for( var i=1; numbersArray.push(i )
11 – Generate a random alphanumeric string
var rdmstring = "";
for( ; rdmString.length return rdmString.substr(0, len);
}
12 – scramble an array of numbers
numbers = numbers.sort( function(){ return Math.random() - 0.5});
/* the array numbers will be equal for example to [120, 5, 228, -215, 400, 458, -85411, 122205] */
13 – String’s trim function
There is a classic trim function in Java, C#, PHP and many other languages, which is used to remove spaces in strings. There is no such function in JavaScript, so we need to add this function to the String object.
String.prototype.trim = function(){return this .replace(/^s |s $/g, "");};//Remove the leading and trailing spaces of the string, excluding the internal spaces of the string
14 – Append an array Go to another array
var array2 = ["Doe" , 555 , 100];
Array.prototype.push.apply(array1, array2);
/* array1 will be equal to [12, "foo", {name "Joe"}, -2458, "Doe", 555, 100] */
//In fact, concat can directly implement two arrays connection, but its return value is a new array. Here is the direct change to array1
15 – Convert the arguments object into an array
arguments object is an array-like object, but not a real array
16 – Verify whether the argument is a number (number)
return !isNaN(parseFloat(n)) && isFinite(n);
}
17 – Verify whether the parameter is an array
return Object.prototype.toString.call(obj) === '[object Array ]' ;
}
Note: If the toString() method is overridden, you will not be able to get the desired results using this technique. Or you can use:
Array.isArray(obj); // This is a new array method
If you are not using multiple frames, you can also use the instanceof method. But if you have multiple contexts, you'll get wrong results.
document.body.appendChild(myFrame);
var myArray = window.frames[window.frames.length-1].Array;
var arr = new myArray(a,b,10); / / [a,b,10]
// instanceof will not work correctly, myArray loses his constructor
// constructor is not shared between frames
arr instanceof Array; // false
18 – Get the maximum or minimum value in an array of numbers
var maxInNumbers = Math.max.apply(Math, numbers);
var minInNumbers = Math.min.apply(Math, numbers);
//Translator’s Note: The technique of passing parameters using the Function.prototype.apply method is used here
19 – Clear an array
myArray.length = 0; // myArray will be equal to [].
20 – Do not use delete to remove items from an array.
Use splice instead of delete to delete an item from an array. Using delete only replaces the original item with undefined, but does not actually delete it from the array.
Don’t use this method:
items.length; // return 11
delete items[3]; // return true
items.length; // return 11
/* items will be equal to [12, 548, "a", undefined × 1, 5478, "foo", 8852, undefined × 1, "Doe", 2154, 119] */
and use:
items.length; // return 11
items.splice( 3,1) ;
items.length; // return 10
/* items will be equal to [12, 548, "a", 5478, "foo", 8852, undefined × 1, "Doe" , 2154, 119] */
delete method should be used to delete an attribute of an object.
21 – Use length to truncate an array
Similar to the way to clear the array above, we use the length property to truncate an array.
myArray.length = 4; // myArray will be equal to [12, 222, 1000, 124].
Also, if you set the length of an array to a larger one than it is now value, then the length of the array will be changed, and new undefined items will be added. The length of an array is not a read-only property.
myArray[myArray.length - 1] ; // undefined
22 – Use logical AND/OR to make conditional judgments
var foo = 10;
foo == 10 && doSomething(); // Equivalent to if (foo == 10) doSomething();
foo == 5 || doSomething( ); // Equivalent to if (foo != 5) doSomething();
Logical AND can also be used to set default values for function parameters
function doSomething(arg1){
Arg1 = arg1 || 10; // If arg1 is not set, Arg1 will be set to 10 by default
}
23 – Use the map() method to iterate over the items in an array
return val * val;
});
// squares will be equal to [1, 4, 9, 16]
24 – Round a number to N decimal places
num = num.toFixed(4); / / num will be equal to 2.4432
25 – Floating point problem
9007199254740992 1 // is equal to 9007199254740992
9007199254740992 2 // is equal to 9007199254740994
Why is this happening? ? 0.1 0.2 is equal to 0.30000000000000004. You need to know that all JavaScript numbers are internally represented as floating point numbers in 64-bit binary, complying with the IEEE 754 standard. For more introduction, you can read this blog post. You can solve this problem using toFixed() and toPrecision() methods.
26 – When using for-in to traverse the internal properties of an object, pay attention to checking the properties
The following code snippet can avoid accessing prototype properties when traversing an object's properties
for (var name in object) {
if (object.hasOwnProperty(name)) {
// do something with name
}
}
27 – Comma operator
var a = 0;
var b = ( a , 99 );
console.log(a); // a will be equal to 1
console.log(b); // b is equal to 99
28 – Cache variables that require calculation or querying
For jQuery selectors, we better cache these DOM elements.
var navleft = document.querySelector('#left');
var navup = document.querySelector('#up');
var navdown = document.querySelector('#down');
29 – Validate parameters before calling isFinite()
isFinite("foo"); // false
isFinite("10"); // true
isFinite(10); // true
isFinite(undifined); // false
isFinite(); // false
isFinite(null); // true !!!
30 – avoid in arrays Negative indexes
var from = numbersArray.indexOf("foo") ; // from is equal to -1
numbersArray.splice(from,2); // will return [5 ]
Make sure the argument when calling indexOf is not negative.
31 – JSON-based serialization and deserialization
var stringFromPerson = JSON.stringify(person );
/* stringFromPerson is equal to "{"name":"Saad","age":26,"department":{"ID":15,"name":"R&D"}}" */
var personFromString = JSON.parse(stringFromPerson);
/* personFromString is equal to person object */
32 – Avoid using eval() and Function constructor
Using eval and Function constructors are very expensive operations because each time they call the script engine to convert the source code into executable code.
var func2 = eval(functionCode);
33 – Avoid using with()
Using with() will insert a global variable. Therefore, variables with the same name will have their values overwritten and cause unnecessary trouble.
34 – Avoid using for-in to iterate over an array
Avoid using this:
for (var i in arrayNumbers) {
sum = arrayNumbers[i];
}
A better way is:
for (var i = 0, len = arrayNumbers.length; i sum = arrayNumbers[i];
}
The additional benefit is that i and len are both The value of the variable is only executed once, which is more efficient than the following method:
Why? Because arrayNumbers.length will be calculated every time it loops.
35 – Pass functions instead of strings when calling setTimeout() and setInterval().
If you pass a string to setTimeout() or setInterval(), the string will be parsed as if using eval, which is very time-consuming.
Don’t use:
setInterval('doSomethingPeriodically() ', 1000);
setTimeOut('doSomethingAfterFiveSeconds()', 5000)
And use:
setInterval(doSomethingPeriodically, 1000);
setTimeOut(doSomethingAfterFiveSeconds, 5000);
36 – Use switch/case statement, and Instead of a long list of if/else
, when judging more than 2 situations, using switch/case is more efficient and more elegant (easier to organize code). But don’t use switch/case when there are more than 10 situations to be judged.
37 – Use switch/case when judging the numerical range
In the following situation, it is reasonable to use switch/case to judge the numerical range:
function getCategory(age) {
var category = "";
switch (true) {
case isNaN(age):
category = "not an age";
break; category = "Baby" ;
break;
default:
category = "Young";
break;
};
return category;
}
getCategory(5) ; // will return "Baby"
//Generally, for judging the numerical range, it is more appropriate to use if/else. switch/case is more suitable for judging certain values
38 – Specify the prototype object for the created object
It is possible to write a function to create an object with specified parameters as prototype :
Copy code
39 – one HTML escape function
Copy code
.
Avoid writing like this:
Copy code
The code is as follows:
var object = ['foo' , 'bar'], i;
for (i = 0, len = object.length; i
Copy code
The code is as follows:
var object = ['foo', 'bar'], i;
try {
41 – Set timeout for XMLHttpRequests.
After an XHR request takes a long time (for example, due to network problems), you may need to abort the request, then you can use setTimeout() with the XHR call.
Copy code
The code is as follows:
var xhr = new XMLHttpRequest ();
xhr.onreadystatechange = function () {
xhr.send();
Also, generally you should avoid synchronous Ajax requests entirely.
42 - Handling WebSocket timeouts
Normally, after a WebSocket connection is created, the server will time out your connection after 30 seconds if you have no activity. Firewalls also disconnect after a period of inactivity.
To prevent timeout issues, you may need to intermittently send empty messages to the server. To do this, you can add the following two functions to your code: one to maintain the connection and one to cancel the connection hold. With this technique, you can control the timeout issue.
Use a timerID:
function keepAlive() {
var timeout = 15000;
if (webSocket.readyState == webSocket.OPEN) {
webSocket.send('');
}
timerId = setTimeout( keepAlive, timeout);
}
function cancelKeepAlive() {
if (timerId) {
cancelTimeout(timerId);
}
}
keepAlive() The method should be added at the end of the onOpen() method of the webSOcket connection, and cancelKeepAlive() is added at the end of the onClose() method.
43 – Keep in mind that primitive operators are always more efficient than function calls. Use vanillaJS.
For example, do not use:
A.push(v);
and use:
44 – when encoding Don’t forget to use code tidying tools . Use JSLint and code compression tools (minification) (such as JSMin) before going online. "Time Saving Tool: Code Beautification and Formatting Tool"
45 – JavaScript is incredible.
Summary
I know there are many other tips, tricks, and best practices out there, so if you have anything else you’d like to add or have feedback or corrections to the ones I’ve shared, please say so in the comments.

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

SublimeText3 Linux new version
SublimeText3 Linux latest version

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

Dreamweaver CS6
Visual web development tools