I have decided to get serious about learning JavaScript. My plan to help myself remember all the new concepts I’ll be learning from now on is to document the learning I’ll be doing through short blog posts. In this post I will go over three different ways to create functions in JS.
1. Regular Function
const square = function(x) { return x*x; };
Here, const
creates a new constant square
. In JavaScript, a constant is a variable that cannot be changed or redeclared. square
holds the value of a function that multiplies any number passed to it by itself, it returns the square of any number.
2. Function declaration
function add(a,b){ return a + b; }
The difference with this function from number 1 is that the function isn’t assigned to a value, it is simply declared and given a name.
3. Arrow Functions
const mult = (a, b) => { return a * b; };
I find the arrow function syntax hard to understand. One way to read this: const mult = (a, b) =>
is to think of it as meaning “this input in the parameters produces this result”, where the result is whatever the function is going to do.