0% found this document useful (0 votes)
2 views

javascriptlesson6

This document covers JavaScript functions and scope, explaining that functions are reusable blocks of code. It details global and local scope, along with block scope for variables declared with let and const. Additionally, it introduces closures and Immediately Invoked Function Expressions (IIFE) for managing variable accessibility and creating temporary scopes.

Uploaded by

vanguyen103
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

javascriptlesson6

This document covers JavaScript functions and scope, explaining that functions are reusable blocks of code. It details global and local scope, along with block scope for variables declared with let and const. Additionally, it introduces closures and Immediately Invoked Function Expressions (IIFE) for managing variable accessibility and creating temporary scopes.

Uploaded by

vanguyen103
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 7

JavaScript Lesson 6: Functions and Scope

Page 1: Introduction to Functions

 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:

Page 4: Block Scope with let and const

 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.

 const is used for variables that should not be reassigned.

Example:
Practical Use of Closures:

 Closures are useful when you want to create private variables that can only be accessed by
specific functions.

Example:

Immediately Invoked Function Expressions (IIFE):

 An IIFE is a function that runs immediately after it’s defined. This is useful for creating temporary
scopes.

Example:

You might also like