CodeGym /Java Course /Frontend SELF EN /Function Parameters

Function Parameters

Frontend SELF EN
Level 35 , Lesson 3
Available

4.1 Function Parameters

Function parameters in JavaScript let you pass values to functions for processing. This makes functions more flexible and adaptable. In this section, we'll look at the main aspects of working with function parameters in JavaScript, excluding default and rest parameters.

Parameters are specified in parentheses after the function name. When calling the function, the values of these parameters get passed to the corresponding variables inside the function.

Example:

The function greet() has two parameters: name and age. When calling the function, the values Alice and 30 are passed to these parameters.

JavaScript
    
      function greet(name, age) {
        return `Hello, ${name}! You are ${age} years old.`;
      }
      console.log(greet('Alice', 30)); // "Hello, Alice! You are 30 years old."
    
  

Handling Undefined Parameters

If a parameter isn't passed when calling a function, its value will be undefined. This can lead to errors if operations that don't support undefined are performed with such a parameter.

Example:

In the function greet(), it checks if the parameter name was passed. If not, the string Guest is used.

JavaScript
    
      function greet(name) {
        if (name === undefined) {
          return 'Hello, Guest!';
        }
        return `Hello, ${name}!`;
      }

      console.log(greet()); // "Hello, Guest!"
      console.log(greet('Bob')); // "Hello, Bob!"
    
  

4.2 Default Parameters

Default parameters allow you to set values that will be used if an argument isn't passed when calling the function or is passed as undefined. This is especially useful for creating functions with optional parameters.

Syntax:

    
      function name (arg1 = value1, arg2 = value2) {
        // function body
      }
    
  

Example 1: Simple Function with Default Parameters

In this example, the function greet() has the parameter name with a default value of Guest. If an argument isn't passed, the default value will be used.

JavaScript
    
      function greet(name = 'Guest') {
        return `Hello, ${name}!`;
      }

      console.log(greet('Alice')); // Outputs: Hello, Alice!
      console.log(greet());        // Outputs: Hello, Guest!
    
  

Example 2: Default Parameters with Expressions

In this example, the tax parameter defaults to 20% of price if no other argument is passed.

JavaScript
    
      function calculatePrice(price, tax = price * 0.2) {
        return price + tax;
      }

      console.log(calculatePrice(100));  // Outputs: 120
      console.log(calculatePrice(100, 15)); // Outputs: 115
    
  

Example 3: Default Parameters Dependent on Other Parameters

In this example, default parameters allow creating a user with predefined roles and statuses.

JavaScript
    
      function createUser(name, role = 'user', isActive = true) {
        return { name, role, isActive };
      }

      console.log(createUser('Alice')); // Outputs: { name: 'Alice', role: 'user', isActive: true }
      console.log(createUser('Bob', 'admin')); // Outputs: { name: 'Bob', role: 'admin', isActive: true }
      console.log(createUser('Charlie', 'moderator', false)); // Outputs: { name: 'Charlie', role: 'moderator', isActive: false }
    
  

4.3 Rest Parameters

Rest parameters allow a function to accept any number of arguments and gather them into an array. This is useful for creating functions that can work with an arbitrary number of arguments.

Syntax:

    
      function name (arg1, arg2, ...argArray) {
        // function body
      }
    
  

Example 1: Summing All Passed Arguments

In this example, the function sumAll() uses rest parameters to sum all passed arguments.

JavaScript
    
      function sumAll(...numbers) {
        return numbers.reduce((sum, num) => sum + num, 0);
      }

      console.log(sumAll(1, 2, 3));       // Outputs: 6
      console.log(sumAll(4, 5, 6, 7, 8)); // Outputs: 30
    
  

Example 2: Function with Fixed and Rest Parameters

In this example, the function showItems() takes a fixed parameter firstItem and an indefinite number of other arguments, gathered into an array otherItems.

JavaScript
    
      function showItems(firstItem, ...otherItems) {
        console.log(`First item: ${firstItem}`);
        console.log(`Other items: ${otherItems.join(', ')}`);
      }

      showItems('apple', 'banana', 'cherry', 'date');

      // Outputs:
      // First item: apple
      // Other items: banana, cherry, date
    
  

Example 3: Function with Dynamic Arguments

In this example, the function createMessage() takes the first argument messageType and gathers all other parameters into an array messages to create a message.

JavaScript
    
      function createMessage(messageType, ...messages) {
        return `[${messageType.toUpperCase()}]: ${messages.join(' ')}`;
      }

      console.log(createMessage('info', 'This', 'is', 'an', 'informational', 'message'));
      // Outputs: [INFO]: This is an informational message

      console.log(createMessage('error', 'An', 'error', 'occurred'));
      // Outputs: [ERROR]: An error occurred
    
  
1
Task
Frontend SELF EN, level 35, lesson 3
Locked
Price with Tax
Price with Tax
1
Task
Frontend SELF EN, level 35, lesson 3
Locked
The First and the Rest
The First and the Rest
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION