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

211
Views
javascript spread operator decision making

myfunction takes object of a persons as input and returns an a new object contaning first name, last name size and weight of person. If either weight or size was not gven in input object it should not be present in output object

function myFunction(obj) {
  return {
    fn: obj.fn,
    ln: obj.ln,
    ...(obj.size && { size: `${obj.size}cm` }),
    ...(obj.weight && { weight: `${obj.weight}kg` }),
  };
}
myFunction({ fn: 'Lisa', ln: 'Müller', age: 17, size: 175, weight: 67 })

I can't understand how ...(obj.size && { size:${obj.size}cm}), works

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

0

You can conditionally create objects with the values (if present), or empty objects (if not present), then (unconditionally) spread them in to the resulting object:

function myFunction(obj) {
  const size = obj.size ? { size: `${obj.size}cm` } : {};
  const weight = obj.weight ? { weight: `${obj.weight}kg` } : {};
  const {fn, ln} = obj;
  return {fn, ln, ...size, ...weight};
}

Alternatively (and perhaps a bit less complicated), you can create the result object first, then conditionally set the property values:

function myFunction(obj) {
  const {fn, ln} = obj;
  const result = {fn, ln};
  if (obj.size) result.size = `${obj.size}cm`;
  if (obj.weight) result.weight = `${obj.weight}kg`;
  return result;
}
about 4 years ago · Juan Pablo Isaza Report

0

This works because of "short circuit evaluation" with the && operator.

If the first operand is falsey, nothing will be "spread" into the object literal. If it is not falsey the object { size: ${obj.size}cm } will be spread into the returned object literal.

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!