👨🏿‍💻
Learn
  • Learn And The Power Of Community
  • Intro
    • learn-co-curriculum/welcome-to-learn-verified
    • learn-co-curriculum/your-first-lab
    • learn-co-curriculum/environment-setup
  • Intro to tic tac toe
    • matz-readme
    • what-is-a-program?
    • hello world
    • Intro to irb
    • Reading-error-messages
    • Data-types
    • variable
    • Variable-assignment lab
    • String interpolation
    • Interpolation-super-power
    • Welcome to tic tac toe
    • Array
    • Tic tac toe board
    • Intro to methods
    • Puts print and return
    • Intro-to-tdd-rspec-and-learn
    • Methods and arguments
    • Say hello (lab)
    • Methods-default-arguments
    • ttt-3-display_board-example
    • ttt-4-display-board-rb
    • Intro-to-cli-applications
    • Greeting-cli
    • cli-applications in Ruby
    • Ruby-gets-input
    • Tic tac toe move
    • Truthiness-in-ruby-readme
    • booleans
    • conditional (if)
    • ttt-6-position-taken
    • ttt-7-valid-move
    • rspec-fizzbuzz
    • Looping-introduction
    • Loop
    • while-and-until-loop
    • Tic Tac Toe Turn lab
    • looping-while-until lab
    • Tic Tac Toe Play Loop (lab)
    • Tic Tac Toe Current Player (lab)
    • Intro to ruby iterators
    • Nested Arrays
    • Boolean Enumerators
    • Search Enumerators
    • Tic Tac Toe Game Status
    • tic-tac-toe
  • OOP tic tac toe
    • intro to oop
    • Intro-to-classes-and-instances
    • Classes-and-instances-lab
    • Instance-methods
    • Instance-methods-lab
    • Object Attributes
    • object-attributes-lab
    • Object Initialization
    • Object-initialize-lab
    • oop barking dog lab
    • Procedural-vs-oop
    • oop tic tac toe
  • Git and github
    • Intro to Version Control
    • Git Repository Basics
    • Git-basics-quiz
    • Forks-and-clones
    • Git Remotes and Github
    • Git Remotes and Github Codealong
    • Thinking Ahead: GitHub as Career Differentiator
    • Github Pull Requests
    • Git Collaboration
    • Git-collaboration-quiz
    • Git Basics Quiz
  • HTML
    • A-quick-tour-of-the-web
    • The-web-is-made-of-strings
    • What-makes-the-web-possible?
    • html-introduction
    • Your first-html-tag-lab
    • Nested-tags-and-attributes
    • Well-formed-html-document-lab
    • HTML elements types overview
    • Researching-HTML-elements
    • Separation-of-content-and-presentation
  • CSS
    • Introduction-to-css
    • introduction-to-css-code-along
  • Procedural Ruby
    • Regex-what-is-a-pattern
    • Regex-basics
    • Regex-lab
    • Regex-match-scan-grep-methods
    • learn-co-curriculum/method-arguments-lab
    • Method-scope
    • Return Values Lab
    • Debugging-with-pry
    • Method-scope-lab
    • Truthiness-code-challenge
    • If Statements Lab
    • Case-statements
    • Case-statements-quiz
    • Logic and Conditionals Quiz
    • Ternary Operators and Statement Modifiers lab
    • Looping Lab
    • looping-quiz
    • learn-co-curriculum/looping-times
    • countdown-to-midnight lab
    • Array introduction
    • Using Arrays
    • Array-CRUD-lab
    • Array-methods
    • Array-methods-lab
    • Square array lab
    • Collect and Return Values
    • Collect Lab
    • Badges and Schedules Lab
    • Oxford comma lab
    • Deli counter lab
    • Reverse Each Word Lab
    • Yield-and-blocks
    • Each Lab
    • Return from Yield Statements
    • My All? Lab
    • My Find Lab
    • Cartoon Collections Lab
    • Enumerators Code Challenge
    • Prime? Lab
    • Sorting
    • Sorting Lab
    • Introduction to Hashes
    • Using Hashes lab
    • Ruby-symbols
    • Hash iteration
    • Hash Iteration Lab
    • Hash Iteration with Collect
    • Intro to Nested Hashes
    • Building Nested Hashes
    • Building Nested Hashes Lab
    • Nested Hash Iteration
    • Nested Hashes Lab
    • Multitype Collections Lab
    • Iterating over Nested Hashes Codealong
    • Other Hashes Codealong
    • Hashes Manipulation Lab
  • OOP Ruby
    • OO Ruby Video: Object Orientation Overview
    • Object Accessors
    • Instance Variables lab
    • Video Review: Object Properties
    • Meowing Cat
    • Intro to Object Orientation - Ruby
    • oo basics lab
    • OO Basics with Class Constants
    • Self
    • OO School Domain lab
    • OO Counting Sentences lab
    • Class Variables and Methods
    • Class Variables and Methods Lab
    • Remembering Objects
    • Puppy Lab
    • Advanced Class Methods
    • Advanced Class Methods Lab
    • Video Review: Object Models
    • OO Email Parser lab
    • OO Anagram Detector lab
    • OO Cash Register lab
    • Intro to Object Relationships
    • Belongs to Object Lab
    • Has Many Object
    • Has Many Object Lab
    • Collaborating Objects Review
    • Collaborating Objects Lab
    • OO My Pets
    • oo kickstarter lab
    • OO Banking lab
    • Has Many Objects Through
    • Has Many Objects Through Lab
    • Intro to Inheritance
    • Intro to Inheritance Lab
    • Super
    • Super Lab
    • Intro to Modules
    • Intro to Modules Lab
    • Mass Assignment
    • Mass Assignment and Metaprogramming
    • Mass Assignment Lab
    • Custom Errors lab
    • OO Triangle lab
  • Scraping and project
    • Gems and Bundler
    • Scraping
    • Scraping Lab
    • Kickstarter Scraping Lab
    • Video Review: Object Orientation and Scraping
    • OO Ruby Object Orientation Video Review
    • Music Library CLI
    • Video Review: Music Library CLI
    • Tic-tac-toe with AI project
    • Student Scraper
    • CLI Data Gem Portfolio Project
    • CLI Data Gem Walkthrough
    • CLI Data Gem Walkthrough: Creating a CLI Scraper Gem
    • Common Anti-Patterns in CLI Data Gem
    • Student Example 1: Refactoring CLI Gem
    • Student Example 2: Refactoring CLI Gem
  • SQL
    • What is SQL
    • SQL Intro and Installation
    • SQL Database Basics
    • SQL Databases and Text Editors
    • SQL Data Types
    • SQL Inserting, Updating, and Selecting
    • Basic SQL Queries
    • SQL Aggregate Functions
    • SQL Aggregate Functions Lab
    • SQL Bear Organizer Lab
    • Edgar Codd and Table Relations
    • Table Relations
    • SQL JOINS
    • SQL Complex Joins
    • SQL Join Tables
    • Grouping and Sorting Data
    • SQL Joins Review Lectures
    • SQL Crowdfunding Lab
    • SQL Library Lab
    • Pokemon Scraper Lab
  • ORM And Active record
    • Why an ORM is Useful
    • Mapping Ruby Classes to Database Tables
    • Mapping Classes to Tables Lab
    • Mapping Database Tables to Ruby Objects
    • Mapping Database Rows to Objects Lab
    • Updating Records in an ORM
    • Updating Records in an ORM Lab
    • Preventing Record Duplication
    • ORMs Lab: Bringing It All Together lab
    • Dynamic ORMs
    • Dynamic ORMs with Inheritance
    • ActiveRecord Mechanics
    • Translating from ORM to ActiveRecord
    • Intro to Rake
    • Mechanics of Migrations
    • Writing Our Own Migrations
    • Migrations and Active Record Lab
    • ActiveRecord CRUD Lab
    • Advanced Finding Lab
    • ActiveRecord Associations
    • ActiveRecord Associations Lab
    • ActiveRecord Associations Lab II
    • ActiveRecord Associations Video Review
    • ActiveRecord Associations Video Review II
    • Video Review: Aliasing ActiveRecord Associations
    • Video Review: Blog CLI with ActiveRecord and Associations
  • Rack
    • How the Internet Works
    • Increasing Layers of Abstraction
    • Inspecting the Web with Rack (lab)
    • The HTTP Request
    • Dynamic URL Routes
    • Dynamic Web Apps with Rack (lab)
    • Rack Responses Lab
    • Rack Routes and GET Params Lab
    • HTTP Status Codes
    • Dynamic URLs and Status Codes Lab
    • Video Review: How The Web Works, Pt 1
    • Video Review: How the Web Works, Pt 2
  • Html
    • How the Web Works
    • Site Planning
    • HTML Fundamentals
    • HTTP Status Codes
    • video review how the web works pt 1
    • How the Web Works, Part 2: Overview
    • Setting Up a New Site
    • Document Structure
    • Text Formatting
    • HTML Tables
    • Html-images
    • HTML Links
    • Html backing-up changes
    • HTML Validation
    • Quiz - HTML Fundamentals
    • Dev Tools Super Power
    • HTML Lists
    • Html issue bot 9000 (lab)
    • HTML Forms and Iframes
    • HTML Map and Contact Form Code-along
    • HTML5 Media
    • HTML5 Video Embed Code-Along
    • HTML5 Semantic Elements
    • HTML5 Semantic Containers Code-along
    • HTML5 Quiz
  • CSS
    • CSS Fundamentals
    • CSS Styling Code Along
    • My Little Rainbow
    • CSS Kitten Wheelbarrow
    • CSS Graffiti Override Lab
    • CSS Issue Bot 9000
    • Your first deployment
    • The Box Model
    • Layout Types
    • Float
    • Clearfix
    • Centering
    • Column Structure
    • CSS Columns Code Along Exercise (lab)
    • Box Model & Page Layout
    • Using Z Index
    • Positioning
    • ZHW Shoes Layout (lab)
    • Zetsy (lab)
    • CSS Box Style Code Along
    • Animal Save (lab)
    • Building Responsive Sites
    • Intro to Responsive Media
    • CSS Media Queries
    • Working with Responsive Type
    • Responsive layout
    • The Viewport Property
    • Responsive Features Code-Along (lab)
    • Bootstrap Introduction
    • Bootstrap Code-Along
    • Bootstrap Grid System
    • Grid Layout Code-Along
    • Bootstrap Navbar Code-Along
  • Sinatra
    • What is Sinatra?
    • Sinatra From Scratch
    • Using the Shotgun Development Server (lab)
    • Sinatra Basics
    • Sinatra Hello World Basics (lab)
    • Routes in Sinatra
    • Sinatra Routes Lab
    • Intro To MVC
    • Sinatra MVC File Structure (lab)
    • Sinatra Views: Using ERB
    • Sinatra Views (lab)
    • Sinatra Basic Views Lab
    • Sinatra Views Lab II
    • Intro To Capybara
    • Dynamic Routes in Sinatra
    • HTML Forms and Params
    • Passing Data Between Views and Controllers in Sinatra
    • Sinatra Forms Lab
    • Sinatra Yield Readme
    • Integrating Models Sinatra Code-along
    • Sinatra MVC Lab - Pig Latinizer
    • Sinatra Basic Forms Lab
    • Sinatra Forms
    • Nested Forms Readme
    • Sinatra Nested Forms Lab: Pirates!
    • Lab Review-- Sinatra Nested Forms Lab: Pirates
    • Sinatra Nested Forms Lab: Superheroes!
    • Sessions and Cookies
    • Mechanics of Sessions
    • Sinatra Basic Sessions Lab
    • Using Sessions
    • Sinatra and Active Record CRUD
    • Sinatra Activerecord Setup
    • Sinatra ActiveRecord CRUD
    • User Authentication in Sinatra
    • Sinatra Sessions Lab - User Logins
    • Securing Passwords
    • Secure Password Lab
    • Sinatra Authentication- Overview
    • RESTful Routes
    • Restful Routes Basic Lab
    • Sinatra ActiveRecord Associations: Join Tables
    • Using Tux in Sinatra with ActiveRecord
    • ActiveRecord Associations in Sinatra
    • Sinatra Multiple Controllers
    • Sinatra and Active Record: Associations and Complex Forms
    • Sinatra Playlister (lab)
    • Welcome to NYC Sinatra! (lab)
    • Building a Site Generator, Part 1- Overview
    • Building a Site Generator, Part 2- Overview
    • Fwitter Group Project
  • Rails
    • Welcome To Rails
      • Rails Application Basics
      • Rails Static Request
      • Rails Hello World Lab
      • Rails Model View Controller
      • Intro to Rails- Overview
    • Intro to REST
    • Active Record Models and Rails
    • ActiveRecord Model Rails Lab
    • RESTful Index Action Lab
    • Rails Dynamic Request
    • Rails Dynamic Request Lab
    • Rails URL Helpers
    • Rails URL Helpers Lab
    • Rails form_tag
    • Rails form_tag Lab
    • Create Action
    • Create Action Lab
    • Index, Show, New, Create Lab
    • Edit/Update Action
    • form_for on Edit
    • Strong Params Basics
    • form_for Lab
    • Rails Generators
    • CRU with form_for Lab
    • Resource and Scaffold Generator
    • Rails Blog scaffold
    • Todo mvc assets and managing lists
    • Rails Forms Overview
    • ActiveRecord Validations
    • ActiveRecord Validations Lab
    • Validations in Controller Actions
    • Validations In Controller Actions Lab
    • Validations with form_tag
    • Validations with form_for
    • DELETE Forms and Requests
    • Testing in Rails
    • Validations with form_tag
    • CRUD With Validations Lab
    • Join the Fun rails
    • Activerecord lifecycle reading
    • Displaying Associations Rails
    • Active Record Associations Review
    • Forms And Basic Associations Rails
    • Forms And Basic Associations Rails Lab
    • Basic Nested Forms
    • Displaying Has Many Through Rails
    • Displaying Has Many Through Rails Lab
    • Has Many Through Forms Rails
    • Has Many Through Forms Rails Labs
    • Has Many Through in Forms Lab Review- Overview
    • Deep Dive into Nested Forms- Overview
    • Layouts And Templates in Rails
    • Rails Layouts And Templates Lab
    • Simple Partials
    • Simple Partials Lab
    • Partials with Locals
    • Partials with Locals
    • Refresher on MVC
    • Refactoring Views With Helpers
    • Refactoring Views With Helpers Lab
    • Model Class Methods
    • Optimal Queries using Active Record (lab)
    • Routing And Nested Resources
    • Nested Resource Routing Lab
    • Modifying Nested Resources
    • Modifying Nested Resources Lab
    • Namespaced Routes
    • Namespaced Routes Lab
    • Todomvc 2 lists have items
    • TodoMVC 3: Mark Items Complete
    • Todomvc 4 refactoring with partials and helpers
    • Todomvc 5 deleting items
    • Introduction to Authentication and Authorization
      • Cookies and sessions
      • Cookies and Sessions Lab
      • Sessions Controller
      • Sessions Controller Lab
      • Login Required Readme
      • Login Required Lab
      • Using has_secure_password
      • Has_secure_password lab
      • Authentication- Overviewn
      • OmniAuth
      • Omniauth Lab
      • Omniauth review lecture in todomvc
      • Authentication and authorization recap and gems
    • Rails Amusement Park lab
    • How to Find Gems
  • JavaScript
    • Intro to JavaScript
      • JavaScript Data Types
      • JavaScript Data Types Quiz
      • JavaScript Variables
      • JavaScript Comparisons
      • Conditionals
      • Logical Operators
      • Functions
      • Intro to Debugging
      • Intro to Testing
      • JavaScript Basics Quiz
    • Scope
      • Scope chain
      • JavaScript Practice Scope Lab
      • Lexical scoping
      • Errors and Stack Traces
      • Hoisting
    • Arrays And Objects
      • Objects
      • JavaScript: Objects and Arrays Quiz
      • Object Iteration
      • JavaScript Logging
      • Traversing Nested Objects
      • Filter
      • Map
    • Functions Revised
      • First-Class Functions Lab
      • First-Class Functions
      • First-Class Functions Practice
      • First-Class Functions Practice Lab
    • OOP
      • Creating Objects
      • Object Methods and Classes
      • Using Prototypes
      • Using Classes in Javascript
      • JavaScript This Walkthrough
      • This Code-along
      • Bind, Call, and Apply Readme
      • Bind, Call, Apply Lab
      • Object Relations
      • Association Methods in Javascript
      • Class Relations Lab
      • JavaScript Closures and Higher Order Functions
      • Closures Lab
      • JavaScript Arrow Functions
      • Daily Lunch Lab
    • DOM
      • Introduction to the DOM
      • Introduction to the DOM Lab
      • More on the DOM
      • Creating and Inserting DOM Nodes
      • The DOM Is a Tree
      • Listening to Nodes
      • Modify HTML With jQuery
      • Modifying HTML Lab
      • jQuery Selectors
      • Document.ready
      • Acting On Events Lab
      • DOM Quiz
    • Templates
      • Introduction to CSS
      • CSS Quiz
      • CSS Libraries
      • CSS Libraries Lab
      • Intro to Templates
      • Template Engines
      • Template Engines Lab
      • Advanced Templating
      • Advanced Templating Lab
    • Asynchronous JavaScript
      • Intro to XHR Code Along
      • Hitting APIs Lab
      • Advanced AJAX Lab
      • AJAX and Callbacks
      • AJAX and Callbacks Lab
      • REST Refresher
      • REST Quiz
      • Fetch
      • JavaScript fetch() Lab
      • Intro to Mocha
      • Testing with Spies
      • Testing with Mocks and Stubs
  • Rails and JavaScript
