📕
SEIRFX
  • Introduction
  • About These Notes
  • Schedule
  • Unit 2
    • Node
      • Internet Fundamentals
      • Full-Stack Fundamentals
      • Intro to Node
      • Node Modules
      • Node Packages
    • Express
      • Intro to Express
      • Routes
      • Routes Lab
      • Views
      • Templates
      • Layouts & Controllers
    • CRUD & REST
      • GET & POST
      • GET & POST Lab
      • PUT & DELETE
    • API Calls in Express
      • Axios
      • Request (no longer maintained)
    • Sequelize
      • Terminology
      • Setup
      • Using Models
      • Seeding Data
      • Validations and Migrations
      • Resources
      • 1:M Relationships
      • N:M Relationships
    • Express Authentication
      • Research Components
      • Code Components
      • Auth in Theory
        • Sessions
        • Passwords
        • Middleware
        • Hooks
      • Auth in Practice
        • Create the User
        • User Signup
        • Sessions
        • User Login
        • Authorization and Flash messages
  • Development Workflow
    • Command Line
      • The Terminal
      • Filesystem Navigation
      • File Manipulation
      • Additional Topics
    • Intro to Git
      • Version Control
      • Local Git
      • Remote Git
      • Git Recipes
    • Group Collaboration
      • Git Workflows
      • Project Roles and Tools
    • VS Code Tips & Tricks
  • HTML/CSS
    • HTML
    • CSS Selectors
    • CSS Box Model and Positioning
      • Box Model
      • Display and Positioning
      • Flexbox
      • Grid
      • Flexbox & Grid Games
      • Floats and Clears
      • Additional Topics
    • Advanced CSS
      • Responsive Design
      • Pseudo-Classes/Elements
      • Vendor Prefixes
      • Custom Properties
      • Additional Topics
    • Bootstrap
    • CSS Frameworks
    • Accessibility
  • JavaScript
    • Primitives
    • Arrays
    • Objects
      • Objects Lesson
      • Objects quick guide
      • Object-ception
    • Control Flow
      • Boolean Expressions
      • Conditionals
      • Loops
      • Promises
    • Functions
      • Scope
      • Callbacks
      • Higher Order Functions
      • Callbacks Review Lab
      • Timing Functions
      • Iterators
      • Combining Data Types
      • Combining Data Types Lab
    • Javascript in the browser
      • DOM and Events
      • DOM Manipulation
      • DOM Review
      • DOM Review Lab
      • HP DOM Lab
      • Programmatic DOM Manipulation
      • Grids & Pyramids
      • DOM & Data
      • DOM Events
      • Color Palette Picker
      • Sketchpad
    • HTML5 Canvas
    • How To Reduce Redundancy
    • OOP
      • Westworld Lab
      • OOP Factories
      • OOP Inheritance
      • OOP Inheritance Lab
      • Tomagotchi Lab
      • OOP Space Battle
      • OOP Snowman
      • (2019) JavaScript OOP
      • (2016) OOP with Classes
      • (1995) OOP with Prototypes
      • Constructors
      • Prototypes
    • Intro to TDD
    • Scoping
    • Inheritance
      • Prototypal Inheritance
      • Call, Apply, and other Functions
      • ES6 Inheritance
      • Resources
    • Custom Node Modules
    • Additional Topics
      • AJAX, Fetch, and Async/Await
      • AJAX w/JSON and Localstorage
        • AJAX w/JSON
        • Local Storage
      • Async module
      • Data Scraping
  • jQuery
    • Intro
      • DOM Manipulation
      • Reddit Practice
      • Styling
      • Events
    • Plugins
    • AJAX
  • APIs
    • Fetch
    • AJAX w/jQuery
    • AJAX w/Fetch
  • Databases
    • Intro to SQL
    • Advanced SQL
    • MongoDB
      • Intro to NoSQL
      • CRUD in MongoDB
      • Data Modeling
      • Intermediate Mongo
  • Left over Node/Express
    • Testing with Mocha and Chai
    • Mongoose
      • Mongoose Associations
    • JSON Web Tokens
      • Codealong
    • Additional Topics
      • oAuth
      • Geocoding with Mapbox
      • Geocoding and Google Maps
      • Cloudinary
      • Websockets with Socket.io
      • SASS
  • Ruby
    • Intro to Ruby
    • Ruby Exercises
    • Ruby Classes
    • Ruby Testing with Rspec
    • Ruby Inheritance
    • Ruby Data Scraping
  • Ruby on Rails
    • Intro to Rails
    • APIs with Rails
    • Asset Pipeline
    • Rails Auth and 1-M
      • Auth Components
    • Rails N:M
    • ActiveRecord Polymorphism
    • Additional Topics
      • oAuth
      • SASS
      • Rails Mailers
      • Cloudinary
      • Jekyll
  • React (Updated 2019)
    • ES6+/ESNext
      • Const and Let
      • Arrow Functions
      • Object Literals and String Interpolation
      • ES6 Recap
      • ES6 Activity
    • Intro to React
      • Create React App
      • Components and JSX
      • Virtual DOM
      • Props
      • Dino Blog Activity
      • Nested Components
      • Lab: LotR
    • React State
      • Code-Along: Edit Dino Blog
      • Lab: Simple Calc
      • Lifting State
    • React Router
      • Browser History/SPAs
      • React Router (lesson and full codealong)
      • Router Lab
    • Fetch and APIs
      • APIs with Fetch and Axios
      • Fetch the Weather
    • React Hooks
    • React LifeCycle
      • Lab: Component LifeCycle
    • React Deployment
    • Additional Topics
      • React Frameworks
        • Material UI Theming
      • Typescript
        • More Types and Syntax
        • Tsconfig and Declaration Files
        • Generics with Linked List
      • Redux
      • TypeScript
      • Context API
      • React Native
  • Meteor
  • Deployment and Config
    • Installfest
      • Mac OSX
      • Linux
      • Git Configuration
      • Sublime Packages
    • Deploy - Github Pages
    • Deploy - Node/Sequelize
    • Deploy - Node/MongoDB
    • Deploy React
    • Deploy - Rails
      • Foreman (Environment Variables)
    • Deploy - AWS Elastic Beanstalk
    • Deploy - S3 Static Sites
    • Deploy - Django
    • Deploy - Flask
  • Data Structures and Algorithms
    • Recursion
    • Problem Solving - Array Flatten
    • Binary Search
    • Algorithm Complexity
    • Stacks and Queues
    • Bracket Matching
    • Ruby Linked Lists
      • Sample Code
      • Beginner Exercises
      • Advanced Exercises
    • JS Linked Lists
      • Sample Code
      • Beginner Exercises
      • Beginner Solutions
    • Hash Tables
    • Intro to Sorting
    • Insertion Sort
    • Bucket Sort
    • Bubble Sort
    • Merge Sort
    • Quick Sort
    • Heap Sort
    • Sorting Wrapup
    • Hashmaps
    • Trees and Other Topics
  • Python
    • Python Installation
    • Intro to Python
    • Python Lists
    • Python Loops
    • Python Dictionaries
    • Python Sets and Tuples
    • Python Cheatsheet
    • Python Functions
    • Python Classes
    • Python Class Inheritance
    • Intro to Flask
    • Intro to SQLAlchemy
      • Flask and SQLAlchemy
    • Using PyMongo
    • Intro to Django
    • CatCollector CodeAlong
      • URLs, Views, Templates
      • Models, Migrations
      • Model Form CRUD
      • One-to-Many Relations
      • Many-to-Many Relations
      • Django Auth
    • Django Cheatsheet
    • Django Auth
    • Django Polls App Tutorial
    • Django School Tool Tutorial
    • Django 1:M Relationships
    • Custom Admin Views
    • Data Structures and Algorithms
      • Recursion
      • Binary Search
      • Stacks and Queues
      • Linked Lists
      • Binary Trees
      • Bubble Sort
      • TensorFlow & Neural Networks
    • Adjacent Topics
      • Raspberry Pi
      • Scripting
  • Assorted Topics
    • History of Computer Science
    • Regular Expressions
    • Being Successful in SEI
    • Internet Fundamentals
      • Internet Lab
    • Adjacent Workflow
      • UX/UI
      • Wireframing Exercise: Build an Idea
      • Agile
    • Post SEI
      • Learning Resources
      • Deliverables -> Portfolio
      • FAQ
  • Projects
    • Project 1
    • Project 2
    • Project 3
      • Project 3 Pitch Guidelines
    • Project 4
    • Past Projects
      • Project 1
      • Project 2
      • Project 3
      • Project 4
      • Portfolios
    • Post Project 2
    • MEAN Hackathon
      • Part 1: APIs
      • Part 2: Angular
    • Portfolio
  • Web Development Trends
  • Resources
    • APIs and Data
    • Tech Websites
    • PostgreSQL Cheat Sheet
    • Sequelize Cheat Sheet
    • Database Administration
  • Archived Section
    • (Archived) ReactJS
      • Intro to React
        • Todo List Codealong
        • Additional Topics
      • Deploy React
      • React with Gulp and Browserify
        • Setting up Gulp
        • Additional Gulp Tasks
      • React Router
        • OMDB Router
        • OMDB Search
        • Additional Resources
      • React Animations
        • CSS Animations
    • AngularJS
      • Intro to AngularJS
        • Components and SPA
        • Create an Angular App
      • Angular Directives and Filters
      • Angular Animation
      • Angular Bootstrap Directives
        • Bootstrap Modals
      • Angular $http
      • Angular Services
        • Service Recipes
        • ngResource
        • Star Wars Codealong
      • Angular Routing
      • Angular + Express
      • Angular Authentication
        • Additional Topics
      • Angular Components
      • Angular Custom Filters
      • Angular Custom Directives
