After learning what functions are in JavaScript, I came across different ways of writing them.
At first, I thought they were all completely different. But after trying them out, I realized the main difference is just how we write and use them.
Function Declaration
This is the normal way of creating a function.
function greet() {
console.log("Hello!");
}
Then we can call it whenever we need it.
greet();
This is probably the easiest one to understand when you're starting out.
Function Expression
Here, we assign a function to a variable.
const greet = function() {
console.log("Hello!");
};
It works like a normal function, but the function is stored inside the variable.
Arrow Function
Arrow functions are a shorter way of writing functions.
const greet = () => {
console.log("Hello!");
};
You'll see these a lot in modern JavaScript, especially when working with arrays and frameworks.
Anonymous Function
An anonymous function is simply a function that doesn't have a name.
For example:
setTimeout(function() {
console.log("Hello!");
}, 1000);
Here, the function is passed directly to setTimeout, so we don't need to give it a name.
IIFE
IIFE stands for Immediately Invoked Function Expression.
The name sounds complicated, but the idea is simple. The function runs immediately after it is created.
(function() {
console.log("Hello!");
})();
You may not use IIFE very often in modern JavaScript, but it's still good to know what it means when you see it in existing code.
What I take from this
There are several ways to write functions, but I don't think you need to memorize all of them at once.
Start with function declarations and arrow functions. Once you're comfortable with those, the other types will be much easier to understand.
The more JavaScript you write, the more naturally you'll know which one to use.
Top comments (2)
Function expression and storing a function in a variable are two different things. You haven't actually explained what function expression is.
Thanks for pointing it out.