Javascript Snippets

Javascript Snippets

Photo by Joan Gamell on Unsplash

Get current date and time

const now = new Date();

EXPLANATION : The code const now = new Date(); is written in JavaScript and creates a new instance of the Date object, assigning it to the variable now.

Here's a breakdown:

  • new Date(): This is a constructor function in JavaScript that creates a new Date object representing the current date and time when called without any arguments.

  • const: This is a keyword in JavaScript used to declare a constant variable. Constants, once assigned a value, cannot be reassigned to a new value.

  • now: This is the variable name chosen by the programmer to store the current date and time. Since it's declared using const, its value cannot be changed after initialization.

So, after executing this line of code, the variable now will hold a Date object representing the current date and time at the moment the line was executed.

Check if a variable is an array

Array.isArray(variable)

EXPLANATION : In JavaScript, Array.isArray(variable) is a method used to check whether a given variable is an array.

Here's a breakdown:

  • Array: This is the built-in JavaScript object for working with arrays.

  • isArray(): This is a method of the Array object. It checks whether the argument passed to it is an array or not.

  • variable: This is the variable or value that you want to check if it's an array or not.

The Array.isArray() method returns true if the variable is an array, and false otherwise. It's commonly used in JavaScript to ensure that a variable is an array before performing array-specific operations on it, thus preventing errors in the code.

Merge two arrays

const newArray = array1.concat(array2);

EXPLANATION : The line const newArray = array1.concat(array2); in JavaScript creates a new array by concatenating two existing arrays (array1 and array2).

Here's how it works:

  • array1 and array2 are existing arrays that you want to combine.

  • concat() is a method available for arrays in JavaScript. It creates a new array that includes elements from both array1 and array2. The original arrays are not modified.

  • The const keyword declares a constant variable named newArray, meaning that its value cannot be reassigned after it's initialized.

So, after this line of code is executed, newArray will contain all the elements of array1 followed by all the elements of array2, effectively combining them into a single array.

Remove duplicates from an array

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

EXPLANATION : The line const uniqueArray = [...new Set(array)]; in JavaScript creates a new array that contains only the unique elements of the original array array.

Here's how it works:

  • array is the original array from which you want to extract unique elements.

  • new Set(array): This part creates a new Set object from the elements of array. A Set is a collection of unique values, meaning it automatically eliminates duplicate values when created.

  • [...new Set(array)]: This part spreads the elements of the Set back into an array. The spread syntax (...) converts the Set object into an array.

  • const: This keyword declares a constant variable named uniqueArray, meaning its value cannot be reassigned after initialization.

So, after this line of code is executed, uniqueArray will contain only the unique elements of array, with duplicates removed.

Sort an array in ascending order

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

EXPLANATION : The line array.sort((a, b) => a - b); in JavaScript sorts the elements of the array array in ascending order.

Here's how it works:

  • array: This is the array that you want to sort.

  • sort(): This is a method available for arrays in JavaScript, used to sort the elements of an array.

  • (a, b) => a - b: This is a comparison function passed as an argument to the sort() method. It tells the sort() method how to sort the elements. In this case, it's a simple comparison function that sorts numbers in ascending order.

    • If the function returns a negative value (e.g., a - b is negative), a comes before b in the sorted array.

    • If the function returns a positive value (e.g., a - b is positive), b comes before a in the sorted array.

    • If the function returns 0, the relative order of a and b remains unchanged.

So, after executing this line of code, the elements of array will be sorted in ascending numerical order. If the elements are strings, they will be sorted alphabetically.

Reverse an array

array.reverse();

EXPLANATION : The line array.reverse(); in JavaScript reverses the order of elements in the array array.

Here's how it works:

  • array: This is the array whose elements you want to reverse.

  • reverse(): This is a method available for arrays in JavaScript, used to reverse the order of elements in the array.

When you call array.reverse(), the elements of the array will be reversed, with the first element becoming the last and the last element becoming the first. This operation modifies the original array; it doesn't create a new array with reversed elements.

Convert string to number

const number=parseInt(string);

