DEV Community

Zouhair Sahtout
Zouhair Sahtout

Posted on

Function - JavaScript

Functions are one of the fundamental building blocks in JavaScript.
In JavaScript we have three type of function:
function declaration, function expression, arrow function

Function Declaration:

function declaration (also called a function definition, or function statement) consists of the function keyword:
Image descriptionWith function declaration, I can call the function before I define it in the code

Function Expression:

function expression(anonymous function) || remember expression produce a value, that's why we did store in a variable.
With function expression I can NOT call the function before I define it in the code.
Internally this happens because of a process called Hoisting.
Image description

Arrow Function

arrow function (just added to JavaScript in ES6).
In one line, without explicitly write the "return"
Image description

What type of function should I use?

Arrow functions, since they are easy to write, the answer is NO.
Because there is a fundamental difference, between the arrow function and more traditional functions (function declaration).
In fact the arrow function do NOT get so called this keyword

Function Calling other function

Image description



Summary
Most of the time you are gonna use function expression a lot, in JavaScript functions are actually just values.
So just as a number or a string or a boolean value.
Function is NOT a type:
It's not like a string or number type, it's a value
And because it's a value, that's why we can store it in a variable as we did above, the whole function get store it in a variable calcAge2.

I hope that helps I tried my best to explain the main different there's actually more that I did not cover.
And thank you if you read till here really appreciate it.

Top comments (0)