How to Assign Default Values to Function Parameters in JavaScript

Use-Cases of this Tutorial

  • Know how to set a default value for function parameters that are not passed.

Function parameters can be initialized with a default value in the parameter list itself using ES6 default parameters.

Assigning Default Values - Traditional Approach

Traditionally the default value of unpassed parameters were set in the body of the function. The specific parameters were checked for an undefined value, and if the condition satisfied, they were initialized with a default value.

function someFunc(a, b) {
	if(a === undefined)
		a = "Useful";
	
	if(b === undefined)
		b = "Angle";

	// "UsefulAngle"
	console.log(a + b);
}

someFunc();

Assigning Default Values - ES6 Way

With ES6 it is now possible to assign default values in the parameter list itself. This approach has resulted in doing away with checking the parameters and assigning value in the function body.

function someFunc(a="Useful", b="Angle") {
	// "UsefulAngle"
	console.log(a + b);
}

someFunc();

Note that parameters can be given a default value if they are not passed, or passed with an undefined value.

function someFunc(a="Useful", b="Angle") {
	// "UsefulAngle"
	console.log(a + b);
}

someFunc(undefined);
Loading Comments