setting a default value to an undefined variable in javascript

≯℡__Kan透↙ 提交于 2019-12-04 05:01:42

Well the most important thing to learn here is if a variable is undefined you, by default, do not have any methods available on it. So you need to use a method that can operate on the variable, but is not a member/method of that variable.

Try something like:

function defaultValue(myVar, defaultVal){
    if(typeof myVar === "undefined") myVar = defaultVal;
    return myVar;
}

What you're trying to do is the equivalent of this:

undefined.prototype.defaultValue = function(val) { }

...Which for obvious reasons, doesn't work.

Elias Van Ootegem

Why not use the default operator:

function someF(b)
{
    b = b || 1;
    return b;
}

Job done! Here's more info about how it works.

Just as a side-note: your prototype won't work, because you're augmenting the String prototype, whereas if your variable is undefined, the String prototype doesn't exactly apply.

To be absolutely, super-duper-sure that you're only switching to the default value, when b really is undefined, you could do this:

var someF = (function(undefined)//get the real undefined value
{
    return function(b)
    {
        b = b === undefined ? 1 : b;
        return b;
    }
})(); // by not passing any arguments

While the two answers already provided are correct, the language has progressed since then. If your target browsers support it, you can use default function parameters like this:

function greetMe(greeting = "Hello", name = "World") {
  console.log(greeting + ", " + name + "!");
}

greetMe(); // prints "Hello, World!"
greetMe("Howdy", "Tiger"); // prints "Howdy, Tiger!"

Here are the MDN docs on default function parameters.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!