il0v3d0g
il0v3d0g

Reputation: 663

Can a function without an argument be called with an argument in JS?

I am trying to figure out what this piece of code is doing, and how this is working. How is let foo = require('foo') being called when it doesn't take any argument?

foo.js

module.export = async () => { do something and return response(200) }

bar.js

let foo = require('foo')
module.exports = {
  foo: async (req) => { return foo(req) }
}

route.js

let api = required('api')
let bar = required('bar')
module.exports = api => {
  api.get('/foo', async req => await bar.foo(req))
}

Upvotes: 0

Views: 75

Answers (1)

slebetman
slebetman

Reputation: 113866

TLDR:

Yes, it is allowed.

How it works

All functions in js have access to a local variable called arguments. The arguments variable is an array-like object (something that looks like an array but is not an instance of the Array class) containing all arguments passed to the function. This is basically the js mechanism supporting variable arguments.

Example:

function a () {
    for (x=0; x<arguments.length); x++) {
        console.log(arguments[x]);
    }
}

In addition to allowing you to pass more arguments than what's defined by a function js also allows you to pass fewer arguments that what's required by a function. The arguments that you don't pass are simply given the value of undefined.

Upvotes: 2

Related Questions