π§ JavaScript Functions & Scope
π οΈ Functions in JavaScript β The Real MVP
A function is like your favorite shortcut: build it once, and reuse it anytime you want. Instead of copy-pasting the same code everywhere (ugh, no thanks), you just call the function and boom β it handles the rest.
π¦ 1. Function Declaration β The OG
This is the classic way of writing a function:
function greet(name) {
console.log("Hello, " + name + "!");
}
greet("Alice");
π Fun fact: You can actually call this function before itβs even written in your code. Why? Because it gets hoisted to the top behind the scenes. Kinda magic.
π§Ύ 2. Function Expression β The Chill Alternative
Here, you treat the function like a regular value and store it in a variable:
const greet = function(name) {
console.log("Hi, " + name + "!");
};
greet("Bob");
β‘ 3. Arrow Function β Clean, Modern, and Snappy
For those who love clean code and minimal vibes:
const greet = (name) => {
console.log("Hey, " + name + "!");
};
greet("Charlie");
π¨ Heads-up: Arrow functions are slick, but they donβt have their own this
. So if youβre working inside objects or classes, make sure thatβs what you actually want.
π Scope in JavaScript β Who Sees What?
Scope is all about visibility β which parts of your code can see or use a variable. It depends on where you declare it.
π Global Scope β The Open World
Declare a variable outside any function, and itβs accessible from pretty much anywhere:
let color = "blue";
function showColor() {
console.log(color); // Totally works
}
π Local Scope β The Private Zone
Put a variable inside a function, and it stays in its own little world:
function greet() {
let message = "Hello!";
console.log(message); // Works just fine
}
console.log(message); // β Nope, doesn't exist out here
π§Ό Pro Tip: Stick with local variables when you can β it keeps things clean and avoids surprise bugs.
β TL;DR β Just the Gist
- Function Declaration β The OG style. Hoisted.
- Function Expression β Stored in a variable. Not hoisted.
- Arrow Function β Short and sweet. No
this
binding. - Global Scope β Visible everywhere.
- Local Scope β Only visible where itβs defined.