JavaScript 4 Ways To Create Function
First we have the Function Declaration. This is mostly common way to create a javascript 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...
First we have the Function Declaration
. This is mostly common way to create a javascript 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
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
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
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
Thanks for Reading my short read, If you like to Buy me coffee, click the image.