Function Declaration vs. Function Expression - Who Wins? ⚔️

Function Declaration vs. Function Expression - Who Wins? ⚔️

JavaScript is like a chaotic kitchen 🍳, and functions are your recipes. But wait! There are two ways to write a recipe: Function Declarations and Function Expressions. Let’s see who’s the real MasterChef! 🏆

The Name Game

Function Declaration 🏷️

Think of it as a well-organized library 📚. Every book has a fixed title and can be found easily.

function readBook() {
    console.log("📖 Reading a book...");
}

Here, readBook is a named function and can be called anytime.

Function Expression 🤫

This one is more like a mystery novel with a missing cover. It exists but doesn’t always have a name.

const readBook = function() {
    console.log("📖 Reading a book...");
};

This is an anonymous function stored in a variable.

🔎 Key Difference: Function Declarations have names, while Function Expressions can be anonymous.

The Hoisting Drama

Afraid of jargon? Me too! Hoisting simply means a mechanism where variable and function declarations are moved to the top of their scope before the code is executed.

Function Declaration 🚀

This is like a superhero. 🦸‍♂️ It flies to the top (hoists itself) and is ready before you even call it.

turnOnLight(); // 💡 Turning on the light...

function turnOnLight() {
    console.log("💡 Turning on the light...");
}

Boom! No errors! The function is available anywhere in the code. 🎉

Function Expression 🚫

This one is a lazy couch potato 🛋️. It doesn’t get up until you explicitly tell it to.

turnOnTV(); // ❌ Error: Cannot access 'turnOnTV' before initialization

const turnOnTV = function() {
    console.log("📺 Turning on the TV...");
};

Oops! Function Expressions don’t hoist in the same way. They’re available only after their definition. 🤦

🔎 Key Difference: Function Declarations are hoisted , but Function Expressions aren’t.

🏆 Final Verdict

  • Use Function Declarations when you need a function globally.

  • Use Function Expressions when you need a function conditionally or inside another function.

So, who wins? Well… it depends! Which one do you prefer? Lemme know…

Thanks for reading, thanks for your time <3