What Is Array Literal Notation in JavaScript and When Should You Use It

What is array literal notation in javascript and when should you use it?

array literal notation is where you define a new array using just empty brackets. In your example:

var myArray = [];

It is the "new" way of defining arrays, and I suppose it is shorter/cleaner.

The examples below explain the difference between them:

var a = [],            // these are the same
b = new Array(), // a and b are arrays with length 0

c = ['foo', 'bar'], // these are the same
d = new Array('foo', 'bar'), // c and d are arrays with 2 strings

// these are different:
e = [3], // e.length == 1, e[0] == 3
f = new Array(3); // f.length == 3, f[0] == undefined

Reference: What’s the difference between “Array()” and “[]” while declaring a JavaScript array?

Use the array literal notation [] for var os_map = {}

The offending line:

var os_autoload_inputs = new Array('searchInput', 'searchInput2',
'powerSearchText', 'searchText');

JSLint does not expect to see new Array constructor, you should use [] instead:

var os_autoload_inputs = ['searchInput', 'searchInput2',
'powerSearchText', 'searchText'];

Why? :

1, Crockford doesn't like new.

2, The Array object could be overridden:

Array = {};
new Array(); // TypeError: Array is not a constructor

3, Usage inconsistencies, e.g.:

var a = new Array(5); // empty 5 elements array
var b = [5]; // 1 element array containing the 5 number on index 0

See also:

  • What’s the difference between “Array()” and “[]” while declaring a JavaScript array?
  • What’s wrong with var x = new Array();

In javascript, when to use object literal and when to use array?

The sample doesn't really compare objects and arrays. You're just adding a needless layer by putting an object in the first element of an array.

Use an object when you have to refer to something by name.

var obj = {}

//3 ways of doing the same thing:

var obj.newName = 'bob';

var obj['newName'] = 'bob';

var name = 'newName';
var obj[name] = 'bob';

The 2nd style isn't really necessary and might actually be a touch slower to access than the 1st but it helps you understand how the 3rd can be useful. Or you could have done the following outright:

var obj = { newName:'bob' }

If you want a bunch of names in an object, it would get a bit silly:

var obj = { newName:'bob', anotherNewName:'sue', yetAnotherNewName:'billy' }

obj.newName === 'bob'
obj.anotherNewName === 'sue'
//etc...

That's what arrays are for.

var listOfNewNames = ['bob','sue','billy']
listOfNewNames[0] === 'bob'
listOfNewNames[1] === 'sue'
//etc...

Of course, nothing prevents you from assigning an array to an object property:

obj { listOfNewNames:['bob','sue','billy'] }

obj.listOfNewNames[0] === 'bob'

Or, as demonstrated above, multiple objects in an array:

var listOfMonsters = [
{ monsterName:'Grarrr',eats:'people' },
{ monsterName:'Wadsworth',eats:'other monsters'}
];

listOfMonsters[1].monsterName === 'Wadsworth'

Objects are typically more about keeping groups of related values and methods together for ease of reference. Arrays are just a list of stuff that all can typically be assumed to apply to or derive from the same thing.

How to avoid the use the array literal notation jslint error in the following javascript code

Try this:

if (!Number.prototype.toZeroPaddedString) {
Number.prototype.toZeroPaddedString = function (count) {
"use strict";
var str = this.toString();
var ary = [];
ary.length = count + 1 - str.length;
return ary.join('0') + str;
};
}

In JavaScript, why is [ ] preferred over new Array();?

Brevity

It has less bytes to transfer over the wire, less bytes to interpret, less mental resources to parse it.

Less is more.

Consistency

What is the difference between these two lines of code?

var arr = [5];
var arr = new Array(5);

According to here new Array(5); will not return an array with a 5 in it, instead it will return a 5 element array, with all the elements being undefined. Whereas these two lines return identical arrays.

var arr = [5,6];
var arr = new Array(5,6);


Related Topics



Leave a reply



Submit