Reference Document

Functions & Events

Quick reference for Lesson 10. Print this and pin it next to your monitor.

Three Ways to Create Functions

1. Function Declaration (hoisted)

function add(a, b) {
  return a + b;
}

2. Function Expression (not hoisted)

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

3. Arrow Function ⭐ (not hoisted, preferred)

// Full
const add = (a, b) => { return a + b; };

// Implicit return (single expression)
const add = (a, b) => a + b;

// Single parameter — no parens needed
const double = n => n * 2;

// No parameters — empty parens required
const getRandom = () => Math.random();

Parameters & Arguments

TermDefinitionExample
ParameterPlaceholder in the function definitionfunction greet(name)
ArgumentActual value passed at call timegreet("Altamash")
Default ParameterFallback if no argument provided(name = "Guest") => ...

Return Values

RuleExplanation
return value;Immediately stops the function and sends value back
No returnFunction returns undefined
Newline after returnASI inserts ; — returns undefined instead of your value!
Arrow implicit return(x) => x * 2 — no {} means auto-return

Scope

ScopeWhere DeclaredWho Can Access
GlobalOutside any functionEveryone
Local / FunctionInside a functionOnly that function
Block (let/const)Inside { }Only that block

Rule: Functions can see OUT, but the outside cannot see IN.

addEventListener Syntax

Pattern

element.addEventListener("eventType", handlerFunction);

✅ Correct: btn.addEventListener("click", handleClick);

❌ Wrong: btn.addEventListener("click", handleClick()); — calls immediately!

Common Event Types

EventFires WhenTypical Element
"click"User clicksButtons, links, any element
"input"Input value changes (live)<input>, <textarea>
"change"Input loses focus after change<select>, <input>
"submit"Form is submitted<form>
"keydown"Key is pressedAny element / document
"mouseenter"Mouse enters elementAny element
"mouseleave"Mouse leaves elementAny element

The Event Object (e)

Property / MethodReturns
e.typeEvent type string ("click")
e.targetThe element that fired the event
e.target.valueCurrent value of an input element
e.keyWhich key was pressed ("Enter")
e.preventDefault()Stops browser default behavior
e.clientX / e.clientYMouse coordinates

Critical Patterns

Form Submit Pattern (used in every framework)

form.addEventListener("submit", (e) => {
  e.preventDefault();              // Stop page reload
  const value = input.value.trim(); // Read + clean input
  if (value === "") return;         // Validate
  // ... do something with value
});

Live Input Preview Pattern

input.addEventListener("input", (e) => {
  preview.textContent = e.target.value;
});