20 Best Javascript Code Snippet

Peng Cao
2 min readSep 5, 2023

1. Get current date and time:

const now = new Date();

2. Check if a variable is an array:

Array.isArray(variable);

3. Merge two arrays:

const newArray = array1.concat(array2);
const newArray = […array1, …array2];

4. Remove duplicates from an array:

const uniqueArray = […new Set(array)];

5. Sort an array in ascending order:

array.sort((a, b) => a — b);

6. Reverse an array:

array.reverse();

7. Convert string to number:

const number = parseInt(string);

8. Generate a random number between two values:

const randomNumber = Math.floor(Math.random() * (max — min + 1)) + min;

9. Check if a string contains a substring:

string.includes(substring);

10. Get the length of an object:

Object.keys(object).length;

--

--

Peng Cao

Writing programming and tech guide; Help each other with followers, thanks mate! Let's version up @ v2.digital