EXPLANATION : The line const number = parseInt(string); in JavaScript parses a string (string) into an integer (number) using the parseInt() function.

Here's how it works:

  • string: This is the string that you want to convert into an integer.

  • parseInt(): This is a built-in JavaScript function used to parse a string and convert it into an integer.

  • const: This keyword declares a constant variable named number, meaning its value cannot be reassigned after initialization.

When you call parseInt(string), JavaScript attempts to convert the string into an integer. It starts parsing from the beginning of the string until it encounters a character that is not a valid part of an integer (such as a letter or a special character), or until the end of the string is reached.

Generate a random number between two values

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

EXPLANATION : The line const randomNumber = Math.floor(Math.random() * (max - min + 1)) + min; in JavaScript generates a random integer between min (inclusive) and max (inclusive).

Here's how it works:

  • Math.random(): This function returns a random floating-point number between 0 (inclusive) and 1 (exclusive).

  • max: This is the maximum value of the range.

  • min: This is the minimum value of the range.

  • (max - min + 1): This calculates the range of numbers that Math.random() can produce. Adding 1 ensures that the maximum value is inclusive.

  • Math.floor(): This function rounds down the result of Math.random() * (max - min + 1) to the nearest integer, effectively removing the decimal part and leaving only the integer part.

  • randomNumber: This is the variable that holds the generated random number.

By adding min to the result, you shift the range of random numbers to start from min.

So, after executing this line of code, randomNumber will hold a random integer value between min and max, inclusive.

Check if a string contains a substring

string.includes(substring)

EXPLANATION : In JavaScript, string.includes(substring) is a method used to determine whether a string (string) contains another string (substring) within it.

Here's how it works:

  • string: This is the main string you want to search within.

  • substring: This is the string you want to search for within the main string.

The includes() method returns true if the substring is found within the string, and false otherwise. It performs a case-sensitive search, meaning that the comparison is case-sensitive.

Get the length of an object

Object.keys(object).length;

EXPLANATION : In JavaScript, Object.keys(object).length is a way to count the number of properties (or keys) within an object (object).

Here's how it works:

  • object: This is the object whose properties you want to count.

  • Object.keys(): This is a built-in method in JavaScript that returns an array containing the names of all enumerable properties (keys) of the provided object.

  • .length: This property accesses the length of the array returned by Object.keys(), which is the number of keys in the object.

When you use Object.keys(object).length, it returns the count of keys in the object. This can be useful, for example, to determine the number of properties an object has or to check if it's empty.

Convert object to array

const array = Object.entries(object);

EXPLANATION : The line const array = Object.entries(object); in JavaScript creates an array (array) containing arrays of key-value pairs from the provided object (object).

Here's how it works:

  • object: This is the object whose key-value pairs you want to extract.

  • Object.entries(): This is a built-in method in JavaScript introduced in ECMAScript 2017 (ES8). It returns an array containing arrays of key-value pairs for each enumerable property of the provided object. Each inner array contains two elements: the key and its corresponding value.

  • const: This keyword declares a constant variable named array, meaning its value cannot be reassigned after initialization.

So, after executing Object.entries(object), array will contain arrays of key-value pairs extracted from object

Check if an object is empty

const array = Object.entries(object);

EXPLANATION : Certainly! Let's break down the line const array = Object.entries(object); in JavaScript:

  • const: This keyword is used to declare a constant variable named array. Constants, once assigned a value, cannot be reassigned to a new value.

  • array: This is the name of the constant variable being declared.

  • Object.entries(): This is a built-in method in JavaScript introduced in ECMAScript 2017 (ES8). It is used to extract the enumerable property key-value pairs from an object and return them as an array of arrays. Each inner array contains two elements: the property key and its corresponding value.

  • object: This is the object whose enumerable property key-value pairs you want to extract.

So, when you execute Object.entries(object), it returns an array of arrays containing the key-value pairs of the provided object. Each inner array within the returned array represents a key-value pair, where the first element is the key and the second element is the corresponding value. Finally, this array of key-value pairs is assigned to the constant variable array.

Get current URL

const currentUrl = window.location.href;