Powered by GitBook
On this page
  • Overview
  • Objectives
  • Introduction
  • Uncaught ReferenceError: _____ is not defined
  • Uncaught TypeError: _____ is not a function
  • Uncaught SyntaxError: missing ) after argument list
  • Uncaught TypeError: Assignment to constant variable.
  • Stack traces
  • index.html and errors.js
  • Playing catch with JavaScript errors
  • Conclusion
  • Resources
  1. JavaScript
  2. Scope

Errors and Stack Traces

PreviousLexical scopingNextHoisting

Last updated 5 years ago

Overview

In this lesson, we'll introduce some of the common types of errors you'll encounter when writing JavaScript code.

Objectives

  1. Recognize common JavaScript errors.

  2. Read a stack trace to discern where an error originated.

Introduction

No one writes perfect code the first time. Or the second time. Or the third time.

We all make mistakes. One of the biggest advantages an experienced programmer has is knowing how to quickly troubleshoot and fix errors they encounter. You will reach this point — it's just a matter of practice. To get you started, let's look at some of the common types of error messages you'll encounter when writing JavaScript code.

Uncaught ReferenceError: _____ is not defined

This is one of the simplest and most common errors, and it's pretty explicitly telling us what went wrong. We tried to reference a variable or function that doesn't exist in the current scope (or in the scope chain)! For example:

