LearnFrenzy
Sign in Take a free test

Objects · Predict the Output · Question 20

Optional chaining with defaults Answer, explanation & discussion

  • Output
  • Easy
  • 0 comments
  • Answer explained
  • Moderated community
Question 20 Back to Exercise

What does the following JavaScript code print (console output, as in Node.js)?

main.js
const cfg = { db: { port: 0 } };
console.log(cfg.db?.port ?? 5432, cfg.cache?.ttl ?? 60, cfg.db.host?.length);
  • A 5432 60 undefined
  • B 0 60 0
  • C 0 60 undefined Correct
  • D TypeError
Correct Answer: Option C

port is 0 (not nullish), so ?? keeps it. cfg.cache is missing, so the chain gives undefined and ?? supplies 60. host is undefined, so ?.length is undefined.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links