Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Idiomatic way to set default value in JavaScript

Tags:

javascript

What would be the most idiomatic way to do the following in JavaScript:

If myParam is not passed into MyFunc by the caller, then I want to set it to a default value. But first I want to try and get it from another object, which may not yet exist:

function MyFunc(myParam) {

    if (!myParam) {
        if (!myObj) {
            myParam = 10;
        }
        else {
            myParam = myObj.myParam;
        }
    }
 
    alert(myParam);
}

I started to write:

myParam = myParam || myObj.mParam || 10

but realized that if myObj does not exist then this would fail. I might guess the following:

myParam = myParam || (myObj && myObj.mParam) || 10

It might even work. But is it the best way?

How would, for example, John Resig do it?

like image 497
Mike Avatar asked Feb 03 '09 02:02

Mike


People also ask

How do you assign default values to variables in JavaScript?

The OR Assignment (||=) Operator The logical OR assignment ( ||= ) operator assigns the new values only if the left operand is falsy. Below is an example of using ||= on a variable holding undefined . Next is an example of assigning a new value on a variable containing an empty string.

What is the default value of a variable in JavaScript?

In JavaScript, function parameters default to undefined . However, it's often useful to set a different default value.

How can we set default value to the variable?

You can set the default values for variables by adding ! default flag to the end of the variable value. It will not re-assign the value, if it is already assigned to the variable.

Which is the correct way to give default value to the parameter A in a function F?

Default function parameters allow formal parameters to be initialized with default values if no value or undefined is passed. function foo(a, b) { a = typeof a !==


1 Answers

If myObj is a global it needs to reference the window object, otherwise it will throw an error if myObj is undefined.

myParam = myParam || (window.myObj ? window.myObj.mParam : 10);

or

myParam = myParam || (window.myObj && window.myObj.mParam) || 10;

This works as well:

myParam = myParam || ((typeof myObj !== "undefined") ? myObj.mParam : 10);
like image 93
Luca Matteis Avatar answered Sep 28 '22 11:09

Luca Matteis