Is it possible to have an object nested within a function? How about a function within a function? I'm determined to grasp

0

Can someone explain to me how the function express() works? I'm having trouble understanding how you can call a function when stored in a variable like const app = express();

Then calling a function like listen() as if it were an object:

app.listen()

Any help in clarifying this would be greatly appreciated.

Thank you in advance!

Answer №1

Methods can be assigned to objects, essentially acting as functions within the object structure. The return value of these methods may or may not be significant depending on the context in which they are used.

const myObject = {
  sum: (num1, num2) => num1 + num2;
  display: (message) => console.log(message);
}

const output = myObject.sum(3, 4);
myObject.display(output);

Answer №2

In the world of Javascript, functions are not just simple entities but rather objects with various capabilities. They can be assigned to variables, executed by calling them, and even have properties assigned to them or read from them.

For instance, let's take a look at this example where we assign the module.exports from the 'express' module to a variable named 'express':

const express = require('express');

Now, here's how you would execute the function by calling it:

const app = express();

And finally, accessing the .static property on the express function would look like this:

app.use(express.static('/public'));

Another interesting aspect is that all regular functions come with some built-in properties. For example, considering a function greet(greeting) which prints out the greeting:

function greet(greeting) {
    console.log(greeting);
}

// This will output 1 as the function has one declared argument
console.log(greet.length);    

Furthermore, you also have the flexibility to add your own custom properties to functions, thanks to their nature as a sub-class of an object.

Answer №3

When a function is nested within another, it cannot be directly accessed from outside the outer function.

However, if a global reference is created for the inner function, it can become accessible.

In this particular scenario, the outerFunction includes two innerFunctions along with variable declarations that assign these functions to their respective variables (outerFunction.innerFunction1 and outerFunction.innerFunction2). Had these been declared using let or const inside the outer function, they would have remained limited to internal access only. But by declaring them without a specific scope, they gain global accessibility.

Therefore, upon invoking the outerFunction, the inner functions are elevated to the global scope and can now be referenced by their assigned names - outerFunction.innerFunction1 and outerFunction.innerFunction2. While naming them with a dot serves as a reminder of their origin, any other name could be used for direct calling (as demonstrated in the third example within the snippet).

function outerFunction(){
    
    function innerFunction1(){
      console.log( 'hello from first innerFunction' );
    } // end innerFunction2;
    
    function innerFunction2(){
      console.log('hello from second innerFunction');
    } // end innerFunction2;

    function innerFunction3(){
      console.log('hello from the third function');
    } // end innerFunction3;
    
  outerFunction.innerFunction1 = innerFunction1;
  outerFunction.innerFunction2 = innerFunction2;
  anyName = innerFunction3;
  
} // end outer function;

outerFunction(); // essential to declare and initialise global variables about to be accessed;
outerFunction.innerFunction1();
outerFunction.innerFunction2();
anyName();

Before diving into the outer function provided in your example, take note of the dot notation variable declaration used for calling. There's nothing mystical about the dot notation; it simply represents a variable name.

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

"Node File Uploads: A Guide to Uploading Files

Is there a way to restrict access to uploaded files only to the user who uploaded them? I want to ensure that each user can only access their own files. At the moment, all files are being uploaded to a shared static folder (Public). ...

Trouble accessing value in Vue.js

I'm having an issue where I am unable to access this.active in my method delete. What could be causing this problem? data () { return { ride: { user: {}, location: {}, type: {} }, active: false } }, methods: { delete () ...

Is Jquery compatible with your Wordpress theme?

My current wordpress version is 3.4.1 and I want to include jQuery in my custom wordpress theme. Despite trying multiple solutions found online, I have been unsuccessful in implementing it convincingly. Can someone please provide a simple example to help ...

Saving data in a CSV file on your local device using HTML5

Is it possible to utilize HTML5 for saving or writing data to a local file on the user's file system? I am curious about this functionality, especially since HTML5 now offers the capability to export data from the client and save it as a CSV file. If ...

The issue persists where Chrome WebAPI's chrome.webRequest.onBeforeSendHeaders is failing to modify the parameters in the outbound requests

