Setting default value of undefined variable in javascript

Ideally, I want to write something like:

function a( b ) { b.defaultVal( 1 ); return b; } 

The purpose of this is that if b is any specific value, b will remain that value; but if b undefined, then b will be set to the value specified in the defaultVal() parameter, in this case 1 .

Is it possible?

I was thinking of something like this:

 String.prototype.defaultVal=function(valOnUndefined){ if(typeof this==='undefined'){ return valOnUndefined; }else{ return this; } }; 

But I did not succeed in applying this logic to any variable, especially to undefined variables.

Does anyone have any thoughts on this? It can be done? Or am I barking the wrong tree?

+4
source share
3 answers

Well, the most important thing is to find out here whether the variable is undefined , by default you have no methods available. Therefore, you need to use a method that can work with a variable, but is not a member / method of this variable.

Try something like:

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

What you are trying to do is equivalent to this:

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

... Which for obvious reasons does not work.

+5
source

Why not use the default operator:

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

Work is done! Here's more on how this works.

As a side note: your prototype will not work because you are increasing the String prototype, whereas if your variable is undefined, the String prototype is not applied exactly.

To be absolutely sure that you are only switching to the default when b really undefined, you can 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 
+11
source

Although the two answers that have already been provided are correct, the language has been advancing ever since. If your target browsers support it, you can use the default function parameters as follows:

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

Here are the MDN documents for the default function parameters.

0
source

Source: https://habr.com/ru/post/1434026/


All Articles