calling a function on a function is it possible?

Viewed 1174

in the following code

const express = require('express');
const app = express()
app.use(express.static('public'));

express is a function so how it call "express.static('public')" method on it? is it possible in JavaScript to call a function which is inside a function

3 Answers

You can attach a function as member data to another function (which is what is done in your example).

const express = () => {};
express.static = argument => console.log('argument');
express.static('public'); # console >>> 'public'

However, you cannot readily access a variable that is defined in a function body.

const express = () => {
    const static = argument => console.log('argument');
};
express.static('public'); # console >>> Error: undefined in not a function

There is a signifiant difference between member data attached to a function (the first example) and the closure that wraps the body of the function (the second example).

So, to answer your question "is it possible in JavaScript to call a function which is inside a function?" No, this is not readily possible with the important note that this is not what is being done in your example.

Actually, it is possible to call a function inside another function in javaScript. So it depends on the condition, Callback is widely used in js

(A callback is a function that is to be executed after another function has finished executing)

function doHomework(subject, callback) {
  alert(`Starting my ${subject} homework.`);
  callback();
}
function alertFinished(){
  alert('Finished my homework');
}
doHomework('math', alertFinished);

And the second example can be Closures

(A closure is a feature in JavaScript where an inner function has access to the outer (enclosing) function's variables)

function outer() {
   var b = 10;
   function inner() {

         var a = 20; 
         console.log(a+b);
    }
   return inner;
}
Related