DEV Community

Cover image for 20+ Handy JavaScript Functions to Simplify Your Code | JavaScript Tutorial
Rahul Sharma
Rahul Sharma

Posted on

20+ Handy JavaScript Functions to Simplify Your Code | JavaScript Tutorial

JavaScript is a functional programming language, and functions play a crucial role. They allow you to encapsulate reusable code and perform specific tasks. Here are some quick examples of functions that can make your life easier:

Regular function



function sum(a, b) {
  return a + b;
}


Enter fullscreen mode Exit fullscreen mode

Function expression



const sum = function (a, b) {
  return a + b;
};


Enter fullscreen mode Exit fullscreen mode

Arrow function



const sum = (a, b) => {
  return a + b;
};
// OR
const sum = (a, b) => a + b;


Enter fullscreen mode Exit fullscreen mode

Generator function



function* indexGenerator() {
  let index = 0;
  while (true) {
    yield index++;
  }
}
const g = indexGenerator();
console.log(g.next().value); // => 0
console.log(g.next().value); // => 1


Enter fullscreen mode Exit fullscreen mode

Create an array of numbers from 1 to n



const range = (n) => Array.from({ length: n }, (_, i) => i + 1);
console.log(range(10)); // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]


Enter fullscreen mode Exit fullscreen mode

Create an array of numbers from 1 to n with a step



const range = (n, step = 1) => Array.from({ length: n }, (_, i) => i * step);
console.log(range(10, 2)); // [1, 3, 5, 7, 9]


Enter fullscreen mode Exit fullscreen mode

Create an array and fill it with a value



const fill = (len, value) => Array(len).fill(value);
console.log(fill(3, 0)); // [0, 0, 0]


Enter fullscreen mode Exit fullscreen mode

Shuffling an array



const shuffleArray = (arr) => arr.sort(() => 0.5 - Math.random());
console.log(shuffleArray([1, 2, 3, 4])); // [3, 2, 1, 4]


Enter fullscreen mode Exit fullscreen mode

Remove Duplicated from Array



const removeDuplicated = (arr) => [...new Set(arr)];
console.log(removeDuplicated([1, 2, 3, 3, 4, 4, 5, 5, 6])); // Result: [ 1, 2, 3, 4, 5, 6 ]

const removeDuplicate = (arr) =>
  Object.values(arr.reduce((a, b) => (a[b] ? a : { ...a, [b]: b }), {}));
console.log(removeDuplicate([1, 2, 3, 3])); // Result: [ 1, 2, 3, ]


Enter fullscreen mode Exit fullscreen mode

Generate random number



const random = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min;
console.log(random(1, 10)); // Result: 1 ~ 10


Enter fullscreen mode Exit fullscreen mode

Find largest numbers



const findLargest = (arr) => arr.map((subArr) => Math.max(...subArr));
console.log(
  findLargest([
    [4, 5, 1, 3],
    [13, 27, 18, 26],
    [32, 35, 37, 39],
    [1000, 1001, 857, 1],
  ])
); // [5, 27, 39, 1001]


Enter fullscreen mode Exit fullscreen mode

Find smallest numbers



const findSmallest = (arr) => arr.map((subArr) => Math.min(...subArr));
console.log(
  findSmallest([
    [4, 5, 1, 3],
    [13, 27, 18, 26],
    [32, 35, 37, 39],
    [1000, 1001, 857, 1],
  ])
); // [1, 18, 32, 857]


Enter fullscreen mode Exit fullscreen mode

Pick a random element from an array



const pick = (arr) => arr[Math.floor(Math.random() * arr.length)];
console.log(pick([1, 2, 3, 4])); // 2


Enter fullscreen mode Exit fullscreen mode

Convert array to object



const toObject = (arr) => ({ ...arr });
console.log(toObject(["a", "b"])); // { 0: 'a', 1: 'b' }


Enter fullscreen mode Exit fullscreen mode

