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
| Term | Definition | Example |
|---|---|---|
| Parameter | Placeholder in the function definition | function greet(name) |
| Argument | Actual value passed at call time | greet("Altamash") |
| Default Parameter | Fallback if no argument provided | (name = "Guest") => ... |
Return Values
| Rule | Explanation |
|---|---|
return value; | Immediately stops the function and sends value back |
| No return | Function returns undefined |
| Newline after return | ASI inserts ; — returns undefined instead of your value! |
| Arrow implicit return | (x) => x * 2 — no {} means auto-return |
Scope
| Scope | Where Declared | Who Can Access |
|---|---|---|
| Global | Outside any function | Everyone |
| Local / Function | Inside a function | Only 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
| Event | Fires When | Typical Element |
|---|---|---|
"click" | User clicks | Buttons, 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 pressed | Any element / document |
"mouseenter" | Mouse enters element | Any element |
"mouseleave" | Mouse leaves element | Any element |
The Event Object (e)
| Property / Method | Returns |
|---|---|
e.type | Event type string ("click") |
e.target | The element that fired the event |
e.target.value | Current value of an input element |
e.key | Which key was pressed ("Enter") |
e.preventDefault() | Stops browser default behavior |
e.clientX / e.clientY | Mouse 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;
});