Super Useful Tips & Tricks for JavaScript Developers

Full Stack Developer | Freelancer | JavaScript | React | Nodejs.
Loves sharing knowledge through technical articles.
Dev.to: https://dev.to/myogeshchavan97
https://linktr.ee/myogeshchavan97
Search for a command to run...

Full Stack Developer | Freelancer | JavaScript | React | Nodejs.
Loves sharing knowledge through technical articles.
Dev.to: https://dev.to/myogeshchavan97
https://linktr.ee/myogeshchavan97
Hey Yogesh Chavan
Good tips thanks. By the way, I can add my two cents to your article.
arr.slice(-1) will return [50] not the value 50. const isArray = Object.prototype.toString.call(arr) == "[object Array]"
Chety Thanks for pointing out my mistake. I have updated the article.
And thanks for mentioning another way for Array type check.
Yogesh Chavan Thanks for sharing helpful about js.
This article is so useful, cause I recently had an array with something like arr = [ {name: foo, count:2}, {name2: doe, count:5} ] and I wanted to convert all count values to percentage while maintaining names as they're and get results into a new array, I think the add function and dynamic object trick you have provided here can make it work, I just haven't figured it out. But in all this is awesome, thanks!
Thanks Hussein Kizz. Glad this article was useful to you. But I think I have not understood what you're trying to do. Are you trying to add all count values to calculate the percentage?
oh yeah Yogesh Chavan thanks, I was trying to do that but I shouted out on the tech twitter community and got help. it's using Array reduce and map and get it to work, here is the tweet: https://twitter.com/HusseinKizz/status/1396586056267407362
Hussein Kizz It's great to hear that you've finally solved the issue
In this tutorial, you will build a Task Management App using Next.js 16 and Prisma 7 from scratch. By creating this app, you will learn: How to set up Prisma 7 with the new Rust-free architecture How to configure a database with Prisma's driver ada...

If you're a React/Next.js developer who diligently updated your packages last week after the critical React2Shell vulnerability (CVE-2025-55182), I have some frustrating news: you need to update again. Security researchers, while probing the patches ...

Is your React app dragging its feet, but you can’t pinpoint the cause? You might think you’re following the best practices, but some common development patterns are actually degrading your app’s performance behind the scenes. In this article, we’ll u...

How to Use Separate SSH Keys for Company and Personal GitHub Accounts Managing multiple GitHub accounts is a common challenge for developers who juggle both personal and professional projects. It becomes even more complex when you want to use differe...

