Jeremiah Zucker
Jeremiah Zucker

Reputation: 182

JavaScript - Is passing undefined as a parameter the same as leaving it out?

Pretty straightforward question. For example, are these equivalent?

window.open('http://someurl.com')

window.open('http://someurl.com', undefined)

Part of me suspects that it might depend on the function itself, but I'm not sure.

Upvotes: 2

Views: 738

Answers (1)

CRice
CRice

Reputation: 32146

In short: In the vast majority of cases, passing undefined is equivalent to leaving the argument out.

However, within a function, you can differentiate between an omitted argument and one that was passed as undefined. While I would never recommend using that distinction to change behavior, you can see the difference between the two if you access the special arguments variable within your function:

function logNumArgs() {
  console.log(arguments.length)
}

logNumArgs() // 0
logNumArgs(undefined, undefined) // 2

Note: the arguments variable is only accessible on non-arrow functions!

MDN - Arguments Object

Upvotes: 3

Related Questions