Anjan Dutta
Default Parameter In Javascript: What and How
Default Parameter In Javascript: What and How
In the year 2015, ES6 or ECMAScript 2015 was introduced as a major update of javascript.
This update introduces several great features ( for example classes, modules, arrow functions, destructuring, blocked-scope construct etc. ) that have helped javascript to become the backbone of modern web app development.
Use of default parameter in javascript has become so common that it has started to replace many existing features which used to make code unnecessarily lengthy.
This is a very simple feature which allows us to set a default value in any function parameter.
The initial definition might sound easy and yes the implementation even easier like below:
function addition(x, y = 0) { return x + y;}console.log(addition(5, 2));// expected output: 7
Here we are passing a value for both parameters, hence x will have 5 in memory and, y will have 2
console.log(addition(3));// expected output: 3
Look closely, we have passed only one value in place of two but still, it will output instead of throwing any error. This is because y will get 1 as a value because it was assigned to y in the function header
This definition was just the tip of an iceberg.
Actually, it has much more to offer.
A precise and smart use of default parameters can lead to a spectacular implementation. A code that you can feel proud of! Ultimately this is the goal, right? Read on.
Understanding undefined and null default parameter
As many of us know, undefined and null are treated differently as a function parameter.
The only common thing between them is, both are the primitive data types. Hence, handling them are also different.
When we don’t send any parameter value in a function call which is expecting parameter(s) then the parameter turns undefined within the function definition or function body.
This often turns into an error if not handled correctly.
Below code is an example of such scenario handled before ES6 default parameters came into the picture.
// ES5function addition(x, y) {y = (typeof y !== 'undefined') ? y : 0;return x + y;}
addition(5, 2); // 7addition(5); // 5
Using es6 default parameters, the function definition will look like:
// ES6function addition(x, y=0) {return x + y;}
See the difference? A lot less headache, isn’t it? Now, In case if we send null, it is treated as a valid value and output will be in accordance to the parameter value.
A default parameter gets evaluated at call time, hence a new object is created every time the function is called.
Rules of using default parameter in javascript
When we define a function with default parameters, the javascript interpreter checks for arguments from left to right.
Let suppose below is a function definition:
function addition(x=5, y) {return x + y;}
console.log(addition(2, 5)); //7/* x = 2, y = 5, x + y = 7 */
console.log(addition(4)); //NaN/* x=4, y=undefined, x + y = NaN */
console.log(undefined,2); //7/* x=5, y=2, x + y = 7 */
Hence, default parameters are only useful when used smartly. Always make sure to apply default values on parameters starting from the extreme right towards the left.
No harm if we pass default values to all parameters, but as they say, with great power comes great responsibility.
Support for primitive and nonprimitive data types
Does it seem like the plate is full? Not yet. Default parameters support both primitive and nonprimitive data types.
It means we can pass arrays, objects, and even functions as es6 default parameters.
Below is an example of error handling using es6 default parameters:
function throwIfNoValue() {throw new Error('Missing argument');}
function foo(argValue = throwIfNoValue()) {return argValue ;}
Here foo() is a function which has a parameter named argValue.
If we don’t pass anything in the function call here, then the function throwIfNoValue() will be called and the returned result will be assigned to the only argument argValue.
This is how a function call can be used as a default parameter. Which makes the code more simplified and readable.
Object destructuring using default parameter in javascript
Object destructuring is another great feature of ES6, but while combined with es6 default parameters, it gives us deeper control over the code.
See the below example:
function generateColor({red= 'FF', green= 'FF', blue= 'FF'} = {}) {// function body}
This is a very interesting example that we have here. The function, generateColor() takes an object as it’s argument. At first, it might seem wrong, as we don’t write objects like the way we have here: {red= ‘FF’, green= ‘FF’, blue= ‘FF’}.
But, this is how in ES6 we are ensuring that if we don’t pass all keys through an object, a key will automatically be created with those specified values as it’s default value. Hence if we make following call to the function:
generateColor({red: '00', blue: 'AA'});// red: '00',// green: 'FF'// blue: 'AA'
The second part ={} lets us call the function without any parameter. Hence, in this case, all default values will be assigned:
generateColor();// red: 'FF'// green: 'FF'// blue: 'FF'
Conclusion
Default parameter in javascript is a relatively easy feature than other ES6 features. And we have already seen that it has a lot of cool things under its hood.
We need to keep in mind all those simple points and next time, before writing code for any such matching scenarios just think and try to apply.