Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

149
Views
Javascript - Set default values for object optional fields in function params

function myFunction(data, options = { merge: true, cache: false }) {
   console.log({ merge: options.merge });
   console.log({ cache: options.cache });
   console.log("----------------------");
}


myFunction({}, { cache: true });
myFunction({}, { merge: false });
myFunction({});

How can I do, in the above example, to avoid losing the default value of the optional field "merge"?

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

You can use default value assignment with the destructuring assignment notation

{ merge = true, cache = false } = {}

function myFunction(data, { merge = true, cache = false } = {}) {
   console.log({ merge: merge });
   console.log({ cache: cache });
   console.log("----------------------");
}


myFunction({}, { cache: true });
myFunction({}, { merge: false });
myFunction({});

about 4 years ago · Juan Pablo Isaza Report

0

Another way is to use the fallback values feature of destructuring

function myFunction(data, options = {}) {
    const {merge = true, cache = true} = options;
    console.log({merge});
    console.log({cache});
    console.log("----------------------");
}

about 4 years ago · Juan Pablo Isaza Report

0

One of the ways:

function myFunction(data, options) {
  options = {merge: true, cache: true, ...options}
  console.log({merge: options.merge});
  console.log({cache: options.cache});
  console.log("----------------------");
}
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!