Find intersection of two arrays



const intersection = (arr1, arr2) => {
  const set = new Set(arr1);
  return arr2.filter((x) => set.has(x));
};
console.log(intersection([1, 2, 3], [2, 3, 4])); // [2, 3]


Enter fullscreen mode Exit fullscreen mode

Remove falsy values from an array



const compact = (arr) => arr.filter(Boolean);
console.log(compact([0, 1, false, 2, "", 3, "a", "e" * 23, NaN, "s", 34])); // [1, 2, 3, 'a', 's', 34]


Enter fullscreen mode Exit fullscreen mode

Reverse String



const reverseString = (str) => str.split("").reverse().join("");
console.log(reverseString("hello")); // olleh


Enter fullscreen mode Exit fullscreen mode

Is String Palindrome



const isPalindrome = (str) => str === str.split("").reverse().join("");
console.log(isPalindrome("madam")); // true


Enter fullscreen mode Exit fullscreen mode

Check object is empty or not



const isEmpty = (obj) => Object.keys(obj).length === 0;
console.log(isEmpty({})); // true


Enter fullscreen mode Exit fullscreen mode

Find the number of days in a month



const getDaysInMonth = (date) =>
  new Date(date.getFullYear(), date.getMonth() + 1, 0).getDate();
console.log(getDaysInMonth(new Date())); // 31


Enter fullscreen mode Exit fullscreen mode

Generate a random color



const getRandomColor = () =>
  `#${Math.floor(Math.random() * 16777215).toString(16)}`;
console.log(getRandomColor()); // #f0f0f0

const randomHex = () =>
  `#${Math.floor(Math.random() * 0xffffff)
    .toString(16)
    .padEnd(6, "0")}`;
console.log(randomHex()); // #f0f0f0


Enter fullscreen mode Exit fullscreen mode

Must Read If you haven't

More content at Dev.to.
Catch me on

Youtube Github LinkedIn Medium Stackblitz Hashnode HackerNoon

Top comments (10)

Collapse
 
tcjr profile image
Tom Carter

Nice list, but that shuffle function is not good and should be avoided. You can read all about the problems here: robweir.com/blog/2010/02/microsoft...

Collapse
 
joseph42a profile image
Joseph42A

Nice well done, just find a shorter way to build array from (n) numbers
Array.from(Array(n).keys())

Collapse
 
pierre profile image
Pierre-Henry Soria ✨

Nice list Rahul 🙂

Collapse
 
wemmersonalb profile image
Wemmerson Albuquerque

Nice! It reminded me of coding marathons =D

Collapse
 
timot profile image
Timothy Joseph Eslabra

this will help me a lot on learning JavaScript thank you so much Rahul <3

Collapse
 
mexikode profile image
MexiKode ⚙ • Edited


var kkeys = [], konami = "38,38,40,40,37,39,37,39,66,65";
window.addEventListener("keydown", function(e){
kkeys.push( e.keyCode );
if ( kkeys.toString().indexOf( konami ) >= 0 )
kkeys = [];
}, true);

99 lives

Collapse
 
mexikode profile image
MexiKode ⚙

generate cache-busting parameter for assets
let v = Date.now();

find needle in any string, example in path
if(top.location.href.includes('/blog')) //is in blog post view

get name of uri hash
let section = top.location.hash.substr(1);

Collapse
 
tushar1471 profile image
TUSHAR MALHOTRA

function shuffleArray(new_arr) {
for (let i = new_arr.length - 1; i >= 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[new_arr[i], new_arr[j]] = [new_arr[j], new_arr[i]];
}
return new_arr;

}

console.log(shuffleArray(new_arr)); For shuffling array

Collapse
 
ahsaniftikhar99 profile image
Ahsan Iftikhar

Brother how did you made the code snippet looked colored?

Collapse
 
devsmitra profile image
Rahul Sharma

Some comments may only be visible to logged-in visitors. Sign in to view all comments.