Practical functions

Creating useful JavaScript functions for everyday tasks like string manipulation, number validation, and financial calculations.

Learning Goals

At the end of this Tutorial, you will be able to:

  • Create functions to validate and manipulate text strings
  • Test strings for length, position, and specific characters
  • Verifying a variable contains a valid number.
  • Rounding numbers and calculating percentages.
  • Working with currency amounts.

Continue using the functions.html workfile you downloaded in the Function Declarations Tutorial.

📄  Functions: Exercises

Working with strings

In JavaScript, you often need to work with text strings. The following functions help with common string operations.

Checking for a character

Copy the following code to your practical-functions.html workfile.

// Function to check if a string contains a specific word
function containsWord(text, searchWord) {
    // Convert both strings to lowercase for case-insensitive search
    return text.toLowerCase().includes(searchWord.toLowerCase());
}
    
// Test the function
let testText = "Hello World";
if (containsWord(testText, "world")) {
    console.log("Found the word!");
}

Note the following:

  • The statement begins with a function declaration.
  • The text string and search word are passed as parameters.
  • The function returns true or false.

Character counting

Let's try another example. Copy this code to your workfile.

// Function to count occurrences of a character
function countCharacter(text, char) {
    return text.split(char).length - 1;
}
    
// Test the function
console.log(countCharacter("hello@example.com", "@")); // Outputs: 1
console.log(countCharacter("javascript", "a")); // Outputs: 2

String length and position

It is good practice to validate string lengths before processing them.

Copy this code to your workfile:

// Function to check string length is within range
function isValidLength(text, minLength, maxLength) {
    const length = text.trim().length;
    return length >= minLength && length <= maxLength;
}
    
// Test the function
let userName = "Jo";  // Too short
if (!isValidLength(userName, 3, 20)) {
    console.log("Username must be between 3 and 20 characters");
}

The function above helps you:

  • Remove whitespace from both ends of the string
  • Check if the remaining text is within allowed length
  • Return true or false

Working with numbers

Before performing operations, it's important to verify the data types of your values.

Data Type

Description

string

Text within quotes, such as "Hello, World".

number

A number without surrounding quotes, such as 12 or 9.99.

boolean

Only two possible values: either true or false.

null

A data type that intentionally has no value.

Verifying a variable is a valid number

Copy this type checking function to your workfile:

// Function to check if value can be used in calculations
function isValidNumber(value) {
    const num = Number(value);
    return !isNaN(num) && isFinite(num);
}
        
// Test the function
console.log(isValidNumber("123")); // true
console.log(isValidNumber("abc")); // false
console.log(isValidNumber("12.34")); // true

Rounding numbers

Here's a function for precise decimal rounding. Add this to your workfile:

// Function to round to 2 decimal places
function roundMoney(amount) {
    return Math.round(amount * 100) / 100;
}
    
// Test the function
console.log(roundMoney(10.567)); // Outputs: 10.57
console.log(roundMoney(10.564)); // Outputs: 10.56

Percentage calculations

Copy this percentage calculation function to your workfile:

// Function to calculate percentage
function calculatePercentage(amount, percentage) {
    if (!isValidNumber(amount) || !isValidNumber(percentage)) {
        return "Error: Invalid numbers";
    }
    return roundMoney((Number(amount) * Number(percentage)) / 100);
}
    
// Test the function
console.log(calculatePercentage(100, 15)); // Outputs: 15.00
console.log(calculatePercentage("100", "15.5")); // Outputs: 15.50

Currencies and financial calculations

When working with money values, precision and proper formatting are essential.

Copy this currency formatting function to your workfile:

// Function to format number as currency
function formatCurrency(amount, currency = 'USD') {
    const currencies = {
        'USD': { symbol: '$', locale: 'en-US' },
        'EUR': { symbol: '€', locale: 'de-DE' }
    };
                
    const { locale } = currencies[currency] || currencies['USD'];
                
    return new Intl.NumberFormat(locale, {
        style: 'currency',
        currency: currency
    }).format(amount);
}
            
// Test the function
console.log(formatCurrency(123.456, 'USD')); // Outputs: "$123.46"
console.log(formatCurrency(123.456, 'EUR')); // Outputs: "123,46 €"

Note the following:

  • The function accepts an amount and optional currency type
  • It uses the browser's built-in number formatting
  • Numbers are automatically rounded to two decimal places
  • Currency symbols are properly positioned based on locale

Further Resources