JavaScript | Top 10 Tips and Tricks - GeeksforGeeks

08 Sep, 2021
For web development or cross-platform development, JavaScript is gaining wide popularity. Once it was considered only as a front-end scripting language but it’s now getting popularity as the back-end too. Even Facebook’s React Native is based on JavaScript. Hence it would surely be beneficial to know some tricks in JavaScript which will not only prevent us from writing extra lines of code but will also make our code crisp and efficient.1. Faster array indexing: Consider an array [10, 9, 8, 7, 6], if we want to assign a value of this array to any variable, our go-to method would be const a = array[0]. If we would like to assign multiple variables, it would be tedious to keep on doing so. 
Code 1: Old school way.  
html
<script>    var array1 = [10, 9, 8, 7, 6];    var x = array1[0];    var y = array1[1];    var z = array1[2];    document.write("x = " + x + "<br>");    document.write("y = " + y + "<br>");    document.write("z = " + z + "<br>");</script>
Output:  
x = 10
y = 9
z = 8
Code 2: A smarter way.  
html
<script>    var array2 = [10, 9, 8, 7, 6];    var [x, y, z, ...rest] = array2;    document.write("x = " + x + "<br>");    document.write("y = " + y + "<br>");    document.write("z = " + z + "<br>");    document.write("rest = " + rest + "<br>");</script>
Output:  
x = 10
y = 9
z = 8
rest = 7, 6
2. Defining functions: The idea is to put some commonly or repeatedly task together and make a function so that instead of writing the same code again and again for different inputs, we can call that function. Everyone must have used functions like this in JavaScript. 
Code 1: Defining function in normal form.  
html
<!DOCTYPE html><html> <body>     <p>Usual function in JavaScript</p>     <p id="demo"></p>      <script>        function myFunction(p1, p2) {            return p1 * p2;        }        document.getElementById("demo").innerHTML                = myFunction(4, 3);    </script></body> </html>
Output:  
Usual function in JavaScript
12
Code 2: There is another way in which functions are treated as variables instead not a very useful trick but still something new. Holding function in a variable, it makes use of arrow functions like this. 
javascript
<!DOCTYPE html><html> <body>     <p>        Function treated as        variable in JavaScript:    </p>      <p id="demo"></p>      <script>        var myFunction = (p1, p2) => {            return p1 * p2;        }        document.getElementById("demo")            .innerHTML = myFunction(4, 3);    </script></body> </html>
Output:  
Function treated as variable in JavaScript
12
3. Defining functions in a single line: Now this trick is really cool. If you know Python, you probably know the lambda function which behaves as an arbitrary function and is written in a single line. Well, we don’t use lambda function in JavaScript, but we can still write one-liner functions. Say we would like to calculate the product of two numbers a and b, we can do it in a one-line script. We need not to specifically write the return statement as this way of defining already means that it will return the output on its own. 
Code:  
javascript
<!DOCTYPE html><html>  <body>     <p>        Function treated as        variable in JavaScript    </p>       <p id="demo"></p>       <script>        const productNum = (a, b) => a * b         document.getElementById("demo")            .innerHTML = myFunction(4, 3);    </script></body>  </html>
Output:  
Function treated as variable in JavaScript
12
4. Boolean: While every programming language, there are only two Boolean value True and False. JavaScript takes it a bit further by introducing a feature enabling the user to create bools. Unlike True and False, these are commonly referred as “Truthy” and “Falsy” respectively. To avoid confusion, all the values except 0, False, NaN, null, “” are defaulted as Truthy. This extended use of bools help us in checking a condition efficiently.  
Code:  
javascript
<script>    const a = !1;    const b = !!!0;     console.log(a);    console.log(b);</script>
Output:  
False
True
5. Filtering Boolean: Sometimes we may want to filter out all the bools, say the “Falsy” bools( 0, False, NaN, null, “”) from an array, this can be done by using map and filter functions in conjunction. Here, it uses the Boolean keyword to filter out Falsy values. 
Code:  
JavaScript
<script>arrayToFilter    .map(item => {        // Item values    })         .filter(Boolean);</script>
Input: [1, 2, 3, 0, "Hi", False, True]

Output: [1, 2, 3, "Hi", True]
6. Creating completely empty objects: If asked to create an empty object in JavaScript, our first go-to method will use in curly braces and assign it to a variable. But this is not a blank object as it still has object properties of JavaScript such as __proto__ and other methods. There is a way around this to create an object without any existent object properties. For this, we use a dictionary and assign it to a null value with its __proto__ being undefined. 
Code:  
javascript
<script>     /* Using .create() method to create       a completely empty object */     let dict = Object.create(null);     // dict.__proto__ === "undefined"</script>
7. Truncating an array: Although .splice() method is widely used to cut or remove specific portions of an array, but it has a worst-case time complexity of O(n). There exists a better alternative for removing elements from the end of an array. It uses the .length property of the array to do so.  
Code:  
javascript
<script>let arrayToTruncate = [10, 5, 7, 8, 3, 4, 6, 1, 0]; /* Specifying the length till where the   array should be truncated */arrayToTruncate.length = 6; console.log(arrayToTruncate)</script>
Output: As seen, we must know the length of the array to be truncated in this way otherwise it will result in an error. The run time here is of O(k) where k is the number of elements that will be left in the array.  
[10, 5, 7, 8, 3, 4]
8. Merging objects: The introduction of spread operator(...) allows user to easily merge to or more objects which was previously achieved by creating a separate function for doing the same. 
Code 1:  
javascript
<script>function mergeObjects(obj1, obj2) {    for (var key in obj2) {        if (obj2.hasOwnProperty(key)) obj1[key] = obj2[key];    }    return obj1;}</script>
Code 2: By using spread operator, the above task can be achieved easily and the code is also quite lucid.  
javascript
<script>    const obj1 = {}; // Items inside the object    const obj2 = {}; // Items inside the object     const obj3 = {...obj1, ...obj2};</script>
Input: 
obj1 = { site:'GeeksforGeeks', purpose:'Education'}
obj2 = { location:'Noida'}

Output:
obj3 = {site:'GeeksforGeeks', purpose:'Education', location:'Noida'}
9. Faster conditional checking: Checking and looping through conditions is an essential part of every programming language. In JavaScript, we do it as:  
Code 1:  
javascript
<script>if (condition) {    doSomething();}</script>
Code 2: However, the use of bit-wise operators make it easier to check conditions and also makes the code one line:  
javascript
<script>    condition && doSomething();</script>
10. Using regex to replace all characters: Very often, one comes to a situation where every occurrence of a character or a sub-string but unfortunately, .replace() method replaces only one instance of occurrence. We can get around this by using regex with .replace() method.  
Code:  
javascript
<script>    var string = "GeeksforGeeks"; // Some string     console.log(string.replace(/eek/, "ool"));</script>
Output:  
"GoolsforGools"
 
sagartomar9927
JavaScript-Misc
JavaScript
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
How to get character array from string in JavaScript?
Remove elements from a JavaScript Array
How to filter object array based on attributes?
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to insert spaces/tabs in text using HTML/CSS?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?