Lesson 4.3: Functions & Scope
Functions in JavaScript
A function is a block of code designed to perform a specific task. Functions help in reusing code and keeping it organized.
1. Types of Functions
a) Function Declaration
b) Function Expression
-
A function can be assigned to a variable.
c) Arrow Function (ES6)
2. Function Parameters and Return
-
Functions can accept inputs (parameters) and return outputs.
3. Scope in JavaScript
Scope determines the accessibility of variables.
a) Global Scope
-
Variables declared outside a function are global and accessible anywhere.
b) Local Scope
-
Variables declared inside a function are local and cannot be accessed outside.
c) Block Scope
-
letandconstare block-scoped (inside{ }). -
varis function-scoped, not block-scoped.
4. Benefits of Functions
-
Reusability of code
-
Makes code organized and readable
-
Helps in maintaining DRY principle (Don’t Repeat Yourself)
✅ Summary:
-
Functions are reusable code blocks (
declaration,expression,arrow). -
Functions can accept parameters and return values.
-
Scope controls variable accessibility:
global,local,block.
