JavaScript Fundamentals

Functions and Scope

Understanding Functions and Scope

Functions are one of the fundamental building blocks in JavaScript. They allow you to write reusable code and create powerful abstractions. Understanding scope is crucial for managing variable accessibility and creating maintainable code.

Function Types

// Function Declarations
function greet(name) {
  return "Hello, " + name + "!";
}

// Function Expression
const add = function(a, b) {
  return a + b;
};

// Arrow Function
const multiply = (a, b) => a * b;

// Default Parameters
const greetUser = (name = "Guest") => {
  return "Hello, " + name + "!";
};

Variable Scope

// Global Scope
let globalVar = "I'm global";

function scopeExample() {
  // Function Scope
  let functionVar = "I'm function-scoped";
  
  if (true) {
    // Block Scope
    let blockVar = "I'm block-scoped";
    var varVariable = "I'm function-scoped (var)";
    console.log(blockVar); // Works
  }
  
  console.log(functionVar); // Works
  console.log(varVariable); // Works
  // console.log(blockVar); // Error!
}

console.log(globalVar); // Works
// console.log(functionVar); // Error!

Closures

// Closures Example
function createCounter() {
  let count = 0;  // Private variable
  
  return {
    increment: () => {
      count++;
      return count;
    },
    decrement: () => {
      count--;
      return count;
    },
    getCount: () => count
  };
}

const counter = createCounter();
counter.increment(); // 1
counter.increment(); // 2
counter.decrement(); // 1