Powered by GitBook
On this page
  • SCOPE
  • Lesson objectives
  • Define Scope restriction
  • Differentiate between Local vs Global Scope
  • Describe how functions can call other functions
  • Use blocks within blocks
  • Block scope flow: outside in
  • Define recursion
  • Define pollution

Was this helpful?

  1. JavaScript
  2. Functions

Scope

SCOPE

Lesson objectives

After this lesson students will be able to:

  1. Define Scope restriction

  2. Differentiate between global and local scope

  3. Describe how functions can call other functions

  4. Use const and let for block-scoping

  5. Use block-scoping with loops

  6. Use block-scoping with conditionals

  7. Use blocks within blocks

  8. Define recursion

  9. Define pollution

Define Scope restriction

Scope is the restriction of where in your code your variables can be accessed. If you try to access a variable outside of its scope, it will not be defined.

In general, you want scope to be restricted. You only want your variables accessible to specific safe zones.

Example of scope restriction

A variable num is defined inside a function.

const exampleFunction = () => {
  const num = 100;
  console.log(num * num);
}

console.log(num);   // num is not available outside the function
exampleFunction();  // even if you run the function first . . .

console.log(num)    // the scope of num is restricted to the function

Differentiate between Local vs Global Scope

When variables are declared inside a function, they are scoped locally to that particular function.