myVar;
// ERROR: Uncaught ReferenceError: myVar is not defined

It can also arise if you forget to put quotation marks around a string:

Hello, world;
// ERROR: Uncaught ReferenceError: Hello is not defined

('Hello, world');
// => "Hello, world"

If you meant to declare the variable in the current scope and simply forgot, declaring the variable should solve the issue:

const myVar = 'Hello, world!';

myVar;
// => "Hello, world!"

The more difficult case is when you expected the variable to exist in the scope chain — that is, you expected the variable to have been declared in an outer scope and therefore to be accessible inside your function. You'll get better at recognizing and debugging this case with practice. For now, double check where the current function is declared. Make sure it's declared at a place where its scope chain should include the outer scope that contains the declaration of the variable you're trying to access.

Uncaught TypeError: _____ is not a function

This one usually indicates that you tried to invoke something that isn't actually a function. For example:

const myVar = 'Hello, world!';

myVar();
// ERROR: Uncaught TypeError: myVar is not a function

A common one that you'll run into when we get into asynchronous programming in JavaScript is Uncaught TypeError: undefined is not a function. The JavaScript engine is telling us that we tried to invoke undefined, which is obviously not invocable. It typically happens when a variable contains undefined instead of a function. The way to debug it is to find where the attempted invocation happened and then figure out why that variable contains undefined.

