org.sonar.l10n.javascript.ArrayAndObjectConstructors.html Maven / Gradle / Ivy
Use Array and Object literals instead of Array and Object constructors.
Array constructors are error-prone due to their arguments :
// Length is 3.
var a1 = new Array(x1, x2, x3);
// Length is 2.
var a2 = new Array(x1, x2);
// If x1 is a number and it is a natural number the length will be x1.
// If x1 is a number but not a natural number this will throw an exception.
// Otherwise the array will have one element with x1 as its value.
var a3 = new Array(x1);
// Length is 0.
var a4 = new Array();
Because of this, if someone changes the code to pass 1 argument instead of 2 arguments, the array might not have the expected length.
To avoid these kinds of weird cases, always use the more readable array literal :
var a = [x1, x2, x3];
var a2 = [x1, x2];
var a3 = [x1];
var a4 = [];
Object constructors don't have the same problems, but for readability and consistency object literals should be used.
var o = new Object();
var o2 = new Object();
o2.a = 0;
o2.b = 1;
o2.c = 2;
o2['strange key'] = 3;
Should be written as :
var o = {};
var o2 = {
a: 0,
b: 1,
c: 2,
'strange key': 3
};
© 2015 - 2025 Weber Informatics LLC | Privacy Policy