JavaScript Code Snippet

Hi Guy’s Welcome to Proto Coders Point, In this Javascript article let’s checkout 15 useful JavaScript code snippets that will help you in various JS Programming tasks

1. Get current Date & Time

To get current date & time in javascript(nodejs), we can make use of Date() below are examples:

// Create a new Date object
const currentDate = new Date();

// Get the current date
const date = currentDate.getDate();

// Get the current month (Note: January is 0) so just add 1.
const month = currentDate.getMonth() + 1;

// Get the current year
const year = currentDate.getFullYear();

// Get the current hours
const hours = currentDate.getHours();

// Get the current minutes
const minutes = currentDate.getMinutes();

// Get the current seconds
const seconds = currentDate.getSeconds();

// Display the current date and time
console.log(`Current Date & Time: ${date}-${month}-${year} ${hours}:${minutes}:${seconds}`);

2. Check if the variable is an array:

To Check if an variable is array or no in JS, We can make use of inbuilt method i.e Array.isArray(), Below is an Example:

// Variable declaration
const myVariable = [1, 2, 3];

// Check if the variable is an array
if (Array.isArray(myVariable)) {
  console.log('The variable is an array.');
} else {
  console.log('The variable is not an array.');

3. Merge two arrays:

In Javascript there are two ways by which we can easily merge or concat two arrays: One is by using `concat()` method, another is by using spread operator ('...') Let;s check example of both of them:

Using `concat()` method:

// Arrays to be merged
const array1 = [1, 2, 3];
const array2 = [4, 5, 6];

// Merge the arrays using concat()
const mergedArray = array1.concat(array2);


Using Spread Operator (…):

// Arrays to be merged
const array1 = [1, 2, 3];
const array2 = [4, 5, 6];

// Merge the arrays using the spread operator
const mergedArray = [...array1, ...array2];


convert array to collection in javascript

4. Remove duplicates from an array:

In JavaScript, there are many ways by which we can remove any duplicates from a given list by using inbuilt methods: Let’s check them one by one.

Using Set Object:

const array = [1, 2, 3, 3, 4, 5, 5];

const uniqueArray = [ Set(array)];


The 'Set' Object is used by which a new set from the array is created, the Set will automatically remove the duplicate values, Then, In above example I have made use of Spread operator '...' to convert the new Set to Array.

converting list to set or set to list in dart

Using the filter() method:

const array = [1, 2, 3, 3, 4, 5, 5];

const uniqueArray = array.filter((value, index, self) => {
  return self.indexOf(value) === index;


we can also make use of filter() method in javascript to remove duplicate from a array, The filter() method has a callback function. The callback function checks if the index of current element is same as of first occurrences and thus it is added into uniqueArray variable.

Using the reduce() method:

const array = [1, 2, 3, 3, 4, 5, 5];

const uniqueArray = array.reduce((accumulator, currentValue) => {
  if (!accumulator.includes(currentValue)) {
  return accumulator;
}, []);


The reduce() method will iterate to the given array and here while iterating to each item from the array we check is it already included in new array by includes() method, If not Included then push the currentValue (Index Item) Into the new array.

The Above Example will create a new array variable with content [1, 2, 3, 4, 5], removing all the duplicates occurrences.

5. Sort an array in ascending order:

To Sort an array in javascript, let’s make use of `sort()` method, Here’s an example:

const array = [3, 1, 4, 2, 5];

// Sort the array in ascending order
const sortedArray = array.sort((a, b) => a - b);


6. Reverse an array:

To reverse an array, will make use of reverse() method, Here’s an example:

const array = [1, 2, 3, 4, 5];

// Reverse the array
const reversedArray = array.reverse();


On an given array, we can apply reverse() method, it will simply reverse all the element from the original array and create a new Array.

7. Convert string to number:

In JavaScript, To convert string to an number, we can make use of parse method i.e. parseInt() or parseFloat() let’s see an example:

Using parseInt() to convert string to integer

const stringNumber = "42";
const number = parseInt(stringNumber);


Using parseFloat() to convert a string to float-point number

const stringNumber = "3.14";
const number = parseFloat(stringNumber);


8. Generate a random number between two values:

In JavaScript, To generate a number between a given range we can make use of Math.random() method, Here is an example:

const min = 1;   // Minimum value
const max = 10;  // Maximum value

// Generate a random number between min and max
const randomNumber = Math.floor(Math.random() * (max - min + 1)) + min;


9. Check if a string contains a substring:

To check is a given string variable contain a particular world or substring we can either use includes() or indexOf() method, Let’s understand this will code snippets:

Using includes() method:

const string = "Hello, world!";
const substring = "world";

// Check if the string contains the substring
const containsSubstring = string.includes(substring);


Using indexOf() method:

const string = "Hello, world!";
const substring = "world";

// Check if the string contains the substring
const containsSubstring = string.indexOf(substring) !== -1;


10. Get the Length of an Object:

In JS, Objects don’t has any inBuilt method or function to get the length of an object like arrays has, But as object has key-value pair elements in it we can get length of an object using key or value, Below is an example:

const myObject = {
  name: "John",
  age: 30,
  city: "New York"

// Get the length of the object
const objectLength = Object.keys(myObject).length;


The Object.keys() method is used to retrieve an array of the object keys and then ‘length’ property is used on the array to get the number of keys in an object.

11. Convert Object to array:

To convert an object into array in JS, We will use Object.entries() method:

const myObject = {
  name: "John",
  age: 30,
  city: "New York"

// Convert the object to an array
const objectArray = Object.entries(myObject);


In this code snippet, the Object.entries() method is called on the myObject object. It returns an array of arrays, where each inner array contains two elements: the key and the corresponding value from the object.

The resulting array, objectArray, will look like this:

  ["name", "John"],
  ["age", 30],
  ["city", "New York"]

12. Check if an object is empty:

To check of an object is empty we can use either of this two method i.e Object.keys() or Object.entries(), Example code snippet below:

Using Object.keys() to check if object is empty:

const myObject = {};

// Check if the object is empty
const isEmpty = Object.keys(myObject).length === 0;


Using Object.entries() to check if object is empty:

const myObject = {};

// Check if the object is empty
const isEmpty = Object.entries(myObject).length === 0;


13. get current URL:

In browser, If you want to add feature to your application to get the current URL using JavaScript we can make use of window.location Here is an example:

var currentURL = window.location.href;

The above code, window.location.href browser property will return the complete URL.

14. Redirect to a new URL:

In Javascript, to redirect a user to desired URL we can make use of window.location with assign() method or by using window.location.href. Here’s an example of how to redirect to a URL:

window.location.href = "";

15. Copy text to clipboard

In Javascript, to copy a text to a clipboard, we can make use of document.execCommand('copy'); method or by using Clipboard API both the code example are given below:

using Clipboard API method:

Here to copy the content we are using clip API writeText() function to copy/write the text content into clipboard.

const textToCopy = "Text to copy";
  .then(() => {
    console.log("Text copied to clipboard");
  .catch((error) => {
    console.error("Error copying text to clipboard:", error);

Using document.execCommand()

const textToCopy = "Text to copy";
var tempInput = document.createElement("input");
tempInput.value = textToCopy;
console.log("Text copied to clipboard");