Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

code-style: Is inline initialization of JS objects ok?

I often find myself using inline initialization (see example below), especially in a switch statement when I don't know which case loop will hit. I find it easier to read than if statements.

But is this good practice or will it incur side-effects or a performance hit?

for (var i in array) {
    var o = o ? o : {};  // init object if it doesn't exist
    o[array[i]] = 1;     // add key-values
}

Is there a good website to go to get coding style tips?

like image 387
michael Avatar asked Dec 10 '22 17:12

michael


1 Answers

Another commonly used pattern to do the same, is the use of the Logical OR || operator (a little bit more readable than your ternary IMHO):

//...
var obj = o || {};

This operator will return its second operand if the first one evaluates to false, otherwise it will return the first one.

Is safe to use it when you expect an object, since those falsy values are null, undefined, NaN, 0, a zero-length string, and of course false.

I find it useful to set default values on function arguments, when of course any of the falsy values are expected as valid by the function:

function test (arg1) {
  arg1 = arg1 || "default value";
  //..
}
like image 73
Christian C. Salvadó Avatar answered Feb 04 '23 01:02

Christian C. Salvadó