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

184
Views
Underscore "defaults" from scratch

I've been trying to rewrite the _.defaults method from underscore.js and I keep getting this error:

should copy source properties to undefined properties in the destination object‣ AssertionError: expected { a: 'existing' } to deeply equal { a: 'existing', b: 2, c: 3, d: 4 }

Here's the missing conditions:

-should copy source properties to undefined properties in the destination object and should return the destination object

and my code:

_.defaults = function (destination, source) {
  Object.keys(destination).forEach(key => {
    if (destination[key] === undefined || destination[key] === null) {
      destination[key] = source[key];
    }
  })
  return destination;

};
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

The idea in _.defaults is that keys from the source object might be missing entirely in the destination object. So you need to iterate the keys of the source object instead of those of the destination object:

_.defaults = function (destination, source) {
  Object.keys(source).forEach(key => {
    if (destination[key] === undefined || destination[key] === null) {
      destination[key] = source[key];
    }
  })
  return destination;

};

Side note: you can write x == null instead of x === null || x === undefined. Saves some precious keystrokes.

_.defaults = function (destination, source) {
  Object.keys(source).forEach(key => {
    if (destination[key] == null) {
      destination[key] = source[key];
    }
  })
  return destination;

};
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!