When to use Object.assign()

Passsing objects as arguments

function func(name, weight, height, isCrazy){  //Some logic to use these arguments

}
//Do you feel the pain during calling this function?func("Raj", 85, 5.11, false);
  • We will need to remember the order of arguments when calling the function every flucking time.
  • We can’t miss any arguments in the middle, but only in the end (if we are using any default arguments).
  • It’s messy to set default arguments in the main function if we wish to.

Solution

function func(args){// now we can use the arguments in the function like this
//since args is an object with our arguments as properties

console.log(args.name);
console.log(args.weight);
console.log(args.height);
console.log(args.isCrazy);
}var person = {
name: "Raj",
weight: 85,
height: 5.11,
isCrazy: false
}
//Do you see how painless this function call isfunc(person);//or we can call directly like thisfunc({
name: "Raj",
weight: 85,
height: 5.11,
isCrazy: false
});

Set up default arguments inside function using Object.assign()

function func(args){  //our default arguments  let defaultArgs = {
name: "default",
weight: 80,
height: 5.10,
isCrazy: true
}
//let's overwrite our defaultArgs if any values were passed let requiredArgs = Object.assign({}, defaultArgs, args); //Now we shall use requiredArgs in our code logic console.log(defaultArgs);
console.log(requiredArgs);
}
  1. function call without any arguments
func();//defaultArgs
//{ name: 'default', weight: 80, height: 5.10, isCrazy: true }
//requiredArgs
//{ name: 'default', weight: 80, height: 5.10, isCrazy: true }
func({
name: "Raj",
isCrazy: false
});
//defaultArgs
//{ name: 'default', weight: 80, height: 5.10, isCrazy: true }
//requiredArgs
//{ name: 'Raj', weight: 80, height: 5.10, isCrazy: false }
func({
name: "Raj",
isCrazy: false,
weight: 200,
height: 6.1
});
//defaultArgs
//{ name: 'default', weight: 80, height: 5.10, isCrazy: true }
//requiredArgs
//{ name: 'Raj', weight: 200, height: 6.1, isCrazy: false }
func({
name: "Raj",
hasSixPacks: true
});
//defaultArgs
//{ name: 'default', weight: 80, height: 5.10, isCrazy: true }
//requiredArgs
/*{ name: 'Raj',
weight: 80,
height: 5.1,
isCrazy: true,
hasSixPacks: true }*/

Words of Caution for best use

  1. Object.assign() was introduced in ECMAScript 2015 so you might want to include the polyfill(function definition for the new functions) in your production code from here for best browser support.
  2. We know that it does not performs deep copy hence you might get weird results if objects contain embedded objects or arrays, as they wont be copied but a reference will be used instead, so stay alert for that.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Neetish Raj

Neetish Raj

Full stack Development | Product Engineering | Recruitment