YouTip LogoYouTip

JavaScript Functions and Scope

Functions

function greet(name) {
    return `Hello, ${name}!`;
}

const add = (a, b) => a + b;

function power(base, exp = 2) {
    return base ** exp;
}

Scope

let global = "visible everywhere";

function test() {
    let local = "visible only here";
    if (true) {
        let block = "visible only in if";
    }
}

Closures

function counter() {
    let count = 0;
    return () => ++count;
}
const c = counter();
c(); // 1
c(); // 2

Summary

  • Arrow functions provide concise syntax
  • let/const are block-scoped
  • Closures remember their outer scope
← JavaScript Arrays and ObjectsJavaScript Variables and Data β†’