Why doesn't express.js throw an error when the variable 'app' is used within its own definition?

When working with express.js, I find it puzzling that createApplication() does not throw an error. This is because it uses app.handle(...) within an anonymous function that defines the same variable 'app'.

I attempted to replicate this in jsFiddle and encountered the expected 'app is undefined' error. The function assignment at the beginning of create Application() is what confuses me:

function createApplication() {

  //New variable 'app' to be defined 
  //by anonymous function

    var app = function(req, res, next) {
      app.handle(req, res, next);        // But 'app' not fully defined yet!
  };

  mixin(app, EventEmitter.prototype, false);
  mixin(app, proto, false);

  // expose the prototype that will get set on requests
  app.request = Object.create(req, {
    app: {\ configurable: true, enumerable: true, writable: true, value: app         }
  })

  // expose the prototype that will get set on responses
  app.response = Object.create(res, {
    app: { configurable: true, enumerable: true, writable: true, value: app 
    }})

  app.init();
  return app;
}

Answer №1

  1. When using JavaScript, it's important to note that var bindings are hoisted to the top of the containing scope. This means that the variable is already defined when a closure is created.
  2. JavaScript closures do not store the values of variables they reference at the time of creation. Instead, they directly access and bind to the lexical environment, allowing them to see the current value of app when invoked.
  3. If you encounter an undefined variable error, it likely stems from calls to the mixin function.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What may be causing my Ajax call to get stuck at readystate 1 and not progress further

I've double-checked all my code, yet I'm not getting any response from my Ajax call. Can someone help me figure out what's wrong? function fetchPokemonData() { const apiRequest = new XMLHttpRequest(); apiRequest.open('GET', &apo ...

Modifying the value of a property in one model will also result in the modification of the same

As a beginner with Vue, I am looking to allow users to add specific social media links to the page and customize properties like text. There are two objects in my data - models and defaults. The defaults object contains selectable options for social media ...

Merge data from api into visual charts using Google Chart Library

I received an API response with the following data structure: { "status": 200, "message": "OK", "data": [ { "_id": { "report_type": "robbery" }, "report_type": "robbery", "Counts": 11 }, { "_id": { "repo ...

How come modifications to a node package are not reflected in a React.js application?

After running "npm install" to install node modules, I made some changes to a module. The modifications are highlighted in a red rectangle. The "find" command line tool only detected one file with that name. Next, I launched my react app: npm run start ...

Direct your attention towards the bootstrap dropdown feature

I have encountered an issue with using a bootstrap dropdown. I need to focus on the dropdown in order to navigate through its options using the keyboard. However, my current attempt at achieving this using jQuery does not seem to be working when I use $(&a ...

Passing PHP value from a current page to a popup page externally: A guide

I'm currently facing an issue at work where there is a repetitive button and value based on the database. I need to extract the selected value from the current page into a pop-up page whenever the corresponding button is clicked throughout the repetit ...

Converting data types when transferring a JavaScript variable to a PHP variable

I have a boolean value stored in a JavaScript variable var value=true; alert(typeof(value)); //Output: boolean I need to pass this variable to a PHP file through AJAX $.ajax({ type: 'POST', data: {value:value}, url: 'ajax.php& ...

What is the method for placing one object within another object?

This is a sample of my data collection: [ { "column1":"data1", "column2":"data2", "column3":[ { "column31":"data31", "column32& ...

Guide to using the Firefox WebExtensions API to make AJAX requests to the website of the current tab

I am trying to develop a web extension that will initiate an AJAX call to the website currently being viewed by the user. The specific endpoint I need to access on this website is located at /foo/bar?query=. Am I facing any obstacles in using either the f ...

Ensure data accuracy by triggering the cache - implementing SWR hook in Next.js with TypeScript

I recently implemented the swr hook in my next.js app to take advantage of its caching and real-time updates, which has been incredibly beneficial for my project (a Facebook clone). However, I encountered a challenge. The issue arises when fetching public ...

Is it possible to loop through a subset of a collection using *ngFor?

Is it possible to iterate through a specific range of elements in a collection using *ngFor? For instance, I have a group of checkboxes with their form control name and label specified as follows: [{id: 'c1', label: 'C1'}, ...] Assum ...

The onclick event seems to be malfunctioning on the website

My goal is to implement a modal box that appears when a user clicks a button and closes when the user interacts with a close button within the modal box. I have created two functions for this purpose: check() : This function changes the CSS of an element ...

What is the process for incorporating beforeAnimate and afterAnimate callbacks into a custom jQuery plugin?

Let's imagine I have developed a plugin: // creating the plugin (function($){ $.fn.myPlugIn = function(options){ defaults = { beforeAnimate : function(){}, afterAnimate : function(){} ...

Implementing automatic value setting for Material UI slider - a complete guide

I am working on developing a slider that can automatically update its displayed value at regular intervals. Similar to the playback timeline feature found on platforms like Spotify, Soundcloud, or YouTube. However, I still want the slider to be interactive ...

What is the best way to deselect all "md-checkboxes" (not actual checkboxes) on an HTML page using a Greasemonkey script?

After spending a frustrating amount of time trying to disable the annoying "md-checkboxes" on a certain food store website, despite unchecking them multiple times and reporting the issue without any luck, I have come to seek assistance from knowledgeable e ...

What triggers the invocation of the onerror handler in XMLHttpRequest?

I am facing a bit of confusion when trying to understand the functionality of XMLHttpRequest's handlers. After reading the specification regarding the onerror handler, it mentions: error [Dispatched ... ] When the request has failed. load [Dispa ...

What is the process for establishing a dependency on two distinct JavaScript files, similar to the depends-on feature found in TestNG?

I am faced with a scenario where I have two separate JS files containing test methods, namely File1 and File2. The requirement is that File2.js should only be executed if File1.js has successfully completed its execution. My current setup involves using ...

Issue: "Access-Control-Allow-Origin does not allow origin null" error message is returned when attempting to access a PHP file using jQuery's ajax method with dataType text/html selected

Why am I encountering this issue in Chrome when using dataType text and HTML? It seems to work fine if I output JavaScript and set the dataType to script. How can I return non-JavaScript data from a PHP file? Client-side code: $.ajax({ url: ...

Customize Your Lightbox Fields with DHXScheduler

In my JSP application for exam timetabling, I have integrated DHXScheduler and customized the lightbox to display additional information about exams using my own fields. The EventsManager class is responsible for managing events by saving, creating, and r ...

Guide on utilizing automatic intellisense in a standard TextArea within a web application

I have successfully created an Online compiler web application that is currently running smoothly. However, I am now looking to enhance my application by implementing intellisense in the TextArea where the program is being typed. For instance, if I type "S ...