javascriptlesson6
javascriptlesson6
What is a Function?
o A function is a block of code designed to perform a particular task. Functions are useful
because they allow you to reuse code and organize it into logical sections.
Example:
Page 3: Scope in JavaScript
What is Scope?
o Scope refers to the accessibility of variables and functions in different parts of your code.
JavaScript has two types of scope:
Global Scope: Variables declared outside any function are in the global scope
and can be accessed from anywhere.
Local Scope: Variables declared inside a function are in local scope and can only
be accessed within that function.
Example:
Block Scope:
o Variables declared with let and const are block-scoped, meaning they are only accessible
within the block they are defined in (like inside {} brackets).
Example:
Difference Between var, let, and const:
var is function-scoped, meaning it is accessible throughout the function it’s declared in.
let and const are block-scoped and cannot be accessed outside the block they’re declared in.
Example:
Practical Use of Closures:
Closures are useful when you want to create private variables that can only be accessed by
specific functions.
Example:
An IIFE is a function that runs immediately after it’s defined. This is useful for creating temporary
scopes.
Example: