Default Parameters in Javascript

const greetings = (name) => {
console.log(`Hello, ${name}`);
}
greetings(); //Output: Hello, undefined
const greetings = (name) => {
const nameVal = (typeof name !== "undefined") ? name: "World";
console.log(`Hello, ${nameVal}`);
}
greetings(); //Output: Hello, World
//Or like using logical OR operator
const greetings = (name) => {
console.log(`Hello, ${name || "World"}`);
}
greetings(); //Output: Hello, World
//Or like this if the parameter is being used in multiple places in the function body
const greetings = (name) => {
const nameVal = name || "World";
console.log(`Hello, ${nameVal}`);
}
greetings(); //Output: Hello, World
//This is how default values can be given to the function parameters
const greetings = (name = "World") => {
console.log(`Hello, ${name}`);
}
greetings(); //Output: Hello, World
const greetings = (greet = "Hello", name = "World") => {
console.log(`${greet}, ${name}`);
}
greetings(); //Output: Hello, World
greetings("Hey", "John"); //Output: Hey, John
greetings(undefined, "John"); //Output: Hello, John

Passing falsy values

The default value in the function will be assigned only if the passed value is undefined and not for any falsy values. Let’s see the examples for the same

const print = (val = "Tada") => {
console.log(`Argument Value: ${val}`);
}
print(''); //Output: Argument Value: ''
print(null); //Output: Argument Value: null
print(); //Output: Argument Value: Tada

Destructured parameter with default value

Not only primitive values, but we can also for objects and arrays we can give default values

const greet = ({name} = {name: "John"}) => {
console.log(`Hello, ${name}`);
}
greet({name: "JavaScript"}); //Output: Hello, JavaScript
greet(); //Output: Hello, John

--

--

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