Why functions?#
A function is a named, reusable block of code. Write it once, use it many times - and give a meaningful name to a piece of logic (calculateFees, isValidEmail).
Declaring and calling#
Namaste, Asha! Namaste, Ravi! Room area: 120 sq ft Two rooms: 200
Parameter function की परिभाषा में लिखा नाम है (name), और argument वह असली value है जो call करते समय भेजते हैं ("Asha")। return function से जवाब वापस भेजता है और function वहीं रुक जाता है।
Default parameters#
5000 4500
Function expressions and arrow functions#
Functions are values - you can store them in variables.
16 27 7
Hi!
{ name: 'Neha', active: true }| Form | Example |
|---|---|
| declaration | function add(a, b) { return a + b; } |
| expression | const add = function (a, b) { return a + b; }; |
| arrow (one expression) | const add = (a, b) => a + b; |
| arrow (block body) | const add = (a, b) => { const s = a + b; return s; }; |
With a block body { } you must write return. (a, b) => { a + b } returns undefined!
Scope#
Keep variables as local as possible. Fewer globals means fewer accidental clashes.
Callbacks and higher-order functions#
A higher-order function takes a function as an argument (or returns one). The function you pass is a callback.
Reminder 1 Reminder 2 Reminder 3 21 setTimeout doesn't block - this prints first This prints after 0.5 seconds
makeMultiplier shows a closure: the returned function remembers k even after makeMultiplier has finished.
Recursion#
A function can call itself. It needs a base case to stop.
120
Summary#
- Functions bundle reusable logic;
returnsends a value back (otherwiseundefined). - Default parameters:
function f(x, y = 10). - Arrow functions:
(a, b) => a + b; use{ }+returnfor longer bodies. let/constare block-scoped; closures remember outer variables.- Callbacks are functions passed to other functions - the heart of events, timers and array methods.