JAVASCRIPT

JavaScript Parameters: Syntax, Usage, and Examples

In JavaScript, parameters allow functions to receive values from a function call. Within the function, parameters behave like variables. A parameter can be of any type, including booleans, numbers, strings, objects, and even functions.

How to Use JavaScript Function Parameters

Creating JavaScript function parameters involves listing them in the parentheses of a function declaration. You can add as many parameters as you like. Within the function, you can use them just like variables.

function functionName(parameter1, parameter2) {
	// Function body using parameter1 and parameter2
}
  • function: The keyword to initiate the function statement.
  • functionName: A unique identifier to name your function, following the JavaScript naming conventions.
  • parameter(s): Any number of variables listed inside the parentheses help pass data into the function (optional).

JavaScript Optional Parameters and Default Parameter Values

In JavaScript, default parameter values ensure parameters have values if the function receives no arguments from the function call.

function greet(name, greeting = "Hello") {
    console.log(greeting + ", " + name + "!");
}

// Example usage:
greet("Alice"); // Uses the default message "Hello"
greet("Bob", "Goodbye"); // Overrides the default message with "Goodbye"

When to Use JavaScript Function Parameters

JavaScript parameters are useful whenever you need to pass specific values into a function to perform its tasks. Parameters make functions flexible and reusable in various scenarios:

Handling Different Data

Parameters allow functions to process different data, making the functions more reusable. By using a parameter, a function that calculates the square of a number can take any number as an input.

function square(number) {
	return number ** 2;
}

// Using the function with different arguments
console.log(square(4)); // Outputs: 16
console.log(square(10)); // Outputs: 100

Configuring Function Behavior

Parameters can adjust how functions behave, allowing them to perform various tasks under different conditions with the same code.

function printTitle(title, underlineStr = "_") {
	console.log(title);
	console.log(underlineStr.repeat(title.length));
}

// Default underline
printTitle("Chapter 1")

// Customized underline
printTitle("Conclusion", "-")

Processing with User Input

Parameters are especially useful in functions that interact with user input, enabling dynamic responses based on the provided input.

function processUserChoice(choice) {
    if (choice === 1) {
        return "You've selected option 1: View Account Balance.";
    } else if (choice === 2) {
        return "You've selected option 2: Deposit Funds.";
    } else if (choice === 3) {
        return "You've selected option 3: Withdraw Funds.";
    } else {
        return "Invalid selection. Please choose a valid option.";
    }
}

// Responding to different user choices
console.log(processUserChoice(1));
console.log(processUserChoice(4));

Examples of JavaScript Parameters

Here are some examples demonstrating practical applications of parameters in JavaScript functions:

Order Processing

A shopping website might use parameters to process all orders the same way while only customizing the details. Parameters might set the item name, quantity, and whether to use gift wrapping.

function greetUser(name, greeting = "Hello") {
    console.log(`${greeting}, ${name}!`);
}
greetUser("Alice");  // Output: "Hello, Alice!"
greetUser("Bob", "Welcome");  // Output: "Welcome, Bob!"

Event Registration

An RSVP function might use parameters to handle different aspects of event registration. Potential parameters are the attendee's name, the number of guests, and special meal requests.

function calculateArea(length, width = 5) {
    return length * width;
}
console.log(calculateArea(10));  // Output: 50
console.log(calculateArea(10, 20));  // Output: 200

Temperature Conversion Function

A weather application might use parameters in a function to convert temperature from Celsius to Fahrenheit.

function convertTemperature(celsius, unit = "F") {
  const fahrenheit = (celsius * 9/5) + 32;
  const kelvin = celsius + 273.15;
  
  console.log(unit === "F" ? `${celsius}°C is ${fahrenheit}°F.` : `${celsius}°C is ${kelvin}K.`);
}

// Converting temperatures
convertTemperature(30); // Defaults to Fahrenheit
convertTemperature(20, "K"); // Converts to Kelvin

Search Engines

Parameters in a function can assemble search queries for data retrieval in applications like databases or search engines.

function createSearchQuery(category, keywords, limit = 10) {
    console.log(`Searching for ${keywords} in category ${category} with a limit of ${limit} results.`);
}

// Example search queries
createSearchQuery("books", "JavaScript");
createSearchQuery("electronics", "smartphone", 5);

Learn More About JavaScript Function Parameters

Rest Parameters

Rest parameters allow a function to accept an indefinite number of arguments as an array-like object. Using rest parameters provides a way to handle function parameters dynamically.

function sumAll(...numbers) {
    return numbers.reduce((sum, current) => sum + current, 0);
}
console.log(sumAll(1, 2, 3, 4, 5));  // Output: 15

Destructuring Parameters

Destructuring in function parameters helps in extracting values directly from objects or arrays passed as an argument.

function displayUserInfo({name, age}) {
    console.log(`Name: ${name}, Age: ${age}`);
}
displayUserInfo({name: "Alice", age: 30});  // Output: "Name: Alice, Age: 30"

Parameters vs. Arguments in JavaScript

While the terms "parameters" and "arguments" are often used interchangeably, they refer to different concepts.

Parameters are the variables in a function's declaration. Arguments, on the other hand, are the values you pass to the function in the function call. In a sense, the values you pass as arguments become parameters within a function.

function createUser(name, age) {
    // Here, 'name' and 'age' are parameters
    console.log(`User created with name: ${name} and age: ${age}`);
}

createUser("Alice", 30); // 'Alice' and 30 are arguments
Learn to Code in Python for Free
Start learning now
button icon
To advance beyond this tutorial and learn Python by doing, try the interactive experience of Mimo. Whether you're starting from scratch or brushing up your coding skills, Mimo helps you take your coding journey above and beyond.

Sign up or download Mimo from the App Store or Google Play to enhance your programming skills and prepare for a career in tech.

You can code, too.

© 2023 Mimo GmbH