Have you ever built a React app only to realize that users from different countries can't use it effectively because it only supports English? In this tutorial, you'll learn how to build truly global React application using internationalization (i18n...

const creditCard = "4111111111114321"; // 16 digit credit card number
const lastFourDigits = creditCard.slice(-4); // get last 4 digits
// prepend * to lastFourDigits to make length equal to creditCard number length
const maskedNumber = lastFourDigits.padStart(creditCard.length, '*');
console.log(lastFourDigits); // 4321
console.log(maskedNumber); // ************4321
By passing { once: true } as the third argument to the addEventListener method, the event handler function will be executed only once.
document.getElementById("btn").addEventListener("click",
function () {
console.log("Button clicked!");
},
{ once: true }
);
const user = {
name: 'David',
age: 30,
city: 'NY'
};
const newAge = 40;
const updatedUser = {
...user,
age: newAge
};
console.log(user); // { name: 'David', age: 30, city: 'NY'}
console.log(updatedUser); // { name: 'David', age: 40, city: 'NY'}
const user = {
name: 'David',
age: 30,
city: 'NY'
};
console.log(Object.keys(user).length); // 3
const numbers = [10, 20, 30, 40, 50];
const last = numbers.slice(-1);
console.log(last); // [50]
const secondLast = numbers.slice(-2);
console.log(secondLast); // [40, 50]
Note that, slice method is available for the array as well as string.
In JavaScript, array is also an object so to check If it's actually an array or object you can use the following 3 ways. (Popular Interview Question)
const arr = [1, 2, 3, 4];
arr.constructor.toString().indexOf("Array") > -1
arr instanceof Array
Array.isArray(arr)
const date = new Date();
console.log(date.getTime()); // 1621708197268
The timestamp value is sometimes useful for generating unique values because the timestamp value is always different for every second.
// old way
function getPairs(key, value) {
var object = {};
object[key] = value
return object;
}
console.log(getPairs('name', 'Mike')); // { name: 'Mike'}
console.log(getPairs('age', '40')); // { age: 40}
// new ES6 way
function getPairs(key, value) {
const object = {
[key]: value
};
return object;
}
console.log(getPairs('name', 'Mike')); // { name: 'Mike'}
console.log(getPairs('age', '40')); // { age: 40}
const user = {
name: 'David',
age: 30
};
// destructure user properties and use a `status` property with value `Married` If it does not exist
const {name, age, status = 'Married' } = user;
console.log(name, age, status) // David 30 Married
const person = {
age: 30
};
// destructure `person` object and rename `name` to `username` and assign a default value of `Anonymous`, If the property does not exist in the `person` object
const {name: username = 'Anonymous', age } = person;
console.log(username, age); // Anonymous 30
const days = ["sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "saturday"];
const [firstDay, secondDay] = days;
console.log(firstDay); // sunday
console.log(secondDay); // monday
const user = {
name: 'David',
age: 30,
address: 'NY'
};
// old way: Hi, I'm David with age 30 and living in NY
console.log("Hi, I'm " + user.name + " with age " + user.age + " and living in " + user.address);
// new way: Hi, I'm David with age 30 and living in NY
console.log(`Hi, I'm ${user.name} with age ${user.age} and living in ${user.address}`);
This can be further simplified as shown below:
const user = {
name: 'David',
age: 30,
address: 'NY'
};
const { name, age, address } = user;
console.log(`Hi, I'm ${name} with age ${age} and living in ${address}`);
ES6 rest operator (...) converts comma-separated values into an array so the numbers parameter of the add function becomes an array.
function add(...numbers) {
return numbers.reduce((acc, value) => {
return acc + value;
}, 0);
}
const sum = add(1, 2, 3, 4, 5);
console.log(sum); // 15
const first = ["two", "three", "four"];
const second = [ "six", "seven", "eight"];
const combined = ["one", ...first, "five", ...second]
console.log(combined); // ["one", "two", "three", "four", "five", "six", "seven", "eight"]
const array = Array(5).fill(false); // [false, false, false, false, false]
const array = [...Array(5).keys()] // [0, 1, 2, 3, 4, 5]
const array = [1, 2, 2, 3, 1, 5];
const unique = [...new Set(array)];
console.log(unique); // [1, 2, 3, 5];
const array = [1, 2, 2, 3, 1, 5];
const unique = array.filter((value, index) => {
return array.indexOf(value) === index;
});
console.log(unique); // [1, 2, 3, 5]
Math.floor(Math.random() * 100)
Math.floor(Math.random() * 100) + 1
function getRandom(min, max) {
return Math.floor(Math.random() * (max - min) ) + min;
}
console.log(getRandom(10, 35)); // any random number >= 10 and < 35
function getRandom(min, max) {
return Math.floor(Math.random() * (max - min + 1) ) + min;
}
console.log(getRandom(10, 35)); // any random number >= 10 and <= 35
const book = {"date": "2019–03–22","book": "Harry potter","author": "J.K.Rowling"};
console.log(JSON.stringify(book, null, 2)) // formatted with 2 spaces

const book = {"date": "2019–03–22","book": "Harry potter","author": "J.K.Rowling"};
console.log(JSON.stringify(book, null, '\t')) // formatted with tabs

window.scrollTo({ top: 0, left: 0, behavior: "smooth" });
let number1;
console.log(!!number1); // false
const number2 = 10;
console.log(!!number2); // true
const name1 = 'Tim';
console.log(!!name1); // true
const name2 = '';
console.log(!!name2); // false
const nullValue = null;
console.log(!!nullValue); // false
This is especially useful If you want to avoid sending null or undefined as a value to the backend.
const number = "20";
const converted = +number;
console.log(converted); // 20
const name = "Mike johnson";
console.log(name.split("")); // ["M", "i", "k", "e", " ", "j", "o", "h", "n", "s", "o", "n"]
const chars = "a,b,c,d,e,f";
console.log(chars.split(",")); // ["a", "b", "c", "d", "e", "f"]
const number = 100.32222;
console.log(number.toFixed(2)); // 100.32
const numbers = [1, 2 ,3, 10, 50];
// old way
console.log(numbers.indexOf(3) > -1); // true as it check if 3 is present in the array
// new way
console.log(numbers.includes(3)); // true
The includes method is also useful when comparing multiple values at once.
const day = "monday";
if(day === "monday" || day === "tuesday" || day === "wednesday" || day === "thursday") {
// do something
}
// The above code is the same as the below code
const day = "monday";
if(["monday", "tuesday", "wednesday", "thursday"].includes(day)) {
// do something
}
const user = {
name: 'David',
location: {
street: {
number: 20,
name: '11 wall street'
}
}
};
// old way
const streetName = user.location && user.location.street && user.location.street.name;
console.log(streetName); // 11 wall street
// new way
const streetName = user?.location?.street?.name;
console.log(streetName); // 11 wall street
Previously, to access the nested property we need to check for each property If it exists or not because directly accessing user.location.street.name will throw an error If the location or street property does not exist and we try to access name on it like this:
const user = {
name: 'David'
};
const streetName = user.location.street.name; // Uncaught TypeError: Cannot read property 'street' of undefined
But now with the ES11 optional chaining operator, the next code after ?. will be executed only if the previous reference is not undefined or null so we don't get any error.
const user = {
name: 'David'
};
const streetName = user?.location?.street?.name;
console.log(streetName); // undefined
So using the optional chaining operator makes the code shorter and easier to understand.
Want to learn Redux in detail and build a complete food ordering app? check out my Mastering Redux course.
Following is the preview of the app, we'll be building in the course. It's a great project you can add to your portfolio/resume.
Note that, in this app, I have used INR as the currency for displaying the prices but you can easily change it to USD or AUD or any other currency with a single configuration change in the app.
Want to stay up to date with regular content regarding JavaScript, React, Node.js? Follow me on LinkedIn.