Variables declared within a function are available within that function and to any sub-functions. The variables are not accessible outside of the function.

When variables are declared outside of any and all functions, the value of the variable is accessible to all other functions (and all functions within those functions), and are scoped globally.

  • Global scope is the the part of your code outside of any enclosing functions

  • Local scope is the parts of your code that are inside functions.

const item = 'spicy meatball';

const exampleFunction = () => {
    console.log(item + " within function");
}

exampleFunction();

=> spicy meatball

Everything is defined within a scope. The variable item is defined in the global scope and is available to all functions and sub-functions.

As a natural consequence of local scope, functions cannot access variables stored in sibling functions.

If we make another function:

const setItem = () => {
    const item = 'spicy meatball';
    return item;
}

const getItem = () => {
    return item;
}

console.log(getItem());

The item variable is not visible inside getItem, because it is scoped only to setItem.

Describe how functions can call other functions

Functions can call other functions that reside in an accessible scope. For example:

const returnName = () => {
  return "Matt"
}

const returnGreeting = () => {
  return "oh hai, " + returnName()
}
console.log(returnGreeting());

Since it is good practice for a function to do only one thing, we can have many functions perform different little tasks and call on each other. This is a good strategy for compartmentalizing functionality.

A function can take the return value of another function and put it to good use.

Question

