JavaScript array indices start at 0, not 1. The .push() method adds an element at the end of the array, which in the case of an empty array (as yours is when your loop begins) will be array element 0.

Your loop inserts the value 1 at array index 0, the value 2 at array index 1, and so forth up to the value 10 at array index 9.

Each of your console.log(ar[i]) statements is trying to log a value from an index one higher than the highest element index, and those elements will always be undefined. So the console logs the value undefined ten times.

You can log the last element of an array like this:

console.log(ar[ar.length-1]);

Or in your case where you (now) know that i will be one higher than the index that .push() used:

console.log(ar[i-1]);
Answer from nnnnnn on Stack Overflow
๐ŸŒ
freeCodeCamp
forum.freecodecamp.org โ€บ javascript
Why is my array undefined, please help - JavaScript - The freeCodeCamp Forum
November 19, 2020 - What should I do to make my array not undefined? I used a for loop to place all my buttons in the array. I used the value 1 to my class list to get the 2nd element of my array. The console says undefined. Here is my codeโ€ฆ
๐ŸŒ
Reddit
reddit.com โ€บ r/learnjavascript โ€บ checking whether an array element is undefined
r/learnjavascript on Reddit: Checking whether an array element is undefined
September 6, 2022 -

If I am accessing an index of an array based on a variable, I would first want to check that the index exists.

My understanding is that if I try to access an index outside of the array's range, I will get a value of 'undefined.' So,

(typeof array[i] === 'undefined')

should return true if array[i] does not exist.

Would it also be possible, because undefined is falsey, to get the same result with

!array[i]

?

Edit: Thanks for the help!

๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ javascript-array-undefined-element-count
JavaScript - array undefined element count
Given an array that may contain undefined values, we need to count how many elements in the array are defined (i.e., not undefined). ... The filter() method is a built-in JavaScript array method that allows you to create a new array by applying a condition.
๐ŸŒ
SitePoint
sitepoint.com โ€บ javascript
Array map returning array of undefined values - JavaScript - SitePoint Forums | Web Development & Design Community
September 26, 2022 - I am iterating over a couple of JSON arrays of objects and comparing properties to add a property from one to the other. It is returning an array with all undefined values. I am not sure why, any suggestions? let urls = [facultyBiosJSON, facultyDirectoryJSON]; async function getJson() { let facultyArray; const [ data1, data2 ] = await Promise.all([ fetch(urls[0]).then(response => response.json()), fetch(urls[1]).then(response => response.json()) ]); facultyA...
๐ŸŒ
Codecademy
codecademy.com โ€บ forum_questions โ€บ 50a058d079a66f5c4f00050e
Getting an undefined array index in my hand... | Codecademy
The error I am getting is: "TypeError: cardsInHand[i] is undefined". I believe it is occurring in the portion of the code broke out below.... I am no...
๐ŸŒ
Dmitri Pavlutin
dmitripavlutin.com โ€บ 7-tips-to-handle-undefined-in-javascript
7 Tips to Handle undefined in JavaScript
March 23, 2023 - Both special values imply an empty state. undefined represents the value of a variable that hasn't been yet initialized, while null represents an intentional absence of an object.
Find elsewhere
๐ŸŒ
SitePoint
sitepoint.com โ€บ javascript
JS Array is undefined - JavaScript - SitePoint Forums | Web Development & Design Community
November 19, 2016 - Hi, this is from one JS Ninja book (which i like very much!). However, the array in this function is not being defined as such, and the push method is not working. not sure what the problem is? function makeHero(event) { event.preventDefault(); var hero = form.name.value; hero.realName = form.realName.value; var hero.powers = []; console.log(hero.powers); //undefined for (i = 0; i
Top answer
1 of 2
11

So from what I could tell, it's calling Array() as if it was passed 10 arguments, but since it doesn't define any of those "integer properties", it's as if it was passed 10 undefined arguments. Is that correct?

Yes, exactly. It's doing this:

var arr = Array(undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined);
var barr = new Array(10);
console.log(barr);

...

console.log(arr.map(function(item) { return 'hi';}));
console.log(barr.map(function(item) { return 'hi';}));

I wanted to know why the map function didn't work for the second one.

Because map, forEach, and similar only visit properties that actually exist. As you said, there's a big difference between.

var arr = Array(undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined);
// Or `var arr = Array.apply(null, {length: 10});

and

var barr = new Array(10);

In the first example, arr has 10 entries, each of which has the value undefined. In the second example, barr has no entries and a length of 10. So in the first one, map will visit the properties, because they exist. In the second one, it won't, because they don't.

Recall that standard arrays in JavaScript aren't really arrays at all (disclosure: that's a post on my blog), they're objects with some special behavior. As such, they're inherently sparse:

var a = [];
a.length = 10000;

a doesn't have 10,000 entries. It has no entries. It's just that its length property is 10000.

You can tell whether the property exists by using hasOwnProperty or in. Compare:

var barr = new Array(10);
console.log(barr.hasOwnProperty(0)); // false
console.log(0 in barr);              // false

to:

var arr = Array.apply(null, {length: 10});
console.log(arr.hasOwnProperty(0));  // true
console.log(0 in arr);               // true

And Array.apply works because it asks {length: 10} what its property 0 is, receives undefined, and so assigns undefined to the property 0 of the array it's constructing, and so on. Is my reasoning correct?

Yes, although to be clear, it's apply that's asking what property 0 is, and then it's using that as the first argument when calling Array. It's Array that then takes the first argument's value and assigns it to the 0 property on the array it's creating.

And is there really no less hackish way to define an array which contains undefined integer properties for each index within its range, rather than having no integer properties at all?

Only slightly: ES2015 adds Array.from, which accepts an array-like object and returns a true array (optionally mapping the entries). So that would be:

var arr = Array.from({length:10});

It's rare to need to do that, as opposed to simply a = new Array(bigNumberHere); or a = []; a.length = bigNumberHere. E.g., many times you don't care if the property doesn't exist or exists with the value undefined. Sometimes you do, but to give you perspective, I've been writing JavaScript professionally for 20 years, fairly intensively the last 8, and I've probably cared, oh, once or twice, tops.

You mentioned that in the specific case you were dealing with, it was combined with map, so Array.from would take the place of both:

var arr = Array.from({length: 10}, function() { return "hi"; });

...yields

["hi", "hi", "hi", "hi", "hi", "hi", "hi", "hi", "hi", "hi"]

Although Array.from is new in ES2015, it can be shimmed/polyfilled on older JavaScript engines.

2 of 2
1

Is that correct?

Yes

you can also use any kind of object which is array-like, so in practice this means it's going to have a property length and integer properties in the range (0...length).

It says that you can pass a duck-type of an array: an object that has a sort of interface:

  1. a length property (for iteration)
  2. optional: some integer properties (the values)

This will be treated as an Array. So passing a { length: 10 } is like pass a real array [undefined,undefined,undefined,..] where each index is created and has value undefined.

So the first code row:

var arr = Array.apply(null, {length: 10});

is interpreted as:

var arr = Array(undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined)

So my current guess is that arr is an array which contains as integer properties 10 variables which each have the value of undefined and barr is an array which, although it has a length of 10, has no integer properties.

Yes.

var test = Array(10);

it outputs: [undefined x10] <-- no indexes, only a simple property 'length' unaligned with the real content, but useful for retrieve it and do some size condiderations.

test[2] = undefined;

it outputs: [undefined x2, undefined, undefined x7] <-- no indexes except for the position '2' that has a value: undefined.

๐ŸŒ
Reddit
reddit.com โ€บ r/learnprogramming โ€บ [javascript] array has undefined values, but every value that's pushed is defined
r/learnprogramming on Reddit: [JavaScript] Array has undefined values, but every value that's pushed is defined
March 14, 2024 -

I've been working on this memory game for college. Its a "match the cards" style of game. You have a grid of playing cards, you need to flip them and find the pairs.

I have a function, pickCards() that loops a fixed number of times. Each iteration, it selects a random card from the array and adds it to an array "cardsPicked". Below is the code for the function. I've removed some stuff to make it more readable (the issue still exists in the below code).

// Picks the cards to display from all the available cards
function pickCards(allCards, numberToPick) {
let cardsPicked = [];
// Loops and appends a random card to the cardsPicked array
for(let i = 0; i < Math.floor(numberToPick/2); i++) {
let card = allCards[Math.floor(Math.random() * allCards.length)]

cardsPicked.push(card);
}
return cardsPicked;
}

If I log cardsPicked at the very end of the function, it returns an array. Occasionally (maybe 50% of the time) some of the values are undefined.

I added a console.log before the cardsPicked.push(card) to check if the card is defined, it is. The log displays the card perfectly (even when the log I've talked about above has undefined values).

The weird thing is, I also added a console.log(cardsPicked) after the cardsPicked.push(card), and it displays the cardsPicked array without any undefined elements. It's just at the end of the function that I'm getting the undefined elements.

In other words:

// Picks the cards to display from all the available cards
function pickCards(allCards, numberToPick) {
let cardsPicked = [];
// Loops and appends a random card to the cardsPicked array
for(let i = 0; i < Math.floor(numberToPick/2); i++) {
let card = allCards[Math.floor(Math.random() * allCards.length)]

console.log(card) <-- displays the card fine
cardsPicked.push(card);
console.log(cardsPicked) <-- displays no undefined values

}
console.log(cardsPicked) <-- displays with undefined values
return cardsPicked;
}

Some information that might be helpful:

  • I know this is JS, but if it were TypeScript, the allCards array is of the below type:

type Card = {
cardName: str // "Ace of Spades", "Two of Hearts", etc
cardImg: str // "img/AS.png", "img/2H.png", etc
isFlipped: bool
hasBeenFlipped: bool
}

(the Card type is just to show you the format of the allCards and cardsPicked array. I'm using JavaScript so it's not part of the code)

  • When I log the cardsPicked array (on a time it doesn't have undefined values), it logs fine. But whenever it has undefined values, I get a "-1" index inside the console (I'm using Firefox 123.0.1). It looks something like below:

Array() [ {...}, {...}, undefined, {...}, {...}]

"-1": Object {cardName...}

0: Object {cardName...}

1: Object {cardName...}

2: Object {cardName...}

3: Object {cardName...}

4: Object {cardName...}

I don't get that "-1" object when the array doesn't have undefined elements

Any help is greatly appreciated! Thank you!

๐ŸŒ
EyeHunts
tutorial.eyehunts.com โ€บ home โ€บ javascript array is undefined | example code
JavaScript array is undefined | Example code
May 29, 2023 - Use length property with isArray() method to check an array is undefined in JavaScript. Use Array some method to check array has an undefined
๐ŸŒ
W3Schools
w3schools.com โ€บ js โ€บ js_mistakes.asp
JavaScript Mistakes
If you use a named index, when accessing an array, JavaScript will redefine the array to a standard object. After the automatic redefinition, array methods and properties will produce undefined or incorrect results:
๐ŸŒ
SitePoint
sitepoint.com โ€บ javascript
TypeError: myArray[j] is undefined - JavaScript - SitePoint Forums | Web Development & Design Community
January 23, 2015 - Hi, I have the following code in which I am trying to populate a two dimensional array (myArray) using the values from an object (myObject) but I am getting the error mentioned in the post title. The error is tied to the 4th line. var myArray = []; var j = 0; for (var i in myObject) { myArray[j][0] = i; myArray[j][1] = myObject[i]; myArray[j][2] = myObject[i] * 2; /* alert(myArray[j][0] + ', ' + myArray[j][1] + ', ' + myArray[j][2]) */ j++; } When I test with alert(), only the first elem...