javascript

function

Function

If you are looking to decrease the duplicated codes, then use function().

First of all, you will see why we have to use function() and second of all, you will the different ways of writing function().

This is the worst way of writing codes:

console.log(2 + 1);
console.log(543 + 1231);
console.log(1245 + 76543);
console.log(987 + 1345);
...

There might be a massive project that you are working and you figure it out that there is something with the codes, so you need to go through all the codes and find out the where the bug is coming from, but with this way:

function add(x, y) {
  return x + y;
}
 
console.log(add(2, 1));
console.log(add(543, 1231));
console.log(add(1245, 76543));
console.log(add(987, 1345));
...

Now you need to change the code from that function and it effects the whole codebase, interesting right?

I can change the plus to minus or multiplication or something you like very easy, and there is no need to go through the codes and change them manually which is nightmare for you and myself... haha

function add(x, y) {
  return x * y;
}
 
console.log(add(2, 1));
...

or even add number to them:

function add(x, y) {
  return x * y + 12;
}
 
console.log(add(2, 2)); // 2 * 2 + 12 => 16
...

You can do something with this just you need to learn it and use it, it is not that hard.

Once you learn, you will love to work with it all the time.

Different Ways of Writing function()

Function Declaration

function add(x, y) {
  return x + y;
}

Function Expression

const add = function (x, y) {
  return x + y;
};

Arrow Function

const add = (x, y) => {
  return x + y;
};

Short Callbacks

const add = (x, y) => x + y;

This kind of function is not used for large function.