DEV Community

Jenuel Oras Ganawed
Jenuel Oras Ganawed

Posted on

JavaScript 4 Ways To Create Function

First we have the Function Declaration. This is mostly common way to create a function as shown in the bellow example. What good about this is you can use the function even if the function is declared on the very bottom of your codes.

function addTwoNumbers(num1, num2) {
    return num1 + num2;
}
console.log(addTwoNumbers(1,10));
// outputs: 11
Enter fullscreen mode Exit fullscreen mode

Function Expression is a function were you asign a function in a variable. Function assigned to a variable needs to be declared on top before using the function.

console.log(addTwoNumbers(1,10)); // Error, becayse cant find addTwo Numbers
const addTwoNumbers = function (num1, num2) {
    return num1 + num2;
}
console.log(addTwoNumbers(1,10));
// outputs: 11
Enter fullscreen mode Exit fullscreen mode

Arrow Function Expression, this function is like a functional expression but instead of writing function we use arrows => instead.

const addTwoNumbers = (num1, num2) => {
    return num1 + num2;
}
console.log(addTwoNumbers(1,10));
// outputs: 11
Enter fullscreen mode Exit fullscreen mode

Concised Arrow Function Expression, is a function were you can directly return without writing a return statement. note: only works if It will directly return a value.

const addTwoNumbers = (num1, num2) => num1 + num2;
console.log(addTwoNumbers(1,10));
// outputs: 11
Enter fullscreen mode Exit fullscreen mode

Thanks for Reading my short read, If you like to Buy me coffee, click the image.

drawing

Top comments (0)