search
HomeWeb Front-endJS Tutorial45 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 ==.

Copy code The code is as follows:

[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
Copy code The code is as follows:

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
Copy the code The code is as follows:
function Person(firstName, lastName){
this.firstName = firstName;
this.lastName = lastName;
}

var Saad = new Person("Saad", "Mousliki");

6 – Use typeof, instanceof and constructor carefully
Copy the code The code is as follows:
var arr = ["a", "b", "c"];
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:
Copy code The code is 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
Copy the code The code is as follows:
var items = [12, 548 , 'a' , 2 , 5478 , 'foo' , 8852, , 'Doe' , 2145 , 119];

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
Copy code The code is as follows:
var numbersArray = [], max = 100 ;

for( var i=1; numbersArray.push(i )
11 – Generate a random alphanumeric string
Copy code The code is as follows:
function generateRandomAlphaNum(len) {
var rdmstring = "";
for( ; rdmString.length return rdmString.substr(0, len);
}

12 – scramble an array of numbers
Copy code The code is as follows:
var numbers = [5, 458, 120, -215, 228, 400, 122205, -85411];
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.
Copy code The code is as follows:

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
Copy the code The code is as follows:
var array1 = [12, " foo" , {name: "Joe"} , -2458];

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

Copy code The code is as follows:
var argArray = Array.prototype.slice.call(arguments);
arguments object is an array-like object, but not a real array

16 – Verify whether the argument is a number (number)
Copy code The code is as follows:
function isNumber(n){
return !isNaN(parseFloat(n)) && isFinite(n);
}

17 – Verify whether the parameter is an array
Copy code The code is as follows:
function isArray(obj){
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:
Copy the code The code is as follows:

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.
Copy code The code is as follows:
var myFrame = document.createElement('iframe');
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
Copy code The code is as follows :
var numbers = [5, 458, 120, -215, 228, 400, 122205, -85411];
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
Copy code The code is as follows:
var myArray = [12, 222, 1000];
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:

Copy the code The code is as follows:
var items = [12, 548 ,'a' , 2 , 5478 , 'foo' , 8852, , 'Doe' ,2154 , 119 ];
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:
Copy code The code is as follows:
var items = [12, 548 ,'a' , 2 , 5478 , 'foo' , 8852, , 'Doe' ,2154 , 119 ];
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.

Copy code The code is as follows:
var myArray = [12, 222, 1000, 124, 98, 10 ];
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.
Copy code The code is as follows:
myArray.length = 10; // the new array length is 10
myArray[myArray.length - 1] ; // undefined

22 – Use logical AND/OR to make conditional judgments
Copy code The code is as follows:

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
Copy code The code is as follows:

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
Copy code The code is as follows:
var squares = [1,2,3,4].map(function (val) {
return val * val;
});
// squares will be equal to [1, 4, 9, 16]

24 – Round a number to N decimal places
Copy code The code is as follows:
var num =2.443242342;
num = num.toFixed(4); / / num will be equal to 2.4432

25 – Floating point problem
Copy code The code is as follows:
0.1 0.2 === 0.3 // is false
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

Copy code The code is as follows:

for (var name in object) {
if (object.hasOwnProperty(name)) {
// do something with name
}
}

27 – Comma operator
Copy code The code is as follows:

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.

Copy code The code is as follows:
var navright = document.querySelector('#right');
var navleft = document.querySelector('#left');
var navup = document.querySelector('#up');
var navdown = document.querySelector('#down');

29 – Validate parameters before calling isFinite()
Copy code The code is as follows:
isFinite(0/0); // false
isFinite("foo"); // false
isFinite("10"); // true
isFinite(10); // true
isFinite(undifined); // false
isFinite(); // false
isFinite(null); // true !!!

30 – avoid in arrays Negative indexes
Copy code The code is as follows:
var numbersArray = [1, 2,3,4,5];
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

Copy code The code is as follows:
var person = {name :'Saad', age : 26, department : {ID : 15, name : "R&D"} };
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.
Copy code The code is as follows:
var func1 = new Function(functionCode);
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:
Copy code The code is as follows:
var sum = 0;
for (var i in arrayNumbers) {
sum = arrayNumbers[i];
}

A better way is:
Copy the code The code is as follows:
var sum = 0;
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:
Copy the code The code is as follows:
for (var i = 0; i
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:
Copy code The code is as follows:

setInterval('doSomethingPeriodically() ', 1000);
setTimeOut('doSomethingAfterFiveSeconds()', 5000)

And use:
Copy code The code is as follows:

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:
Copy code The code is as follows:

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
The code is as follows:function clone(object) { function OneShotConstructor(){ }; OneShotConstructor.prototype= object; return new OneShotConstructor();
}
clone(Array).prototype; // []


39 – one HTML escape function


Copy code
The code is as follows:function escapeHTML(text) { var replacements= {"": ">","&": "&", """: """}; return text.replace( /[&"]/g, function(character) {              return replacements[character]; Internally using try-catch-finally
at runtime, each time the catch clause is executed, the caught exception object will be assigned to a variable, and in the try-catch-finally structure, each time This variable will be created
.
Avoid writing like this:



Copy code
The code is as follows:

var object = ['foo' , 'bar'], i;
for (i = 0, len = object.length; i try { // do something that throws an exception } catch (e) { // handle exception }}

and use:




Copy code


The code is as follows:

var object = ['foo', 'bar'], i;
try {
for (i = 0, len = object .length; i // do something that throws an exception }}catch (e) { // handle exception}

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 () {
if (this.readyState == 4) { clearTimeout(timeout); // do something with response data }}var timeout = setTimeout ( function () { xhr.abort(); // call error callback
}, 60*1000 /* timeout after a minute */ );
xhr.open('GET', url, true);

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:

Copy code The code is as follows:
var timerID = 0;
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:
Copy the codeThe code is as follows:
var min = Math.min(a,b);
A.push(v);

and use:
Copy code The code is as follows:
var min = a A[A.length] = v;

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.

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

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.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

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 the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

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 vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

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 vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

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.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

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.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

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.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

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.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

MantisBT

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

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools