Why doesn’t it need a undefined or null for optional parameters in Node.js?

  Kiến thức lập trình

See this example from Node.js docs:

response.writeHead(statusCode[, statusMessage][, headers])
const body = 'hello world';
response
  .writeHead(200, {
    'Content-Length': Buffer.byteLength(body),
    'Content-Type': 'text/plain',
  })
  .end(body);   

The second parameter of writeHead function should be statusMessage.
Why can this second parameter be skipped automatically, don’t we need a undefined or null for the parameter? How does Node.js know the object is for the third parameter?

Why not:

const body = 'hello world';
response
  .writeHead(200, undefined, {
    'Content-Length': Buffer.byteLength(body),
    'Content-Type': 'text/plain',
  })
  .end(body); 

New contributor

Mason Xing is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

The documentation says:

The last argument, headers, are the response headers. Optionally one can give a human-readable statusMessage as the second argument.

The implementation of the writeHead function checks whether the second argument is string or object and behaves accordingly. You can see it in the source.

if (typeof reason === 'string') {
  // writeHead(statusCode, reasonPhrase[, headers])
  // ...
} else {
  // writeHead(statusCode[, headers])
  // ...
}

LEAVE A COMMENT