Programming Tutorials

Different ways you can pass arguments to a function in JavaScript

By: Tanya in Javascript Tutorials on 2023-04-25  

Here are the different ways you can pass arguments to a function in JavaScript, using the area function example:

  1. Positional parameters: This is the traditional way of passing arguments to a function, where the values are listed in order of their corresponding parameters. For example:
function area(width, height) {
  return width * height;
}

area(10, 20); // returns 200
  1. Default parameters: You can provide default values for function parameters, which are used when no argument is provided or when undefined is passed as the argument. For example:
function area(width = 5, height = 10) {
  return width * height;
}

area(); // returns 50
area(3); // returns 30
area(4, 6); // returns 24
  1. Rest parameters: You can use the rest parameter syntax (...) to pass an arbitrary number of arguments as an array. For example:
function area(...dimensions) {
  let total = 1;
  dimensions.forEach(dimension => {
    total *= dimension;
  });
  return total;
}

area(2, 3, 4); // returns 24
area(2, 3, 4, 5); // returns 120
  1. Object destructuring: You can pass an object as an argument and destructure its properties to obtain the parameter values. This can make the code more readable and easier to understand. For example:
 function area({ width, height }) {
  return width * height;
}

area({ width: 10, height: 20 }); // returns 200

In this case, the argument passed to the area function is an object with properties width and height. The function uses destructuring to extract these values and calculate the area.

  1. Object spread: You can use the object spread syntax (...) to pass an object as an argument and spread its properties into individual parameters. For example:
function area({ width, height }) {
  return width * height;
}

const dimensions = { width: 10, height: 20 };
area({ ...dimensions }); // returns 200

In this case, the object dimensions is passed as an argument to the area function. The spread syntax is used to spread the object properties into individual parameters for the area function.






Add Comment

* Required information
1000

Comments

No comments yet. Be the first!

Most Viewed Articles (in Javascript )

Latest Articles (in Javascript)