We saw 2 ways to create arrays in JavaScript:
2 Ways We Can Create An Array In JavaScript
We also looked at the better method.
In this article, I’ll discuss the example why it’s not a good idea to use new array() method to create arrays.
Two different ways to create numbers array:
var numbers = new Array();
var numbers = [];
Let’s create the arrays with some numbers in it:
var numbers = new Array(1,2,3,4);
var numbers = [1,2,3,4];
Its fine until this point.
Let’s access elements.
var numbers = new Array(1,2,3,4);
console.log(numbers[1]); //2
console.log(numbers.length); //4
var numbers = [1,2,3,4];
console.log(numbers[1]); // 2
console.log(numbers.length); //4
Seems perfectly fine. Right?
What if we want to create an array of prime numbers but add the numbers one by one.
Let’s add just one number “2” for now and add some numbers later on.
var numbers = new Array(2);
console.log(numbers[0]); //undefined
console.log(numbers.length); //2
var numbers = [2];
console.log(numbers[0]); // 2
console.log(numbers.length); //1
It messed up the whole plan. Didn’t it?
📌 So, when we try to create a single element array with new array(), it created the array of the size of that element but keeps the elements empty inside it.
If you are really determined to use that method then you might argue to add 2 elements and then adding other elements later on.
var numbers = new Array(2,2);
console.log(numbers[0]); //2
console.log(numbers.length); //2
var numbers = [2,2];
console.log(numbers[0]); // 2
console.log(numbers.length); //2
Yay! We did it! ✌
But Prime numbers are 2, 3, 5, 7, 11, .. and you entered a wrong number in it. So, now you would want to remove it.
Let’s try to change some elements in it.
var numbers = new Array(2,2);
numbers.pop();
numbers.push(3);
console.log(numbers[1]); //3
console.log(numbers.length); //2
var numbers = [2,2];
numbers.pop();
numbers.push(3);
console.log(numbers[1]); //3
console.log(numbers.length); //2
Works just fine.
So, if you plan ahead and keep the problem in mind, you might avoid the problem.
But if you’re going to create an array using new array() method, you might run into problems.
Like this example,
var numbers = new Array(2);
numbers.push(3);
console.log(numbers[1]); //undefined
console.log(numbers.length); //3
var numbers = [2];
numbers.push(3);
console.log(numbers[1]); //3
console.log(numbers.length); //2
array create numbers