Array creation is homogenous and predictable, or is it a hack?
TL;DR: Be very careful with Javascript Arrays.
Problems
- The Least surprise principle violation
Solutions
Be as declarative as possible
Avoid creating Arrays with one argument.
Context
Javascript has a lot of magic tricks.
Knowing them makes some developers proud and a sense of belonging to juniors.
A language should be intuitive, homogeneous, predictable, simple, and pure.
Sample Code
Wrong
const arrayWithFixedLength = new Array(3);
console.log(arrayWithFixedLength); // [ <5 empty items> ]
console.log(arrayWithFixedLength[0]); // Undefined
console.log(arrayWithFixedLength[1]); // Undefined
console.log(arrayWithFixedLength[3]); // Undefined
console.log(arrayWithFixedLength[4]); // Undefined
console.log(arrayWithFixedLength.length); // 3
Right
const arrayWithTwoElements = new Array(3, 1);
console.log(arrayWithTwoElements); // [ 3, 1 ]
console.log(arrayWithTwoElements[0]); // 3
console.log(arrayWithTwoElements[1]); // 1
console.log(arrayWithTwoElements[2]); // Undefined
console.log(arrayWithTwoElements[5]); // Undefined
console.log(arrayWithTwoElements.length); // 2
const arrayWithTwoElementsLiteral = [3,1];
console.log(arrayWithTwoElementsLiteral); // [ 3, 1 ]
console.log(arrayWithTwoElementsLiteral[0]); // 3
console.log(arrayWithTwoElementsLiteral[1]); // 1
console.log(arrayWithTwoElementsLiteral[2]); // Undefined
console.log(arrayWithTwoElementsLiteral[5]); // Undefined
console.log(arrayWithTwoElementsLiteral.length); // 2
Detection
[X] Automatic
We can check for the notation with one argument and flag it as a warning.
Tags
- Smart
Conclusion
Many "modern" languages are full of hacks to make life easier for programmers but are a source of potential undiscovered bugs.
Relations

Code Smell 06 - Too Clever Programmer
Maxi Contieri ⭐⭐⭐ ・ Oct 25 '20 ・ 2 min read

Code Smell 69 - Big Bang (JavaScript Ridiculous Castings)
Maxi Contieri ⭐⭐⭐ ・ May 4 '21 ・ 2 min read

Code Smell 93 - Send me Anything
Maxi Contieri ⭐⭐⭐ ・ Oct 13 '21 ・ 2 min read
Disclaimer
Code Smells are just my opinion.
Credits
Photo by Ryan Quintal on Unsplash
Originally on this tweet:
![]()
Tapas Adhikary@tapasadhikary
🪐 Tricky Fact - JavaScript Array Constructor
- When you pass a single parameter to the Array constructor, the array's length is set to that number. The elements will still have empty slots.
- When you pass multiple parameters, an array gets created with given elements!
See 👀11:09 AM - 02 Feb 2023
When someone says, "I want a programming language in which I need only say what I want done," give him a lollipop.
Alan J. Perlis

Software Engineering Great Quotes
Maxi Contieri ⭐⭐⭐ ・ Dec 28 '20 ・ 13 min read
This article is part of the CodeSmell Series.
Top comments (0)