JavaScript | Top 10 Tips and Tricks
Last Updated :
25 Apr, 2025
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.
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>
x = 10
y = 9
z = 8
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>
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>
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>
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.
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>
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.
javascript
<script>
const a = !1;
const b = !!!0;
console.log(a);
console.log(b);
</script>
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.
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.
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.
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.
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:
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.
javascript
<script>
var string = "GeeksforGeeks"; // Some string
console.log(string.replace(/eek/, "ool"));
</script>
"GoolsforGools"
Similar Reads
Top 10 JavaScript Projects for Resume
In the world of programming, a well-crafted resume is not just about listing your skills and experiences. It is about showcasing your practical abilities through physical projects. For JavaScript builders, building correct tasks isn't always best demonstrates talent but additionally highlights creat
9 min read
Top 95+ Javascript Projects For 2025
JavaScript is a lightweight, cross-platform programming language that powers dynamic and interactive web content. From real-time updates to interactive maps and animations, JavaScript brings web pages to life.Here, we provided 95+ JavaScript projects with source code and ideas to provide hands-on ex
4 min read
JavaScript Strings Coding Practice Problems
Strings are one of the most essential data types in JavaScript, used for handling and manipulating text-based data. This curated list of JavaScript string practice problems covers everything master JavaScript Strings. Whether you're a beginner or an experienced developer, these problems will enhance
1 min read
JavaScript Stack Coding Practice Problems
Stacks are a fundamental data structure used for managing data in a Last In, First Out (LIFO) manner. This curated list of JavaScript Stack Coding Practice Problems will help you master stack operations. Whether you're a beginner or an experienced developer, these problems will enhance your stack ma
1 min read
JavaScript Map Coding Practice Problems
Maps are an essential data structure used for storing key-value pairs. They provide efficient lookups, insertions, and deletions, and are widely used for implementing dictionaries, caches, and many other applications. This curated list of JavaScript Map Coding Practice Problems will help you master
2 min read
JavaScript Coding Questions and Answers
JavaScript is the most commonly used interpreted, and scripted Programming language. It is used to make web pages, mobile applications, web servers, and other platforms. Developed in 1995 by Brendan Eich. Developers should have a solid command over this because many job roles need proficiency in Jav
15+ min read
8 Best Tips to Improve Your JavaScript Skills
JavaScript is also known as the Language of Browsers, as it is the most commonly used language for creating interactive web pages. This scripting language is undoubtedly the most important web technology alongside HTML and CSS. With JavaScript, you can create, implement, display, and animate various
6 min read
JavaScript Hashing Coding Practice Problems
Hashing is a fundamental concept in JavaScript used to map data to a fixed-size value, enabling fast lookups, efficient data retrieval, and optimized storage. Hashing is commonly used in hash tables, caching, data indexing, and cryptography to store and retrieve values efficiently.This curated list
2 min read
JavaScript Heap Coding Practice Problems
Heaps are an essential data structure in JavaScript used for efficiently managing priority-based tasks. A Heap is a specialized tree-based structure that allows for quick retrieval of the smallest or largest element, making it useful for priority queues, scheduling algorithms, and graph algorithms l
2 min read
JavaScript Operators Coding Practice Problems
Operators in JavaScript allow you to perform operations on variables and values, including arithmetic, logical, bitwise, comparison, and assignment operations. Mastering JavaScript operators is essential for writing efficient expressions and conditional statements. This curated list of JavaScript op
1 min read