Useful JavaScript Tips, Tricks and Best Practices
1 – Don’t forget var
keyword when assigning a variable’s value for the first time.
var
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 ===
instead of ==
===
instead of ==
The ==
(or !=
) operator performs an automatic type conversion if needed. The ===
(or !==
) operator will not perform any conversion. It compares the value and the type, which could be considered faster than ==
.
3 – undefined
, null
, 0, false
, NaN
, ''
(empty string) are all falsy.
undefined
, null
, 0, false
, NaN
, ''
(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. For more details about why you should use semi-colons, take a look to this artice: http://davidwalsh.name/javascript-semicolons.
5 – Create an object constructor
6 – Be careful when using typeof
, instanceof
and constructor
.
typeof
, instanceof
and constructor
.typeof : a JavaScript unary operator used to return a string that represents the primitive type of a variable, don’t forget that
typeof null
will return “object”, and for the majority of object types (Array, Date, and others) will return also “object”.constructor : is a property of the internal prototype property, which could be overridden by code.
instanceof : is another JavaScript operator that check in all the prototypes chain the constructor it returns true if it’s found and false if not.
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
A better option could be to implement a random sort order by code (e.g. : Fisher-Yates shuffle), than using the native sort JavaScript function. For more details take a look to this discussion.
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 String
object.
A native implementation of the trim() function is available in the recent JavaScript engines.
14 – Append an array to another array
15 – Transform the arguments
object into an array
arguments
object into an array16 – 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 instanceof
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 splice
instead of using delete
to delete an item from an array. Using delete
replaces the item with undefined
instead of the removing it from the array.
Instead of…
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 length
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 undefined
as a value. The array length is not a read only property.
22 – Use logical AND/ OR for conditions
The logical OR 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
NOTE : the toFixed()
function returns a string and not a number.
25 – Floating point problems
Why does this happen? 0.1 +0.2 is equal to 0.30000000000000004. What you need to know is that all JavaScript numbers are floating points represented internally in 64 bit binary according to the IEEE 754 standard. For more explanation, take a look to this blog post.
You can use toFixed()
and toPrecision()
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 isFinite()
isFinite()
30 – Avoid negative indexes in arrays
Make sure that the arguments passed to splice
are not negative.
31 – Serialization and deserialization (working with JSON)
32 – Avoid the use of eval()
or the Function
constructor
eval()
or the Function
constructorUse of eval
or the Function
constructor are expensive operations as each time they are called script engine must convert source code to executable code.
33 – Avoid using with()
(The good part)
with()
(The good part)Using with()
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 i
and len
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 arrayNumbers
is recalculated every time the loop iterates.
NOTE : the issue of recalculating the length in each iteration was fixed in the latest JavaScript engines.
35 – Pass functions, not strings, to setTimeout()
and setInterval()
setTimeout()
and setInterval()
If you pass a string into setTimeout()
or setInterval()
, the string will be evaluated the same way as with eval
, 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.
Instead of using…
…use…
41 – Set timeouts to XMLHttpRequests
XMLHttpRequests
You could abort the connection if an XHR takes a long time (for example, due to a network issue), by using setTimeout()
with the XHR call.
As a bonus, you should generally avoid synchronous XHR 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 timerID
…
The keepAlive()
function should be added at the end of the onOpen()
method of the webSocket connection and the cancelKeepAlive()
at the end of the onClose()
method.
43 – Keep in mind that primitive operations can be faster than function calls. Use VanillaJS.
For example, instead of using…
…use…
44 – Don’t forget to use a code beautifier when coding. Use JSLint and minification (JSMin, for example) before going live.
45. Replace All
We know that the string.replace() function replaces only the first occurrence. You can replace all the occurrences by adding /g at the end of the regex.
46. Extract Unique Values
We can create a new array only with the unique values by using the Set object and the Spread operator.
47. Convert number to string
We just have to use the concatenation operator with an empty set of quotation marks.
48. Convert string to number
All we need is the + operator.
Be careful with this one since it only works with 'string numbers'.
49. Shuffle elements from array
Every day I'm shufflin'
50. Flatten multidimensional array
Simply by using the Spread operator.
51. Short Circuit Conditionals
Let's take this example:
And shorten it by simply using the variable together with the function:
52. Dynamic Property Names
I always thought that I first had to declare an object before being able to assign a dynamic property.
53. Use length to resize/empty an array
We basically overwrite the length of the array.
If we want to resize the array:
If we want to empty the array:
Last updated