Mcope
Mcope

Reputation: 781

When creating a Javascript function, should I check if parameter was undefined?

When creating a function like this:

function (var1) {
    if (!var1) var1 = 'Hello'
    return var1 + ' World'
}

Is it acceptable for me to check if var1 is unset by simply doing if (!var1)?

Or should I always do an undefined check like if (var1 === undefined) ?

I know both will work. I just want to know what the true "professional" way of doing this is.

Upvotes: 0

Views: 77

Answers (2)

Lewis
Lewis

Reputation: 14866

If you're looking for a better solution for the default parameters issue, then here they are.

Common approach

function(var1){
    //0,'',undefined,null,NaN and false will be fallbacked to 'hello'
    //use `typeof` operator if you want to check for
    //a specific falsy value or data type
    var1 = var1 || 'hello';
    return var1+' World';
}

ES6 approach (be careful with the compatibility issue)

function(var1='hello'){
    return var1+' World';
}

Upvotes: 0

deceze
deceze

Reputation: 522032

This depends on whether you simply expect any truthy value (not 0, false, null, NaN or undefined) or explicitly need to distinguish between these various falsey values. If there's a meaningful difference between false and undefined, check for undefined explicitly. If any falsey value is equally falsey to you, don't bother.

The strength of a dynamic type system like Javascript's is that you do not always have to worry about types and can lump a bunch of different values into the same category (like falsey or truthy), which can save you a bit of code. You just need to know what is what and when the situation demands more explicit checks.

You should also check for undefined like so:

typeof var1 == 'undefined'

The typical Javascript idiom for this kind of default argument would also be:

var1 = var1 || 'Hello';

Upvotes: 3

Related Questions