# Code Smell 196 - Javascript Array Constructors


> TL;DR: Be very careful with Javascript Arrays.

# Problems

- The Least surprise principle violation

# Solutions

1. Be as declarative as possible.

2. 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

[Gist Url]: # (https://gist.github.com/mcsee/5d0644c120630d637c9649d7c92805c7)
```javascript
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

[Gist Url]: # (https://gist.github.com/mcsee/a7f4c59210257cb279efc6747b4e3122)
```javascript
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

%[https://maximilianocontieri.com/code-smell-06-too-clever-programmer]

%[https://maximilianocontieri.com/code-smell-69-big-bang-javascript-ridiculous-castings]

%[https://maximilianocontieri.com/code-smell-93-send-me-anything]

# Disclaimer

Code Smells are just my [opinion](https://maximilianocontieri.com/i-wrote-more-than-90-articles-on-2021-here-is-what-i-learned).

# Credits

Photo by [Ryan Quintal](https://unsplash.com/@ryanquintal) on [Unsplash](https://unsplash.com/photos/US9Tc9pKNBU)
  
Originally on this tweet:

%[https://twitter.com/mcsee1/status/1621348702907502593]
  
* * *

> 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_
 
%[https://maximilianocontieri.com/software-engineering-great-quotes]

* * *

This article is part of the CodeSmell Series.

%[https://maximilianocontieri.com/how-to-find-the-stinky-parts-of-your-code]
