5 JavaScript Useful Functions

5 JavaScript Useful Functions
December 12, 2023

1. Function to Format Number as Currency

function formatCurrency(number) {
  return new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }).format(number);
}

This code defines a function named formatCurrency which is used to format a number into a currency format, specifically in US dollars.

Function Name: formatCurrency:

Converts a number to US dollar format.

Parameter: number:

The number you want to convert.

Key Actions:

Uses Intl.NumberFormat to format the number.

Sets the format to US dollars ('en-US', { style: 'currency', currency: 'USD' }).

Returns the formatted number as a string, like "$100.00".

2. Function to Copy Text to Clipboard

function copyToClipboard(text) {
  const elem = document.createElement('textarea');
  elem.value = text;
  document.body.appendChild(elem);
  elem.select();
  document.execCommand('copy');
  document.body.removeChild(elem);
}

Function Name: copyToClipboard

This function is used to copy text to the clipboard.

Parameter: text

The text you want to copy.

Creating a Text Area:

document.createElement('textarea'): Creates a new, hidden text area element on the webpage.

elem.value = text: Sets the value of this text area to the text you want to copy.

Adding to Document:

document.body.appendChild(elem): Temporarily adds the text area to the webpage so it can be used for copying.

Selecting the Text:

elem.select(): Selects (highlights) all the text in the text area.

Copying the Text:

document.execCommand('copy'): Copies the selected text to the clipboard, like pressing Ctrl+C.

Removing the Text Area:

document.body.removeChild(elem): Removes the text area from the webpage, as it's no longer needed.

3. Function to Get the Current URL

function getCurrentUrl() {
  return window.location.href;
}

Function Name: getCurrentUrl

It's a function designed to give you the current webpage's URL.

What it Does:

window.location.href: This part gets the full address (URL) of the webpage you are currently on.

Return Value:

The function returns the URL as a string of text.

4. Function to Scroll to the Top of the Page

function scrollToTop() {
  window.scrollTo(0, 0);
}

Function Name: scrollToTop

This function is designed to quickly take you to the very top of the webpage you're viewing.

What it Does:

window.scrollTo(0, 0): This command is the key part of the function.

It tells the browser to scroll to a specific position on the page.

The numbers (0, 0) represent the coordinates at the top-left corner of the webpage.

Result:

After this function runs, you'll find yourself at the top of the webpage, no matter where you were on that page before.

5. Function to Generate a UUID (Universally Unique Identifier)

function generateUUID() {
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
    var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
    return v.toString(16);
  });
}

Function Name: generateUUID

It's designed to generate a unique string of characters, known as a UUID (Universally Unique Identifier).

UUID Format:

The UUID format is represented by the string 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.

This format includes random numbers and letters, separated by hyphens.

Generating Random Values:

.replace(/[xy]/g, function(c) { ... }): This part replaces each 'x' and 'y' in the format with random hexadecimal values (0-9 and a-f).

For each 'x', it uses a completely random value.

For 'y', it calculates a value that makes sure the UUID follows certain standards.

Random Number Calculation:

var r = Math.random() * 16 | 0: Generates a random number for each replacement.

v = c === 'x' ? r : (r & 0x3 | 0x8): Determines the final value to replace 'x' or 'y'.

Converting to Hexadecimal:

v.toString(16): Converts the value into a hexadecimal (base 16) number.

Return Value:

The function returns a unique string in the UUID format.


Resources for You

ChatGPT Guide For Software Developers

Learn to use ChatGPT to stay ahead of competition

Front-End Developer Interview Kit

Today, Start preparing to get your dream job!

JavaScript Developer Kit

Start your JavaScript journey today!

Master JavaScript by Solving Daily Challenges

Challenge Yourself Daily: Advance Your JavaScript Skills and Career

View Challenges

Newsletter for Developers!

Join our newsletter to get important Web Development and Technology Updates