JavaScript Functions & Scope

Himmat Kumar Jun 1, 2025, 6:37 AM
Blog Thumbnail

🧠 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.

Related Posts

Himmat Kumar β€’ Jun 1, 2025, 1:07 AM

Introduction JavaScript

Himmat Kumar β€’ Jun 1, 2025, 1:07 AM

JavaScript Variables: var vs let vs const

Himmat Kumar β€’ Jun 1, 2025, 1:07 AM

JavaScript Data Types Explained with Examples

Himmat Kumar β€’ Jun 1, 2025, 1:07 AM

JavaScript Loops β€” for, while, do...while

Himmat Kumar β€’ Jun 1, 2025, 1:07 AM

Date and Time in JavaScript β€” Easy Guide

112 viewsLaravel
Himmat Kumar β€’ Jun 1, 2025, 12:53 AM

Master Laravel: Basic System Requirement,Installation a...