This page looks best with JavaScript enabled

Passing Arguments to a Javascript Function

 ·   ·  ☕ 2 min read

You can pass one or more values to a function, but that has been made much easier and streamlined with the advent of ES2015 - 2018 standards.

Let’s start with a simple function.

1
2
3
4
5
6
function sum(x, y) {
  return x + y;
}

const summer = sum(3, 6);
console.log(summer); // 9

If you follow the newer standards, you can rewrite the above function to -

1
2
3
4
5
6
const diff = (x, y) => {
  return x - y;
};

const differ = sum(6, 3);
console.log(differ); // 3

If you change the order of arguments, the ‘sum’ function is not impacted, but ‘diff’ function is not impacted. I typically tend to use named variables to avoid this issue.

1
2
3
4
5
6
function sum({ x, y }) {
  return x - y;
}

const differ = sum({ x: 6, y: 3 });
console.log(differ); // 3

By using an object, you can re-order variables, add new variables, and in general, refactor much more easily than ever before.

Follow a more popular format that can selectively extract variables as well -

1
2
3
4
5
6
7
function sum(data) {
  let { x, y } = { ...data };
  return x - y;
}

const differ = sum({ x: 6, y: 3 });
console.log(differ); // 3

You can also use the spread operator in the function.

1
2
3
4
5
6
function sum({ x, y, ...rest }) {
  return x - y;
}

const differ = sum({ x: 6, y: 3, z: 12 });
console.log(differ); // 3

Functions arguments can specify default values.

1
2
3
4
5
function multi(number, factor) {
  return factor * number;
}

console.log(multi(1, 2)); // 2

Below is my preferred way to pass arguments - we simply use a single (or minimal) objects and named arguments within the object(s).

1
2
3
4
5
function multi({ factor = 1, number }) {
  return factor * number;
}

console.log(multi({ number: 2 })); // 2
Stay in touch!
Share on

Prashanth Krishnamurthy
WRITTEN BY
Prashanth Krishnamurthy
Technologist | Creator of Things