简体   繁体   中英

node.js allows undefined arguments in function call

Suppose I define a function:

function pp(r)
{
    console.log("In Function", r);
    console.log("In Function", q);
    console.log("In Function", m);
}

If I execute this - I am able to use the variable q inside the function, even though it is not defined as a function parameter. However in that place if I place another variable - it throws an error.

pp('op', q='rr')
In Function op
In Function rr
Uncaught ReferenceError: m is not defined

Now if I remove the line console.log("In Function", q); I still get the error Uncaught ReferenceError: m is not defined which is acceptable as q is a named variable.

How am I able to use a variable passed to a function that is not defined in the function parameter?

pp('op', q='rr') - this is not the right approach. It will create a global variable 'q' with the value 'rr'. That's the reason you are getting the value of q.

one approach is,

function pp(r, q='rr', m)
{
    console.log("In Function", r);
    console.log("In Function", q);
    console.log("In Function", m);
}

pp('op') //  r -> op , q -> rr and m is undefined

[or] use arguments

 function pp()
    {

      if(arguments.length > 0) {
        console.log("In Function", arguments[0]);//op1
        console.log("In Function", arguments[1]);//undefined
        console.log("In Function", arguments[2]);//undefined
    }
  }
    
    pp('op1')

You can use Javascript Rest Parameters . ES6 provides a new kind of parameter called Rest Parameter that has a prefix of three dots (...)

Let's see how to use it:

function pp(r, ...args) { // ...args contains all rest parameters
  console.log("In Function", r); // op
  console.log("All other passed values", args)   // [rr, tt]
  console.log(args[0]) // 0th index value => rr
  console.log(args[1]) // 1st index value => tt
}

pp('op', 'rr', 'tt');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM