最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Idiomatic way to set default value in JavaScript - Stack Overflow

programmeradmin7浏览0评论

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?

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?

Share Improve this question edited Oct 4, 2020 at 10:01 Alex 1,5801 gold badge15 silver badges27 bronze badges asked Feb 3, 2009 at 2:30 MikeMike 1,62316 silver badges29 bronze badges 1
  • myParam = myParam || (myObj || {}).myParam || 10 – Hafthor Commented Sep 24, 2015 at 18:45
Add a ment  | 

2 Answers 2

Reset to default 17

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);

I think the other answers have proven that there are a whole bunch of ways a one-liner can fail here. My version below is perhaps more readable, and doesn't explicitly test for object/property existence, but isn't much shorter:

function MyFunc(myParam){
    if (!myParam){
        try{
            myParam = myObj.myParam;
        }
        catch(e){
            myParam = 10;
        }
    }
}
发布评论

评论列表(0)

  1. 暂无评论