JavaScript Functions ๐¶
Mentor's Note: A function is a "Recipe." You write it once, and then you can cook that dish (run that code) whenever you're hungry, just by calling its name! ๐ก
๐ The Scenario: The Coffee Recipe โ¶
Imagine you have a specific way you like your coffee.
- The Logic:
- Ingredients (Parameters): 1 spoon Coffee, 2 spoons Sugar. ๐ฆ
- The Process (Body): Mix with hot water, stir well. โ๏ธ
- The Result (Return): A hot cup of coffee. โ
- The Result: Instead of explaining the process every morning, you just tell your assistant: "Make Coffee." โ
๐ Concept Explanation¶
1. Function Declaration¶
You define a function with the function keyword.
2. Parameters vs. Arguments¶
- Parameters: The "Placeholders" in the definition (
name). - Arguments: The "Real Data" you pass when calling (
"Vishnu").
3. Function Scope (The "Private Room") ๐งฑ¶
Variables created inside a function are Local. They cannot be seen or used by the rest of the world outside that function.
๐จ Visual Logic: The Function Machine¶
graph LR
A[Input: 5, 10 ๐ฅ] --> B[Function: Addition Machine โ๏ธ]
B --> C[Output: 15 ๐ค]
๐ป Implementation: The Function Lab¶
๐ Sample Dry Run¶
| Step | Action | price |
discount |
Result |
|---|---|---|---|---|
| 1 | Call calculate(100, 10) |
100 |
10 |
Waiting... |
| 2 | Calculate 100 - 10 |
-- | -- | 90 |
| 3 | return 90 |
-- | -- | 90 sent back! โ |
๐ Technical Analysis¶
- Hoisting: Function declarations are moved to the top by the browser. You can call a function before you define it! (But don't do this, it's messy). โฑ๏ธ
๐ฏ Practice Lab ๐งช¶
Task: The Area Master
Task: Write a function getArea(length, width) that returns the area of a rectangle.
Bonus: Try writing it as an Arrow Function.
Hint: length * width. ๐ก
๐ก Interview Tip ๐¶
"Interviewers love asking about Anonymous Functions. These are functions without a name, often used as callbacks (e.g.,
button.onclick = function() { ... })!"
๐ก Pro Tip: "Computers are good at following instructions, but not at reading your mind. Be precise with your functions!" - Donald Knuth