Uncaught SyntaxError: missing ) after argument list

When you see this error, it means you tried to invoke a function but forgot the closing parenthesis:

console.log('Hello,', 'world!';
// ERROR: Uncaught SyntaxError: missing ) after argument list

function myAdder (num1, num2) {
  return num1 + num2;
}

myAdder(10, 4;
// ERROR: Uncaught SyntaxError: missing ) after argument list

Uncaught TypeError: Assignment to constant variable.

You're probably familiar with this one by now — it means we accidentally tried to assign a new value to a variable declared with the const keyword, which prevents reassignment. However, sometimes you rightfully feel that you didn't try to reassign anything, and it boils down to a small typo:

const snackSelection = 'Pretzels';

if ((snackSelection = 'Pretzels')) {
  console.log("That'll be $1, please!");
}
// ERROR: Uncaught TypeError: Assignment to constant variable.

In this case, we accidentally used the assignment operator, a single = sign, instead of a comparison operator, such as the triple equals (===) strict equality operator.

This is just a selection of some of the many types of errors you might encounter while writing JavaScript code. The main point is to use the information you're given. The JavaScript engine isn't trying to trick you — on the contrary, it's trying to help you debug.

Stack traces

One of the really neat pieces of information provided with the error messages is what's called a stack trace. If you've been following along with the examples in the JS console, you've probably already seen something like this:

const snackSelection = 'Pretzels';

if ((snackSelection = 'Pretzels')) {
  console.log("That'll be $1, please!");
}
// ERROR: Uncaught TypeError: Assignment to constant variable.    VM5412:3
//           at :3:20
//        (anonymous) @ VM5412:3

At first glance, that's the kind of error message that makes a programmer new to JavaScript run screaming in the opposite direction. So many random numbers! What the heck are and (anonymous)?! VM5412:3 looks like the name of R2-D2's cousin!

All of this strange information is telling us the same thing: the exact location of where the error occurred. We're not going to go too deep into it, but VM standards for Virtual Machine, and it's Chrome's way of saying that the script didn't run in a specific file. In this case, the script ran in the JavaScript console, and Chrome arbitrarily assigned an ID of 5412 to the execution of that particular script. If you're coding along — which you should be! — the number in your console is most likely different. If you run the same code again, the number will have changed because Chrome's treating it as a new script execution and will assign it a new ID number.

The :3 piece of VM5412:3 is, however, interesting. It's telling us which line within the script caused the error. In this case, it happened on the third line.

The at:3:20 message elaborates on the :3, indicating that, not only was the error on the third line, it was on the 20th character of the third line. The is, like the VM designation, telling us that the error didn't occur in a specific file.

The only new piece of information on the final line is (anonymous), which is slightly different from the above. While indicates that we aren't in a particular file, (anonymous) tells us that we're in the global scope — that the error didn't occur inside of a function.

To get a better sense of the various pieces of information provided in the error message, let's take a look at a couple errors in a JavaScript file. That way, we won't have (most of) this garbage to further confuse us.

index.html and errors.js

Clone this repo to your local machine, and open up index.html in your browser.

When the file's open in your browser, open the JS console, and you should see something similar to the following error:

Whoa, that's so much easier to understand! It's telling us the error occurred on line 5 in errors.js. Let's see what's on line 5 of the file:

if (snackSelection = 'Pretzels') {

Ah, it's the same error from before: we've accidentally used the assignment operator instead of the strict equality operator. Let's fix it:

if (snackSelection === 'Pretzels') {

Save the errors.js file after you've made the fix, and refresh the browser window. You should see two things in the console, the That'll be $1, please! message from the first code snippet and a new error telling us that third is not defined:

Let's see what's on lines 17, 13, and 20 in errors.js:

function first() {
  second(); // Line 13
}

function second() {
  third(); // Line 17
}

first(); // Line 20

Now that we're dealing with a series of function invocations, we can really see the power of the stack trace: it traces the error up through the stack of function calls that led to it. Let's read it backwards and reconstruct the events that led to the error:

  1. In the global scope: the JavaScript engine reaches line 20 and invokes first().

  2. Inside first(): the engine reaches line 13 and invokes second().

  3. Inside second(): the engine reaches line 17 and sees the identifier third, but it can't find a declared variable or function with that name in the current scope (second()) or the outer scope (the global scope).

  4. Because it can't find a matching declaration, the JavaScript engine throws an error inside second() that then propagates up the call stack until it reaches the global execution context.

To fix the third is not defined error, let's first try declaring third as the simplest thing we know, a variable:

function first() {
  second();
}

function second() {
  third();
}

const third = 'Declaring a new variable.';

first();

Remember what we learned earlier in the section on common JavaScript errors. If our understanding is correct, this should fix the third is not defined error and, in its place, throw a new error. Can you guess what the new error will be?

Did you correctly deduce what the new error would be?

The new error is telling us that third is not a function. It may have been pretty obvious that our initial solution would just result in another error — after all, the code we're working with isn't all that complicated. However, intentionally breaking your code and seeing whether it breaks in the exact way you predicted is a great technique for improving your debugging and general JavaScript skills. The more you understand the errors and their causes, the easier debugging will become.

The fix, of course, is to declare third() as a function instead of a simple variable:

function first() {
  second();
}

function second() {
  third();
}

function third() {
  console.log("Now I'm a function!");
}

first();

When we save the file and refresh the page again, all of the errors should be gone:

Playing catch with JavaScript errors

We mentioned earlier that an error thrown in a function "propagates up the call stack until it reaches the global execution context." But why?

The reason thrown errors propagate up the call stack is that the JavaScript engine is looking for something to catch the error. This is getting back to why all of the error messages we've seen so far are uncaught errors.

Conclusion

Arguably the biggest difference between being a novice and an expert developer is how comfortable you feel with reading and debugging error messages. JavaScript — and, indeed, every programming language — is designed by programmers for programmers. The language doesn't intentionally make things more difficult for you. On the contrary, every time you write code that results in some sort of error, JavaScript goes out of its way to provide you with the information you need to find and fix the error. When you see one of those bright red error messages pop up, don't freak out! It's the JavaScript engine starting a friendly dialog with you: "Hey, I tried to do what you asked of me, but I ran into a problem. Here's where the problem occurred, and here's what happened."

As you become more comfortable diagnosing and solving error messages, you'll become a faster, better programmer, and writing JavaScript code will become more and more enjoyable!

Resources

JavaScript provides a control flow structure called try...catch with which you can try to run some JavaScript statements and catch any errors thrown within the try block. We aren't going to go into any greater depth on the topic because it isn't worth getting sidetracked. If you really want to learn more about handling errors with a try...catch statement, check out the . You'll probably encounter try...catch in the wild, but it's often not the best tool for the job. By design, it's a performance nightmare to rely on your code throwing errors as a control flow pattern. It's much better to make your code flexible and properly handle things like bad user input without throwing errors. Errors should be reserved for when something goes seriously wrong.

View on Learn.co and start learning to code for free.

MDN reference
MDN — Errors
Uncaught ReferenceError: _____ is not defined
Uncaught TypeError: _____ is not a function
Uncaught SyntaxError: missing ) after argument list
Uncaught TypeError: Assignment to constant variable.
MDN — try...catch
Errors and Stack Traces
That's good. Good deduction, yeah.
Assignment to constant variable
No more errors
third is not a function
Assignment to constant variable
Forever stepping on rakes