If everything has a scope, our functions are declared in a scope. In which scope have we been declaring our functions? answer: global scope Let's build two interacting functions from the ground up, both will be defined in the global scope: ```javascript const firstName = () => { return 'Madeline'; }; const fullName = () => { return firstName() + " O'Moore"; }; console.log(fullName()); ``` ### extra problem * Write a function `checkSquare` that will return **true** if a number is a **perfect square** (Check if the square root is a whole number). Hint: use Math.sqrt() and (num % 1 == 0) * Write function `checkToLimit` that will loop up to an arbitrary limit brought in as a param (say, 100), and console log whether each number is a perfect square. Call upon the previously defined `checkSquare` function. ## Use `const` and `let` for block-scoping **`let`** and **`const`** will scope your variables to the **block** in which they are declared. Example -- make a block and declare a variable within: ```javascript { const item = 'spicy meatball'; } ``` `item` is available inside the block, but not available outside. This works: ```javascript { const item = 'spicy meatball'; console.log(item); } ``` > => "spicy meatball" This doesn't: ```javascript { const item = 'spicy meatball'; } console.log(item); ``` > ReferenceError: item is not defined **`var`** by contrast will leak out of a block. ```javascript { var item = 'spicy meatball'; } console.log(item); ``` > => "spicy meatball" This is not so great. In general, we want to control our scope as tightly as possible. If we don't, we can end up with variable collisions and accidental overwrites. This is why we stick with `let` and `const`. ## Use block-scoping with loops Using `let` within a for loop control panel scopes the variable to the block. ```javascript for (let i=0; i Inside the block: 1 > > Inside the block: 2 > > etc. > > Outside the block: Reference error: i is not defined ### Activity (6 mins) - Write a for loop but use **var** instead of **let**. Verify: is the variable accessible outside the loop after it has run? Verify: is the variable accessible outside of the loop with **let**? Verify: What about a **let** variable defined within the block of the loop? ## Use block-scoping with conditionals Using `let` or `const` within conditional blocks will scope to the block (no surprises there). ```javascript if (true) { const num = 100; console.log(num); } ``` > => 100 ```javascript if (true) { const num = 100; } console.log(num); ``` > => Reference error: num is not defined Knowing what we know about block scope, can we write code like this? ```javascript const age = 21; let message = ''; if (ageAnswer ``` => You can buy the beer ```

Use blocks within blocks

Following the same logic, can we access variables in a block that have been declared in an outside block? Try running this code and see what you find.

const words = 'that\'s a...';
{
    const item = 'spicy meatball';
    const start = 'mama mia!'
    {
        console.log(start);
        console.log(words);
        console.log(item);
    }
}

Answer ``` => mama mia! => that's a ... => spicy meatball ```

Block scope flow: outside in

We know if we declare a variable inside a block that it is not accessible at the global level.

If we declare a variable at the global level, is it accessible inside a block?

const words = 'that\'s a...';
{
    const item = 'spicy meatball';
    console.log(words);
    console.log(item);
}

Answer ``` => that's a... => spicy meatball ```

Define recursion

A function has access to itself because it is always declared in a scope accessible to itself.

When a function invokes itself, this is called recursion.

const func = () => {
    return func();
}

This will create a loop. This particular loop is infinite because it has no exit condition. (don't try this at home)

This function has an exit condition and can safely call itself:

const countdown = (num) => {
    if(num != 0){
        console.log(num);
        countdown(num - 1 );
    } else {
        return
    }
}

Take the next 5 minutes and try this on your own.See if you can figure out how it works.

When you figure it out, try writing up an explanation and pasting it into the slack channel!

Define pollution

You do not want your global scope to be polluted. This means, try not to add too many variables to the global namespace. There are a few reasons for not polluting your global scope.

  • Global variables can be overwritten or misconstrued elsewhere

  • Potentially causing unwanted, hard to track bugs

  • Namespace

  • Memory / garbage collection

You can learn more about what this all means from the great answers on stackoverflow below.

PreviousFunctionsNextCallbacks

Last updated 4 years ago

Was this helpful?

More on Garbage Collection

This lesson has been adapted from

http://stackoverflow.com/questions/8862665/what-does-it-mean-global-namespace-would-be-polluted
https://dzone.com/articles/memory-management-and-garbage-collection-in-javasc
SEIR-MAE