ES6 Object.assign function to set default parameter values.

Let's see an example of assigning default values to object properties using || operator.

Program 1:

<script>

var drawDiv = function(config){

   config.height = config.height || 100
   config.width = config.width || 100
   config.margin = config.width || 10
   config.padding = config.padding || 10

   console.log(config)
}

drawDiv({margin:0, padding: 0 })


</script>

 

The above code defines a function expression named drawDiv which expects a config object as a parameter.

#13  invokes the function by passing the value for margin and padding set to 0, but due to || operator 0 is considered as false and value 10 is set for each of them.

The above problem can be solved by using Object. assign function, the example code is mentioned below.

Program 2:

<script>
var drawDiv = function(config){

   var defaultValues = {
   	height: 100,
   	width: 100,
   	margin: 10,
    padding: 10
   };

   config = Object.assign(defaultValues,config)
   console.log(config)
}

drawDiv({margin:0, padding: 0 })

</script>

 

The Syntax for Object.assign():

Object.assign(target, ...sources) // returns target object

 

In the program 2, an object named defaultValues is created and used as target object at #11.

Now the value of margin and padding will be set to 0 respectively.