EXPLANATION : The line const currentUrl = window.location.href; in JavaScript retrieves the URL of the current webpage and stores it in the variable currentUrl.

Here's how it works:

  • window: This is a global object in web browsers that represents the current browser window.

  • location: This is a property of the window object that contains information about the current URL.

  • href: This is a property of the location object that returns the entire URL of the current webpage, including protocol, domain, port, path, query parameters, and fragment identifier.

  • const: This keyword declares a constant variable named currentUrl, meaning its value cannot be reassigned after initialization.

So, after executing this line of code, currentUrl will contain the URL of the current webpage. This can be useful for various purposes, such as tracking, logging, or dynamically generating links within the webpage.

Redirect to a new URL

window.location.replace(url);

EXPLANATION : The line window.location.replace(url); in JavaScript is used to navigate the browser to a new URL specified by the url parameter, replacing the current page in the browser's history.

Here's how it works:

  • window: This is a global object in web browsers that represents the current browser window.

  • location: This is a property of the window object that contains information about the current URL and provides methods for navigating to new URLs.

  • replace(): This is a method of the location object. It is used to replace the current URL in the browser's history with a new URL, effectively redirecting the browser to the new URL.

  • url: This is a string parameter that specifies the URL to which the browser should navigate.

When you call window.location.replace(url), the browser will navigate to the specified URL, and the current page in the browser's history will be replaced by the new page. This means that the user won't be able to navigate back to the original page using the browser's back button.

This method is commonly used for redirecting users to a new page after performing some action or for implementing page redirects in web applications.

Set a cookie

document.cookie = "name=value; expires=date; path=path; domain=domain; secure";

EXPLANATION : The line document.cookie = "name=value; expires=date; path=path; domain=domain; secure"; in JavaScript is used to set a cookie in the user's browser.

Here's what each part of the cookie string means:

  • name=value: This sets the name and value of the cookie. Replace name with the desired name of the cookie and value with the desired value.

  • expires=date: This optional attribute sets the expiration date and time for the cookie. Replace date with the desired expiration date and time in UTC format. If not specified, the cookie will be deleted when the browser session ends.

  • path=path: This optional attribute sets the path on the server for which the cookie is valid. Replace path with the desired path. If not specified, the default path is the current path of the document.

  • domain=domain: This optional attribute sets the domain for which the cookie is valid. Replace domain with the desired domain. If not specified, the default domain is the domain of the current document location.

  • secure: This optional attribute indicates that the cookie should only be transmitted over secure HTTPS connections. If present, no value needs to be specified. If not specified, the cookie will be transmitted over both HTTP and HTTPS connections.

Get a cookie