I have been attempting to include an IP address in the X-Forwarded-For parameter within the requestHeader, but my code does not seem to be working based on the examples provided in the Chrome API. Below is the code snippet I am currently using: var reque ...

What is the best way to trigger the code within my useEffect React hook to execute again upon refreshing the page?

I'm encountering an issue where the value of states is becoming 'undefined' after refreshing the page. Within my useEffect hook, I am generating a random number to select a question object from an array. Everything works smoothly on the ini ...

Mysterious source utilizing leafletView for showcasing popups within the Angular Leaflet Directive

I've been attempting to implement a pop-up window on an Angular Leaflet map using Prune Cluster, but I keep running into an error stating that 'leafletView' is an unknown provider. Despite following the examples provided on this page, https: ...

Angular's directives do not trigger the 'viewContentLoaded' event

I recently created a 'light-gallery' directive that relies on the jquery.lightgallery.js plugin to initialize the $.fn.lightGallery() functions. It is crucial for these functions to be executed after the directive template has been compiled and l ...

Concealing HTML pages in Node.js: A step-by-step guide

I have a specific requirement where my website's html pages should only be accessible to users who are logged in. However, when I used the command below, my html pages became public: app.use(express.static('public')); For instance, I do no ...

Can you explain what an express template engine is?

Having recently started working with express and angular development, I have a question about rendering views. Specifically: 1) What are the advantages of rendering a view via express using a template engine rather than solely relying on angular? 2) Is i ...

Exploring the Benefits of Utilizing Fetch over XMLHttpRequest in React Native

Recently, I attempted to upload images to S3 from my react native app by following a guide provided by Heroku: https://devcenter.heroku.com/articles/s3-upload-node In essence, I utilized the aws-sdk on my express.js backend to generate pre-signed requests ...

Alert: Unresolved Promise Rejection Notification in the world of Express.js and Node.js!

Recently delving into the world of Node.js and Express.js, I've been attempting to incorporate the Shippo API into my E-commerce website. Unfortunately, I have encountered persistent errors that have proved challenging to troubleshoot despite numerous ...

Using ng-transclude directive allows for encapsulating HTML content within an ng-transclude element

My directive includes an ng-repeat in the template and also has an ng-transclude option after the repeater to allow users to input their own content. The issue arises when the custom content is surrounded by an ng-transclude element upon rendering, which i ...

What is the best way to delay a method in vue.js?

In the tab element called competences, there is an input field with the reference search. <ul class="nav nav-tabs" id="myTab" role="tablist"> <li class="nav-item"> <a @click="competencesTabClick" aria-controls="Company" aria-sel ...

Activating a link click inside a table with jquery

I have been attempting to trigger a click on an anchor within the table compareTable with the code below, however it does not appear to be working as expected. Would anyone be able to provide insight into a possible solution? $('#compareTable a' ...

Unable to display label in form for Angular 2/4 FormControl within a FormGroup

I'm having trouble understanding how to: Use console.log to display a specific value Show a value in a label on an HTML page Display a value in an input text field Below is my TypeScript component with a new FormGroup and FormControls. this.tracke ...

Implementing closure within a recursive function allows for better control

One of my functions is designed to take a parameter and print the last number in the Fibonacci Series. For example, if the parameter is 3, it would return 2 as the series progresses like 1, 1, 2. function recursionFib(num){ if(num ...

Tips for preventing the playback of the sound while recording

When creating a basic JavaScript application that involves opening a stream from the user and analyzing frequencies, I found that while Google Chrome and Opera work well by providing feedback in the headphones, Firefox often remains silent. Additionally, F ...

In HTML, data can be easily accessed, however, JavaScript does not have the same

When trying to access the 'data' element in a JSON object, I have encountered an issue. The element is accessible when called from HTML, but not when called in JavaScript. HTML: <p>{{geoJson.data}}</p> JavaScript: let scope; let d ...

Send the context parameter value of Unified Service Desk to a JavaScript web resource in CRM

Currently, I am working on CRM 8.2 and Unified Service Desk 4.1. I have a specific requirement where I need to pass parameter values from within Unified Service Desk Data Parameters to a JavaScript Webresource. I have come across some resources that sugge ...