Вопрос

I have a question regarding setting default values for variables inside functions. I know there are several posts regarding how to do this however I'm interested in this alternative method and whether anyone can explain to me the pro's/con's of using it particularly as the JSBIN compiler is flagging an error...

Line 2: void 0 === data && (data = 20); --- Expected an assignment or function call and instead saw an expression.

New/Alternative Method

var a = function(data) {
  void 0 === data && ( data = 20 );

  return data;     
};

Current Method using typeof operator

var b = function(data) {
  data = typeof data === "undefined" ? data = 30 : data;

  return data;   
};
Это было полезно?

Решение 2

Since void 0 is undefined. Than this:

void 0 === data && ( data = 20 );

Is a very goofy way of writing this code:

if (data === undefined)
  data = 20

So executed first comparison void 0 === data and if it is true it will execute the right side of the condition which assigns 20 to the data.

The code bellow basically assigns data variable a value 30 when data is undefined. Though again this code is pretty goofy, the reason being is that you don't need to set data = 30 in the true branch, you can just return 30... this code works because when you assign a varaible a vlue the result of the assignment is the value itself so this is what happens here, operation data = 30 returns 30, but you could just write data = typeof data === "undefined" ? 30 : data;

var b = function(data) {
  data = typeof data === "undefined" ? data = 30 : data;
  return data;   
};

The best way I think would be the following:

var b = function (data) {
  data = data || 30;
}

Другие советы

I have never seen it written that way, I doubt it will take off. Developers used to use void 0 in place of undefined because undefined was once a writable attribute of the window object. With newer browsers, this has not been the case for a long while now. The only reason you'd write it like that now is to stroke your own ego and feel superior to others who may not know the meaning behind void 0.

All of the methods have various pros and cons --

Here is the method I like:

function hasOptionalParams(p1, p2 p3) {
 if (arguments.length === 0) {  
   p1 = "default";
  }

 if (arguments.length === 1) {  
   p2 = "default";
  }

 if (arguments.length === 2) {  
   p3 = "default";
  }


}

EDIT: More Details

I like this method for a number of reasons.

  • It is the absolute more clear for someone new to JavaScript. I work on a team and I never know who will be working on the code next and what their skill level is.
  • This truly does catch arguments that are not passed in, as opposed to someone who purposefully passes a null, undefined or 0
  • I can set multiple behaviors. I can set p2 and p3 to be different if only p1 is passed.
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top