Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change array size by just adding element and no push javascript

I know the universal way of changing an array's size is to use .push().

However, today I saw a piece of code in angularJS that does something like this:

var service = {
   pages: [],
   doSmth: doSmth
};

doSmth();

function doSmth() {
   service.pages[1] = "abc";
   service.pages[5] = "def";
}

I ran the debugger on the browser and found that before doSmth() is called, pages[1] is undefined, but after that, pages[1] is assigned the value without any error.

How is this possible?

like image 970
PTN Avatar asked Nov 24 '15 20:11

PTN


People also ask

Can you change the size of an array in JavaScript?

Change array size by just adding element and no push javascript.

Can you change the size of an array after creation?

Arrays can either hold primitive values or object values. An ArrayList can only hold object values. You must decide the size of the array when it is constructed. You can't change the size of the array after it's constructed.

What is the opposite of push () in JavaScript?

The opposite of push() (as the question is titled) is pop() .


Video Answer


2 Answers

That's just the magic that JavaScript allows. If you come from a language like Java or C, this may seem like a weird idea, but you can set the value of any index in the array at any time, and the array will expand to that size!

Consider:

var t = [];
t.length === 0;
t[10000] = 'value';
t.length === 10001;

JavaScript just handles this behind the scenes. It's worth mentioning that this behavior is not specific to JavaScript. This is seen a bit in other interpreted languages as well. Ruby, for example, allows you to do the same.

Additionally in JavaScript, length is a writeable attribute of arrays, so you can easily truncate or clear an entire array:

var t = [1];
t[4] = 0;
t === [1, undefined, undefined, undefined, 0];
t.length = 2;
t === [1, undefined];
t.length = 0;
t === [];

Setting the length to 0 is one of the fastest and simplest ways to clear an array. It might not be the most intuitive solution, but it's my go-to.

like image 136
Brennan Avatar answered Oct 20 '22 00:10

Brennan


An array in JavaScript is just an object with some special properties. Essentially, they are just objects with positive, integer property names. There are some other key differences, but the idea is that you could do this:

var obj = { };
obj['1'] = 'abc';

So you can do the same with an array.

However! You shouldn't. Modern JavaScript engines usually optimize arrays by backing them with fast, native implementations. By setting indexes that are not currently allocated will de-optimize your code into something more like an object, which is much slower.

like image 41
TbWill4321 Avatar answered Oct 20 '22 01:10

TbWill4321