1
\$\begingroup\$

I know the maximum array size is 6. So what is the best practice to declare an array?

In the following code I used it like this:

<!DOCTYPE html>
<html>
<body>

<p id="demo"></p>

<script>
var marks = new Array(6);
marks = [40, 100, 1, 5, 25, 10];
document.getElementById("demo").innerHTML = marks[3];    
</script>

</body>
</html>

My understanding is that in this case, a memory location will be allocated at initialization time itself, and so while running, it will just assign the data to the array, which will provide some better performance. But if it will not take the 6 data, some memory space will be wasted.

And another way of implementation is:

<script>
var marks = []
marks = [40, 100, 1, 5, 25, 10];
document.getElementById("demo").innerHTML = marks[3];    
</script>

Here memory will be allocated dynamically when assigning the variable, so memory will not be wasted.

I know declaring an array with new() constructor is not a good practice (as mentioned here)), but if we know the maximum size, I want to know about the best practice. So what is the best practice here for declaring an array in JavaScript?

\$\endgroup\$
1
  • 1
    \$\begingroup\$ Even if this gets reopened (which I voted for) this question is still off topic as of our help center, namely: Best practices in general (that is, it's okay to ask "Does this code follow common best practices?", but not "What is the best practice regarding X?" \$\endgroup\$
    – Vogel612
    Commented Jun 27, 2014 at 9:48

1 Answer 1

2
\$\begingroup\$

Interesting question,

first off, you are worrying about the wrong things. Even if the first approach provides some better performance, (which I think unlikely), it would be premature optimization.

The right way would be simply:

var marks = [40, 100, 1, 5, 25, 10];
document.getElementById("demo").innerHTML = marks[3];

Now, from a memory perspective, I am pretty sure that the only thing happening with new Array(6); is the setting of length to 6. It does not mean that memory is allocated. If you think about that, assigning memory would be silly because JS does not know what you will put in that array, it could be an integer or it could be a really long string, or a function or an object, you get the point..

My advise is to code in an idiomatic way, simply expressing what needs to be done.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.