Module 23: Functions and Scope
Functions are values
🏠The everyday picture
A recipe card can be stored in a box, handed to a friend, or pinned to the wall. The card itself is a thing you can pass around, separate from actually cooking it.
📘What it really is
- In JavaScript, a function is a value, just like a number or an object. It can be:
- stored in a variable:
const double = function (n) { return n * 2; };; - kept in an array or object:
const tools = { double, triple };; - passed into another function (Lesson 3);
-
returned from another function (Lesson 4).
-
doubleis the function itself;double(4)calls it and gives8. Forgetting the brackets, or adding them where they don't belong, is a very common mistake. -
Function declarations (
function double(n) {...}) can be used before the line where they're written; functions stored in variables can't. Either style is fine; be consistent. -
A function that takes or returns other functions is called a higher-order function.
map,filterandsortare examples you already use.
🖱️Try it
Create calc.js. Write functions addGst(price) (adds 18%) and addDelivery(price) (adds ₹40). Store them in
an array steps, then loop over the array, applying each step to a starting price of ₹500 in turn. Print the
result after each step.
✅Quick check
What's the difference between addGst and addGst(100)?
Show the answer
addGst is the function itself; addGst(100) runs it and gives the result.
Name a higher-order function you already use.
Show the answer
map, filter, reduce, sort or addEventListener: each takes a function as an argument.
