天天看點

45 Useful JavaScript Tips, Tricks and Best Practices

45 Useful JavaScript Tips, Tricks and Best Practices

the developers who master javascript and write organized and performant code have become the most sought after in the job market.

in this article, i’ll share a set of javascript tips, tricks and best practices that should be known by all javascript developers regardless of their browser/engine or the ssjs (server side javascript) interpreter.

note that the code snippets in this article have been tested in the latest google chrome version 30, which uses the v8 javascript engine (v8 3.20.17.15).

1 – don’t forget <code>var</code> keyword when assigning a

variable’s value for the first time.

assignment to an undeclared variable automatically results in a global variable being created. avoid global variables.

2 – use <code>===</code> instead of <code>==</code>

the <code>==</code> (or <code>!=</code>)

operator performs an automatic type conversion if needed. the <code>===</code> (or<code>!==</code>)

operator will not perform any conversion. it compares the value and the type, which could be considered faster than <code>==</code>.

3 – <code>undefined</code>, <code>null</code>,

0, <code>false</code>, <code>nan</code>, <code>''</code> (empty

string) are all falsy.

4 – use semicolons for line termination

the use of semi-colons for line termination is a good practice. you won’t be warned if you forget it, because in most cases it will be inserted by the javascript parser.

5 – create an object constructor

6 – be careful when using <code>typeof</code>, <code>instanceof</code> and <code>constructor</code>.

7 – create a self-calling function

this is often called a self-invoked anonymous function or immediately invoked function expression (iife). it is a function that executes automatically when you create it, and has the following form:

8 – get a random item from an array

9 – get a random number in a specific range

this code snippet can be useful when trying to generate fake data for testing purposes, such as a salary between min and max.

10 – generate an array of numbers with numbers from 0 to max

11 – generate a random set of alphanumeric characters

12 – shuffle an array of numbers

13 – a string trim function

the classic trim function of java, c#, php and many other language that remove whitespace from a string doesn’t exist in javascript, so we could add it to the <code>string</code>object.

14 – append an array to another array

15 – transform the <code>arguments</code> object into an array

16 – verify that a given argument is a number

17 – verify that a given argument is an array

note that if the tostring() method is overridden, you will not get the expected result using this trick.

or use…

you could also use <code>instanceof</code> if you are not working

with multiple frames. however, if you have many contexts, you will get a wrong result.

18 – get the max or the min in an array of numbers

19 – empty an array

20 – don’t use delete to remove an item from array

use <code>split</code> instead of using <code>delete</code> to

delete an item from an array. using <code>delete</code>replaces the

item with <code>undefined</code> instead of the removing it from

the array.

instead of… &gt;

use…

the delete method should be used to delete an object property.

21 – truncate an array using length

like the previous example of emptying an array, we truncate it using the <code>length</code> property.

as a bonus, if you set the array length to a higher value, the length will be changed and new items will be added with <code>undefined</code> as

a value. the array length is not a read only property.

22 – use logical and/ or for conditions

the logical and could also be used to set a default value for function argument.

23 – use the map() function method to loop through an array’s items

24 – rounding number to n decimal place

25 – floating point problems

you can use <code>tofixed()</code> and <code>toprecision()</code> to

resolve this problem.

26 – check the properties of an object when using a for-in loop

this code snippet could be useful in order to avoid iterating through the properties from the object’s prototype.

27 – comma operator

28 – cache variables that need calculation or querying

in the case of a jquery selector, we could cache the dom element.

29 – verify the argument before passing it to <code>isfinite()</code>

30 – avoid negative indexes in arrays

make sure that the arguments passed to <code>indexof</code> are not

negative.

31 – serialization and deserialization (working with json)

32 – avoid the use of <code>eval()</code> or the <code>function</code> constructor

use of <code>eval</code> or the <code>function</code> constructor

are expensive operations as each time they are called script engine must convert source code to executable code.

33 – avoid using <code>with()</code> (the good part)

using <code>with()</code> inserts a variable at the global scope.

thus, if another variable has the same name it could cause confusion and overwrite the value.

34 – avoid using for-in loop for arrays

instead of using…

…it’s better to use…

as a bonus, the instantiation of <code>i</code> and <code>len</code> is

executed once because it’s in the first statement of the for loop. thsi is faster than using…

why? the length of the array <code>arraynumbers</code> is recalculated

every time the loop iterates.

35 – pass functions, not strings, to <code>settimeout()</code> and <code>setinterval()</code>

if you pass a string into <code>settimeout()</code> or <code>setinterval()</code>,

the string will be evaluated the same way as with <code>eval</code>,

which is slow. instead of using…

…use…

36 – use a switch/case statement instead of a series of if/else

using switch/case is faster when there are more than 2 cases, and it is more elegant (better organized code). avoid using it when you have more than 10 cases.

37 – use switch/case statement with numeric ranges

using a switch/case statement with numeric ranges is possible with this trick.

38 – create an object whose prototype is a given object

it’s possible to write a function that creates an object whose prototype is the given argument like this…

39 – an html escaper function

40 – avoid using try-catch-finally inside a loop

the try-catch-finally construct creates a new variable in the current scope at runtime each time the catch clause is executed where the caught exception object is assigned to a variable.

41 – set timeouts to <code>xmlhttprequests</code>

you could abort the connection if an xhr takes a long time (for example, due to a network issue), by using <code>settimeout()</code> with

the xhr call.

as a bonus, you should generally avoid synchronous ajax calls completely.

42 – deal with websocket timeout

generally when a websocket connection is established, a server could time out your connection after 30 seconds of inactivity. the firewall could also time out the connection after a period of inactivity.

to deal with the timeout issue you could send an empty message to the server periodically. to do this, add these two functions to your code: one to keep alive the connection and the other one to cancel the keep alive. using this trick, you’ll control the timeout.

add a <code>timerid</code>…

the <code>keepalive()</code> function should be added at the end of

the <code>onopen()</code> method of the websocket connection and

the <code>cancelkeepalive()</code> at the end of the <code>onclose()</code> method.

for example, instead of using…

44 – don’t forget to use a code beautifier when coding. use jslint and minification (jsmin, for example) before going live.

i know that there are many other tips, tricks and best practices, so if you have any ones to add or if you have any feedback or corrections to the ones that i have shared, please adda comment.

in this article i have used my own code snippets. some of the snippets are inspired from other articles and forums:

<a target="_blank" href="https://code.google.com/p/jslibs/wiki/javascripttips">google code javascript tips</a>

<a target="_blank" href="http://stackoverflow.com/questions/724826/javascript-tips-and-tricks-javascript-best-practices">stackoverflow tips and tricks</a>

<a target="_blank" href="http://stackoverflow.com/questions/6888409/settimeout-for-xhr-requests">timeout for xhr</a>

<a target="_blank" href="http://stackoverflow.com/questions/11246/best-resources-to-learn-javascript">http://stackoverflow.com/questions/11246/best-resources-to-learn-javascript</a>