DEV Community

Cover image for Javascript default parameter for null and undefined
Sajidur Rahman Shajib
Sajidur Rahman Shajib

Posted on • Edited on

Javascript default parameter for null and undefined

Hello Devs,
Are you facing any problem when you pass null or undefined in a function as a parameter? May be you have faced this problem or maybe you haven't.On the other hand, maybe you know the solutions in many ways.

In this post I want talk about how to pass default value in case of null and undefined. Hopefully, it will help somebody.

Oh Enough Introduction...

Let's get to the main point. Take a function called sayHi() which takes a parameter and print that parameter. that's it.

const sayHi = (greeting) => {
    console.log(greeting)
}

sayHi('Hi')

//your@console:~$ Hi
Enter fullscreen mode Exit fullscreen mode

Now, if I don't give any parameter what will be happen? Let's check...

const sayHi = (greeting) => {
    console.log(greeting)
}

sayHi()

//your@console:~$ undefined
Enter fullscreen mode Exit fullscreen mode

So in this case if we set a default parameter in the function,our problem will be solved.

const sayHi = (greeting='Hi') => {
    console.log(greeting)
}

sayHi()

//your@console:~$ Hi
Enter fullscreen mode Exit fullscreen mode

So undefined related problem solved...!

Now ,let's check again if I put a null parameter what will happen?

const sayHi = (greeting='Hi') => {
    console.log(greeting)
}

sayHi(null)

//your@console:~$ null
Enter fullscreen mode Exit fullscreen mode

Ok, that's the problem we don't need a null value as our output. Default value will be used when the parameter is undefined. However, if we put null here, our default parameter can't prevent it. Because undefined!==null

So how should we handle this?

Now we need nullish coalescing operator ??

console.log(12 ?? "not found") // 12
console.log(0  ?? "not found") // 0

console.log("Sajid" ?? "not found") // "Sajid"
console.log(""     ?? "not found") // ""

console.log(true  ?? "not found") // true
console.log(false ?? "not found") // false

console.log(undefined ?? "not found") // "not found"
console.log(null      ?? "not found") // "not found"
Enter fullscreen mode Exit fullscreen mode

If the left value is null or undefined , then the right value will be assigned. That's how nullish coalescing operator works.

So out solution will be

const sayHi = (greeting) => {
    const hi = greeting ?? 'Hi'
    console.log(hi)
}

sayHi(null)

//your@console:~$ Hi
Enter fullscreen mode Exit fullscreen mode

You can also use || or operator which can be problematic if your left value contains "" or 0 or false

Something like that,

console.log("" || "not found") // "not found"
console.log(0 || "not found") // "not found"
Enter fullscreen mode Exit fullscreen mode

So coalescing operator is our best solution if we want to ignore only undefined and null as parameter.

So Dev, what do you think about this operator?

Top comments (0)