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

What is the most effective way to extract information from a .txt file and showcase a random line of it using HTML?

As a newbie in HTML, my knowledge is limited to finding a solution in C#. I am attempting to extract each line from a .txt file so that I can randomly display them when a button is clicked. Instead of using a typical submit button, I plan to create a custo ...

Having trouble sending Props between components within a specific route as I keep receiving undefined values

Here is the code for the initial component where I am sending props: const DeveloperCard = ({dev}) => { return ( <Link to={{pathname:`/dev/${dev._id}`, devProps:{dev:dev}}}> <Button variant="primary">Learn More</Butt ...

The "add to cart" button is unresponsive

My issue is that the add to cart button on my website is not responding properly. I have implemented JavaScript on the add to cart button, where I have assigned an attribute called data-product with a value of {{product.id}}. var updateBtns = document.g ...

JQuery is having trouble locating a variable in a different JavaScript file

Currently, I am utilizing the cakephp framework and have developed 2 distinct javascript files which I have stored in my webroot/js directory. The first javascript file includes modal dialog variables that define the settings for the dialog boxes. The seco ...

Having issues with JavaScript and MySQL data retrieval following XMLHttp update to the database

After running the newNet.php file successfully creates a new entry and assigns it an auto-incremented netID. The next step is to retrieve this newly created ID and use it in the showActivities() function to display the record. Ideally, it should work like ...

Coding with Angular 4 in JavaScript

Currently, I am utilizing Angular 4 within Visual Studio Code and am looking to incorporate a JavaScript function into my code. Within the home.component.html file: <html> <body> <button onclick="myFunction()">Click me</button> ...

Extracting JavaScript OnClick button using Selenium

I'm having trouble extracting the email address from the following URL: https://www.iolproperty.co.za/view-property.jsp?PID=2000026825 that is only visible after clicking on the "Show email address" button. However, every time I attempt to click and r ...

The issue of deleting the incorrect document ID in React Firebase

I'm currently facing an issue while trying to implement a delete operation on a Firebase database using Reactjs. The problem lies in my function that seems to be fetching the wrong id from Firebase. There's a button triggering the handleOpen fun ...

Finding the Middle Point of a Circle Using CEP/JavaScript

Using a specific set of calculations, I am able to create a circle in this manner: var yMinCir = height - 1515.80/2.667+8.5; var yMaxCir = height - 1545.80/2.667+8.5; var myCircle = page.ovals.add({geometricBounds:[yMinCir, 1312.63/2.667+8.5, yMaxCir, 1342 ...

React-dnd supporting multiple draggable and droppable elements

I am facing a challenge with making multiple elements draggable using react-dnd. I have an array of 4 fields that I would like to make draggable, but when I map through the array and give each element a className of 'element', they do not move as ...

Guide on creating a menu that remains open continuously through mouse hovering until the user chooses an option from the menu

I have a unique scenario where I am working with two images. When the mouse hovers over each image, two corresponding menu bars appear. However, the issue is that when the mouse moves away from the images, the menu disappears. Any suggestions on how to im ...

Generate several invoices with just a single click using TypeScript

I'm interested in efficiently printing multiple custom HTML invoices with just one click, similar to this example: Although I attempted to achieve this functionality using the following method, it appears to be incorrect as it prompts the print dialo ...

Can node JS code be written on the client side in Meteor 1.3?

Is it feasible to write Node.js code on the client side of Meteor 1.3? I tried looking for information but couldn't locate any evidence. Previous inquiries didn't mention its availability, however, I recall reading that it would be possible start ...

The problem with the first item title in the Jquery slider is causing

I've been working on setting up a Jquery slider (caroufredsel) in which I want certain elements to be displayed above the slider itself, outside of the wrapper. Everything is working fine except for the first slide! After spending several days trying ...

Creating an input range element and its event handler dynamically within the ajaxStop function allows for real-time updates based on the

As a beginner in JavaScript development and Ajax, I am currently working on creating a webpage that utilizes Ajax to fetch data from a server. The data is then used to draw geoJSON features on a map using Leaflet. These feature sets need to be toggleable f ...

The issue with the jQuery function lies in its inability to properly retrieve and return values

Within my code, I have a function that looks like this: $.fn.validate.checkValidationName = function(id) { $.post("PHP/submitButtonName.php", {checkValidation: id}, function(data) { if(data.returnValue === true) { name = true; } else { ...

What is the solution for halting code execution in a foreach loop with nested callbacks?

Currently, I am in the process of setting up a nodejs database where I need to retrieve user information if the user exists. The issue I'm facing is that when I return callback(null) or callback(userdata), it does not stop the code execution and resul ...

React and Express encounter the error message "TypeError is not a function" while collaborating on a project

var express = require('express') const app = express(); const port = process.env.PORT || 5000; app.listen(3000, () => console.log('Server started')) Can anyone spot the problem in this code snippet? According to VS Code: T ...

Toggle classes on button click

<div class='fixed_button homes hidden'> <a class='btn btn-primary homes'>Continue &rarr;</a> </div> Using jQuery Library $(".homes").on('click', function(){ $("choose_style").addClass(&apo ...

What is the best way to create a React component that renders a class component as a functional component?

My Objective: At the moment, I am in the process of developing an AuthUserRole HOC component to manage user roles like Manager and Employee. However, I encountered a tutorial that uses a functional component to return a class component as referenced here. ...