const cookieValue=document.cookie.replace(/(?:(?:^|.*;\s*)name\s*\=\s*([^;]*).*$/,"$1");

EXPLANATION : Here's a breakdown of the corrected regular expression pattern:

  • /: Delimiter for the regular expression.

  • (: Start of a capturing group.

    • ?:: Non-capturing group.

    • ^|.*;\s*: Match the start of the string or any characters followed by a semicolon and optional whitespace.

    • name: Match the string "name".

    • \s*=\s*: Match the equal sign with optional whitespace around it.

    • ([^;]*): Capture group to match and capture any characters except a semicolon (the cookie value).

    • .*$: Match any remaining characters until the end of the string.

  • )|: End of the capturing group.

  • ^.*$: Match any remaining characters from the start to the end of the string.

In this expression, the $1 in the replacement string refers to the content captured by the first capturing group, which is the value of the "name" cookie.

So, cookieValue will contain the value of the "name" cookie after executing this line of code.

Check if a cookie exists

document.cookie.split(';').some((item)=>item.trim().startsWith('name='));

EXPLANATION : Here's how it works:

  • document.cookie: This property returns a string containing a semicolon-separated list of all cookies associated with the current document.

  • split(';'): This method splits the document.cookie string into an array of substrings using semicolons as separators. Each substring represents an individual cookie.

  • some(): This method tests whether at least one element in the array satisfies the provided testing function.

  • item.trim().startsWith('name='): Inside the some() method, each item (cookie) is trimmed to remove leading and trailing whitespace using the trim() method. Then, startsWith('name=') checks if the cookie starts with the string "name=".

If at least one cookie in the list starts with "name=", the some() method returns true, indicating that a cookie with the name "name" exists. Otherwise, it returns false.

This code snippet is commonly used to check the existence of a specific cookie before performing operations involving its value.

Remove a cookie

document.cookie="name; expires=Thu, 01 Jan 1978 00:00:00 UTC; path=path; domain=domain; secure";

EXPLANATION : Here's a breakdown of each part of the cookie string:

  • name: This sets the name of the cookie to "name". Since no value is provided after the equal sign, the value of the cookie will be empty.

  • expires=Thu, 01 Jan 1978 00:00:00 UTC: This sets the expiration date and time for the cookie. In this case, it is set to expire on January 1, 1978, at midnight (UTC time). This effectively deletes the cookie immediately after it is set.

  • path=path: This sets the path on the server for which the cookie is valid. Replace path with the desired path. If not specified, the default path is the current path of the document.

  • domain=domain: This sets the domain for which the cookie is valid. Replace domain with the desired domain. If not specified, the default domain is the domain of the current document location.

  • secure: This indicates that the cookie should only be transmitted over secure HTTPS connections. If present, no value needs to be specified. If not specified, the cookie will be transmitted over both HTTP and HTTPS connections.

So, after executing this line of code, a cookie named "name" will be set in the browser with an empty value and the specified attributes. However, since it is set to expire immediately in 1978, it will essentially be deleted right after being set.

Get the current viewport dimensions

const viewportWidth = Math.max(document.documentElement.clientWidth || 0,window.innerWidth || 0);
const viewportHeight = Math.max(document.documentElement.clientHeight || 0,window.innerHeight || 0);

EXPLANATION : The code you provided calculates the viewport width and height of the browser window. Let's break it down:

const viewportWidth = Math.max(document.documentElement.clientWidth || 0, window.innerWidth || 0);
  • viewportWidth: This variable stores the calculated viewport width.

  • document.documentElement.clientWidth: This property retrieves the width of the viewport including the width of the vertical scrollbar (if present) but excluding the width of the vertical scrollbar. It's supported in most modern browsers.

  • window.innerWidth: This property retrieves the width of the viewport including the width of the vertical scrollbar (if present) but excluding the width of the vertical scrollbar. It's also supported in most modern browsers.

  • Math.max(): This function returns the maximum of the two values provided. It's used here to ensure that even if one of the values is unavailable (undefined), the calculation won't fail. The || 0 part ensures that if the value is undefined, it's treated as 0.

Similarly, for the viewport height:

const viewportHeight = Math.max(document.documentElement.clientHeight || 0, window.innerHeight || 0);
  • viewportHeight: This variable stores the calculated viewport height.

  • document.documentElement.clientHeight: This property retrieves the height of the viewport including the height of the horizontal scrollbar (if present) but excluding the height of the horizontal scrollbar. It's supported in most modern browsers.

  • window.innerHeight: This property retrieves the height of the viewport including the height of the horizontal scrollbar (if present) but excluding the height of the horizontal scrollbar. It's also supported in most modern browsers.

Overall, these two lines of code ensure that viewportWidth and viewportHeight contain the maximum available viewport width and height, respectively, considering various browser compatibility factors.

Copy text to clipboard

navigator.clipboard.writeText(text);

EXPLANATION : The line navigator.clipboard.writeText(text); in JavaScript writes the specified text to the clipboard of the user's device.

Here's how it works:

  • navigator: This is a built-in object in JavaScript that represents the browser environment and provides information about the browser and device.

  • clipboard: This is a property of the navigator object that provides access to the clipboard functionality.

  • writeText(): This is a method of the clipboard object. It is used to write text to the clipboard.

  • text: This is the text that you want to write to the clipboard.

When you call navigator.clipboard.writeText(text), it attempts to write the specified text to the clipboard. However, please note that this operation may fail due to various reasons, such as browser restrictions or user permissions. It's also worth noting that this method is only available in secure contexts (i.e., HTTPS).