Useful JavaScript snippets you need in your everyday tasks as a developer

Useful JS code snippets


As a frontend developer, JavaScript is a must-know in this world. This article will give you a list of useful snippets I have saved and used when coding.

These snippets are the most common tasks I face when writing JavaScript code. If you have other useful snippets, please let me know in the comment section.

Let’s go!

#1-Sorting an array

const months = ['March', 'Jan', 'Feb', 'Dec'];
// expected output: Array ["Dec", "Feb", "Jan", "March"]
const numbers= [1, 30, 4, 21, 100000];
numbers.sort((a,b)=> {return a-b});
// expected output: Array [1, 4, 21, 30, 100000]

#2-Filtring an array

const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];const result = words.filter(word => word.length > 6);console.log(result);
// expected output: Array ["exuberant", "destruction", "present"]

#3-Looping through an array

let cars = ["Ford", "Ferrari", "BMW"];for(let car of cars){
// Ford
// Ferrari
// BMW

#4-Select random element

let items = ["Facebook", "Youtube", "Instagram", "Twitter"];let index = Math.floor(Math.random() * items.length );

#5-Check if an element has a CSS class

const element = document.querySelector("#elt");
const isActive = element.classList.contains("active");
// Returns true or false

#6-String interpolation

let name = "Front";console.log(`Hello, so happy to see you in our ${name} blog!`);
// Hello, so happy to see you in our Front blog!

#7-Replace in a string

let str = "My awesome string!";
let txt = str.replace("string", "text");
console.log(txt);// My awesome text!

#8-Get current time

let d = new date();
let now = `${d.getHours()}:${d.getMinutes()}:${d.getSeconds()}`;
console.log(now);// 11:04:21

#9-Reverse a string

function reverse(str){
return str.split("").reverse().join("");
const reversed = reverse("FRONT");

Dear reader, I hope this was clear and useful.

I hope you’re safe wherever you are and your family too! Hang in there. Tomorrow will be better!

Let’s get in touch on Medium, Linkedin, Facebook, Instagram, or Twitter.



I’m a passionate software engineer and woman in the tech world. Find more about me here: 🔗 I love to help people and share what I know!

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store