20+ Handy JavaScript Functions to Simplify Your Code | JavaScript Tutorial
Tags: javascript, webdev, programming, tutorial
Published: 2024-05-12 05:48:11


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:

{%youtube CUWQGt5rz28 %}

### Regular function

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

### Function expression

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

### Arrow function

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

### Generator function

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

### Create an array of numbers from 1 to n

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

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

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

### Create an array and fill it with a value

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

### Shuffling an array

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

### Remove Duplicated from Array

```javascript
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, ]
```
### Generate random number

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

### Find largest numbers

```javascript
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]
```

### Find smallest numbers

```javascript
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]
```
### Pick a random element from an array

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

### Convert array to object

```javascript
const toObject = (arr) => ({ ...arr });
console.log(toObject(["a", "b"])); // { 0: 'a', 1: 'b' }
```
### Find intersection of two arrays

```javascript
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]
```

### Remove falsy values from an array

```javascript
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]
```

### Reverse String

```javascript
const reverseString = (str) => str.split("").reverse().join("");
console.log(reverseString("hello")); // olleh
```
### Is String Palindrome

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

### Check object is empty or not

```javascript
const isEmpty = (obj) => Object.keys(obj).length === 0;
console.log(isEmpty({})); // true
```
### Find the number of days in a month

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

### Generate a random color

```javascript
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
```

---

##### Must Read If you haven't

{% link https://dev.to/devsmitra/how-to-create-the-app-using-jsx-without-react-k08 %}

{% link https://dev.to/devsmitra/reactjs-signal-for-state-mangement-21pf %}

{% link https://dev.to/devsmitra/simplify-javascripts-async-concepts-with-one-gif-3c6a %}

---

###### More content at [Dev.to](https://dev.to/devsmitra "Rahul Sharma(DevsMitra)").

{% user devsmitra %}

###### Catch me on
<p>
{% cta https://www.youtube.com/@bit-buddy?sub_confirmation=1 %} Youtube {% endcta %}
{% cta https://github.com/devsmitra %} Github {% endcta %}
{% cta https://www.linkedin.com/in/rahul-sharma-18b8b374 %} LinkedIn {% endcta %}
{% cta https://devsmitra.medium.com %} Medium {% endcta %}
{% cta https://stackblitz.com/@devsmitra %} Stackblitz {% endcta %} {% cta https://devsmitra.hashnode.dev %} Hashnode {% endcta %}
{% cta https://hackernoon.com/u/devsmitra %} HackerNoon {% endcta %}
</p>