Defining and Calling Functions
Defining and Calling Functions in JavaScript
Functions are the primary building blocks of software. A function is a reusable, modular block of code designed to perform a specific task. By packaging code into functions, you avoid repeating logic (DRY: Don't Repeat Yourself) and create clean, testable programs.
1. Function Declarations vs. Function Expressions
In JavaScript, there are two traditional ways to define functions:
A. Function Declaration
Uses the function keyword followed by the function name:
B. Function Expression
Assigns an anonymous (or named) function to a variable:
2. Hoisting Differences (Crucial Interview Concept!)
Why does the choice between Declaration and Expression matter? Hoisting!
Function Declarations are Hoisted Completely:
You can call a function declaration before the line where it is written:
Function Expressions are NOT Hoisted:
Because the function is assigned to a const or let variable, it resides in the Temporal Dead Zone until initialized:
3. Function Execution & The Call Stack
When a function is called in JavaScript:
- 1A new Execution Context is created.
- 2The function is pushed onto the top of the Call Stack.
- 3Its code executes.
- 4When it hits
returnor ends, it is popped off the Call Stack, and control returns to the caller.
4. Functions as First-Class Citizens
In JavaScript, functions are First-Class Citizens, which means functions are treated like any other value:
- They can be assigned to variables.
- They can be stored in arrays and objects.
- They can be passed as arguments to other functions (Callbacks).
- They can be returned from other functions (Higher-Order Functions).
Practice Quiz
const before its declaration?init?Function Parameters and Return Values
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
Related Lessons
| Previous Lesson | Next Lesson |
|---|---|
| Template Literals (Basics) | Function Parameters and Return Values |
Practice Quiz
Test your understanding of this lesson with 5 questions. Each question has one correct answer.