Code-style: Is the inline initialization of JS objects in order?

I often find that I use built-in initialization (see the example below), especially in the switch statement, when I do not know which loop cycle will get into. It’s easier for me to read than statements.

But is this good practice or will it have 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 site to get coding style tips?

+4
source share
2 answers

Another widely used pattern for this is the use of the Logical OR || (a little more readable than your ternary IMHO):

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

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

It is safe to use it when you expect an object, since these false values ​​are null , undefined , NaN , 0 , a string of zero length and, of course, false .

It is useful for me to set default values ​​for function arguments, when, of course, any of the false values ​​is expected as a valid function:

 function test (arg1) { arg1 = arg1 || "default value"; //.. } 
+7
source

Why not just declare it outside the loop?

 var o = {}; for (var i in array) { o[array[i]] = 1; } 

Otherwise, no, I do not see a problem with what you are doing.

+7
source

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


All Articles