12 useful JavaScript Code Snippet

Javascript Jeep🚙💨
4 min readMay 12, 2023


In this post we will look 12 useful javascript code snippet

Photo by Pankaj Patel on Unsplash

JavaScript is one of the most popular programming languages around. It has become a staple for dynamic and interactive web pages. But whether you’re a beginner or a seasoned developer, it never hurts to have a few code snippets up your sleeve. So in this post, I’m going to share 12 useful JavaScript code snippets with explanations.

Reverse a string

Let’s start with a simple one. This code snippet reverses the order of characters in a string.

function reverseString(str) {
return str.split("").reverse().join("");

The reverseString() function takes a string as input and returns the same string with the characters in reverse order. It uses the split() method to convert the string into an array of characters, then the reverse() method to reverse the order of the array, and finally the join() method to convert the array back into a string.

Count occurrences of a character

This code snippet counts the number of occurrences of a character in a string.

function countOccurences(str, char) {
return str.split(char).length - 1;
countOccurences("test", "t"); // 2

The countOccurrences() function takes two arguments: a string and a character. It returns the number of times the character appears in the string. It does this by using the split() method to convert the string into an array of substrings separated by the character, and then returning the length of the resulting array minus one.

Get current URL

This code snippet gets the current URL of the webpage.

const currentUrl = window.location.href;

The location.href property returns the current URL of the webpage, including any GET parameters.

Check if string contains substring

This code snippet checks if a string contains a substring.

const string = "hello world";
const substring = "world";
const containsSubstring = string.includes(substring); //true

The includes() method returns true if the string contains the given substring, and false otherwise.

Random number between two values

This code snippet generates a random number between two values.

function randomBetween(min, max) {
return Math.floor(Math.random() * (max - min + 1) + min);

The randomBetween function that takes two arguments: min and max. These arguments specify the minimum and maximum values between which we want to generate the random number (inclusive of both).

Inside the function, we use the built-in Math.random() method to generate a random number between 0 and 1 (exclusive of 1). We then multiply this number by the difference between max and min (inclusive of both) and add min. The floor() method is used to round the result down to the nearest integer, which gives us a random integer between min and max.

Note that we add 1 to the difference between max and min to include the upper bound. For example, if we want to generate a random number between 1 and 5, the difference between them is 4, so we add 1 to get 5 and make sure that 5 is included in the range.

Capitalize first letter of each word

This code snippet capitalizes the first letter of each word in a string.

function capitalizeWords(str) {
return str.replace(/\b\w/g, function(l){ return l.toUpperCase() });

The capitalizeWords() function takes a string and returns a new string with the first letter of each word capitalized. It does this by using a regular expression to match the first letter of each word (\b matches a word boundary, \w matches a word character), and using the replace() method to replace each match with its uppercase equivalent.

Find maximum value in array

This code snippet finds the maximum value in an array.

const nums = [1, 2, 3, 4, 5];
const maxNum = Math.max(...nums);

The Math.max() function takes any number of arguments and returns the largest value. The ... (spread) operator is used to pass an array of numbers as separate arguments to the function.

Sort array in ascending order

This code snippet sorts an array in ascending order.

const nums = [5, 3, 1, 4, 2];
nums.sort((a, b) => a - b);

The sort() method sorts an array in place, according to a specified sorting function. The sorting function subtracts a from b for ascending order.

Generate array of numbers

This code snippet generates an array of numbers based on a range.

function generateArray(start, end) {
return Array(end - start + 1).fill().map((_, idx) => start + idx)

The generateArray() function takes two arguments: a start and end value. It returns an array of numbers between those two values, inclusive of both. It does this by creating a new array with the Array() constructor, filling it with undefined values, and then using the map() method to replace those values with the corresponding numbers.

Check if variable is an array

This code snippet checks if a variable is an array.

const nums = [1, 2, 3, 4, 5];
const isArray = Array.isArray(nums);

The Array.isArray() function takes an argument and returns true if it is an array, and false otherwise.

Remove duplicates from array

This code snippet removes duplicates from an array.

const nums = [1, 2, 3, 2, 4, 5, 3];
const uniqueNums = [...new Set(nums)];

The Set object is used to create a new set of unique values, and then the ... (spread) operator is used to convert the set back into an array.

Remove falsy values from array

This code snippet removes falsy values (e.g. undefined, null, 0) from an array.

const arr = [0, 1, false, 2, '', 3];
const filtered = arr.filter(Boolean);

The filter() method creates a new array with all elements that pass the test implemented by the provided function. The Boolean constructor is used as the test function to remove all falsy values from the array.

These JavaScript code snippets will come in handy when you’re working on your next project. Whether you’re manipulating strings, arrays, or numbers, there’s a code snippet for almost everything. So go ahead and experiment with these snippets to see how you can use them to optimize your code and make your life a little easier.