By interstar


2008-12-09 00:20:05 8 Comments

How do I append an object (such as a string or number) to an array in JavaScript?

30 comments

@jdecuyper 2008-12-09 00:24:28

Use the Array.prototype.push method to append values to the end of an array:

// initialize array
var arr = [
  "Hi",
  "Hello",
  "Bonjour"
];

// append new value to the array
arr.push("Hola");

console.log(arr);


You can use the push() function to append more than one value to an array in a single call:

// initialize array
var arr = ["Hi", "Hello", "Bonjour", "Hola"];

// append multiple values to the array
arr.push("Salut", "Hey");

// display all values
for (var i = 0; i < arr.length; i++) {
  console.log(arr[i]);
}


Update

If you want to add the items of one array to another array, you can use firstArray.concat(secondArray):

var arr = [
  "apple",
  "banana",
  "cherry"
];

arr = arr.concat([
  "dragonfruit",
  "elderberry",
  "fig"
]);

console.log(arr);

Update

Just an addition to this answer if you want to prepend any value to the start of an array (i.e. first index) then you can use Array.prototype.unshift for this purpose.

var arr = [1, 2, 3];
arr.unshift(0);
console.log(arr);

It also supports appending multiple values at once just like push.

@Jay 2016-01-10 00:09:38

Note the return value of .push is not the array (or a new one, like .concat), but an integer representing the array's new length.

@RST 2016-02-23 09:08:06

One other thing to notice. Don't use arr.length in the for condition, put it in a variable and use that variable in the for condition. There is no need to recalculate length on every run as this array's length is not changing.

@Robert Siemer 2016-02-25 17:57:20

@RST: don’t use for at all (use .forEach).

@RST 2016-02-25 18:29:44

@RobertSiemer Not sure what your point is. Going from for to foreach will have no impact on execution, they will both work. And there are probably even more ways to do this. I only added my comment because this answers seems to be used, and appreciated a lot while it has a flaw, especially when you have large arrays.

@Robert Siemer 2016-02-25 21:34:56

@RST, my point is: the fix is not to copy arr.length in a var, but to not use arr.length at all.

@Stijn de Witt 2016-04-03 13:31:06

I'd say the original code is just fine. There is no need whatsoever to optimize access to the length property. The interpreter does an amazing job at that itself and it will not make any difference in The Real World whether you optimize it away or not. If your array becomes so huge that optimizing .length would actually help, most probably an array is not the right data structure anymore. Using forEach has it's advantages, but it's highly doubtful that increased performance would be one of them, as the function call for each iteration incurs a cost and saves nothing.

@mikeyq6 2016-06-09 16:39:32

@RobertSiemer The length property of an array is not calculated every time you call it, it's a variable stored in the array object, which is only updated when you alter the array. So there is in fact no performance cost in including arr.length in the for condition.

@Robert Siemer 2016-06-13 16:41:31

@mikeyq6: I never argued about speed. Using .length is prone to one-off-errors. .forEach is not.

@Robert Siemer 2016-06-14 09:30:25

@mikeyq6: No, I didn’t talk about “calculate the length every iteration”. User RST did. Talk to him. – I’m against writing a for-loop at all (with.length or any other way).

@Florrie 2016-08-02 01:21:39

Why use a function call or make an extra length variable or get the length every cycle when you could just use a for...of loop?

@Mojimi 2017-09-27 17:48:22

@RobertSiemer coderwall.com/p/kvzbpa/don-t-use-array-foreach-use-for-inste‌​ad . Man, as a beginner its really hard to know who to believe haha

@Mörre 2017-12-17 09:35:06

@Mojimi As a beginner ignore any advice that is about performance questions in edge cases such as this one. Use the more expressive syntax. Over time Javascript runtimes add more and more optimizations - they will inline forEach callback functions (some of them probably already do that) and there will be no difference in the generated machine code, if the function is called often enough to be compiled instead of interpreted by the runtime. Same advice goes as for any language that isn't assembler, actually.

@Anomaly 2020-04-27 20:41:59

Concat doesn't append to the list, it creates a new one. For an approach which actually does append to the existing list, and is more performant, use the approach in the answer by Omnimike below (use push.apply or the spread operator with push).

@alex 2020-08-06 08:25:01

hello friends and thank you all for the extensive debate. in ff 68.10 esr, push and unshift worked great for me, but concat did not.

@Mαzen 2011-08-13 00:52:19

Use concat:

a = [1, 2, 3];
b = [3, 4, 5];
a = a.concat(b);
console.log(a);

@rjmunro 2011-08-03 11:46:29

If arr is an array, and val is the value you wish to add use:

arr.push(val);

E.g.

var arr = ['a', 'b', 'c'];
arr.push('d');
console.log(arr);

@CodingIntrigue 2015-06-09 14:02:48

With the new ES6 spread operator, joining two arrays using push becomes even easier:

var arr = [1, 2, 3, 4, 5];
var arr2 = [6, 7, 8, 9, 10];
arr.push(...arr2);
console.log(arr);

This adds the contents of arr2 onto the end of arr.

Babel REPL Example

@Fizer Khan 2014-03-17 16:27:46

You can use push and apply function to append two arrays.

var array1 = [11, 32, 75];
var array2 = [99, 67, 34];

Array.prototype.push.apply(array1, array2);
console.log(array1);

It will append array2 to array1. Now array1 contains [11, 32, 75, 99, 67, 34]. This code is much simpler than writing for loops to copy each and every items in the array.

@amit bakle 2016-02-12 10:15:02

This is what i required, maintain original array reference

@Mieszko 2018-10-05 09:54:00

If you are using ES6/7 you can also the ... operator instead of apply const a1 = [] const a2 = [5,6,7] const.push(...a2) edit: syntax highlight

@connectyourcharger 2019-05-03 00:10:09

I'd use array1.concat(array2) in this situation. The call to push seems unnecessary.

@Omnimike 2012-08-30 05:24:44

I think it's worth mentioning that push can be called with multiple arguments, which will be appended to the array in order. For example:

var arr = ['first'];
arr.push('second', 'third');
console.log(arr);

As a result of this you can use push.apply to append an array to another array like so:

var arr = ['first'];
arr.push('second', 'third');
arr.push.apply(arr, ['forth', 'fifth']);
console.log(arr);

Annotated ES5 has more info on exactly what push and apply do.

2016 update: with spread, you don't need that apply anymore, like:

var arr = ['first'];
arr.push('second', 'third');

arr.push(...['fourth', 'fifth']);
console.log(arr) ;

@Gabriel Littman 2014-08-20 18:45:20

best answer for appending an array of items while not creating a new array.

@Juan Mendes 2014-08-22 01:44:20

@GabrielLittman Specially because appending to an array, IMHO, should modify the array, not create a new one.

@Michael 2015-02-16 23:41:06

I like the push.apply version, would rather use Array.prototype.push.apply() though.

@see sharper 2016-03-15 04:14:59

Sometimes it's important to preserve the reference to an array - for example in AngularJs when an array is in scope on some controller and some service needs to update the data in the array for display. That's why I'm upvoting this solution.

@MK_Dev 2008-12-09 00:35:27

If you're only appending a single variable, then push() works just fine. If you need to append another array, use concat():

var ar1 = [1, 2, 3];
var ar2 = [4, 5, 6];

var ar3 = ar1.concat(ar2);

alert(ar1);
alert(ar2);
alert(ar3);

The concat does not affect ar1 and ar2 unless reassigned, for example:

var ar1 = [1, 2, 3];
var ar2 = [4, 5, 6];

ar1 = ar1.concat(ar2);
alert(ar1);

Lots of great info here.

@vbullinger 2013-07-12 22:47:49

Just making sure people catch the var ar3 = ar1.concat(ar2); part. ar1.concat(ar2) does not save the values into ar1. You have to catch it by assigning it to ar3 or back to ar1, such as: ar1 = ar1.concat(ar2);

@Stijn de Witt 2015-09-18 13:09:46

I'd say this is the wrong answer actually. The question was How do I append to an array in JavaScript?, but concat actually creates a new array. That is an important difference! Instead I'd say the answer below by Omnimike is actually the best one: Use Push.apply to push a whole array to an existing array without creating a new one.

@cameronjonesweb 2016-04-01 01:30:22

@StijndeWitt you can still append without creating a new array, as stated in the previous comment ar1 = ar1.concat(ar2); will append to ar1

@Stijn de Witt 2016-04-03 13:26:19

@cameronjonesweb Actually, what it does is create a new array with the same contents as ar1, append ar2 and then return the new array. Just leave out the assignment part (ar1 = ...) from that line of code and you'll see that the original ar1 did not in fact change. If you want to avoid making a copy, you'll need push. Don't believe me, believe the docs: "The concat() method returns a new array" First sentence in the docs for concat.

@Ade 2018-04-07 18:29:22

@StijndeWitt You're right. But, a different way to look at it though, .push only works well in adding single variables/objects, but will however mess up when it comes to appending Arrays, which ar2 above is anyways. The result of .push in the scenario will be = [ar1, [ar2]]. .concat solves that problem, but with sacrifice of speed and a new array created. To use .push properly in array appends, loop out the contained element first and push each. ar2.forEach(each => { ar1.push(each); });

@Stijn de Witt 2018-04-11 22:09:04

To append a complete array with push, use Function.prototype.apply, which allows us to specify the parameters to a function as a single array. This works because push accepts a variable number of arguments and will push all arguments passed. Array is actually a very clever object with just a couple of methods that are very versatile. Try it: var array = ['look', 'an', 'array']; var result = []; result.push.apply(result, array); console.info(result);

@Nicholas Shanks 2020-05-05 12:49:26

ar1.push(...ar2) will append all of the items in the second array to the first without creating a new array or invoking a for loop of any kind.

@Srikrushna 2018-06-28 19:01:32

Append Single Element

//Append to the end
arrName.push('newName1');

//Prepend to the start
arrName.unshift('newName1');

//Insert at index 1
arrName.splice(1, 0,'newName1');
//1: index number, 0: number of element to remove, newName1: new element


// Replace index 3 (of exists), add new element otherwise.
arrName[3] = 'newName1';

Append Multiple Elements

//Insert from index number 1
arrName.splice(1, 0,'newElemenet1', 'newElemenet2', 'newElemenet3');
//1: index number from where insert starts, 
//0: number of element to remove, 
//newElemenet1,2,3: new elements

Append array

//join two or more arrays
arrName.concat(newAry1, newAry2);
//newAry1,newAry2: Two different arrays which are to be combined (concatenated) to an existing array

@Mihail Malostanidis 2018-08-12 16:12:29

Why not arrName.push('newElemenet1, newElemenet2, newElemenet3')?

@Srikrushna 2018-08-12 17:27:04

In the push() it insert the element in last but in my example it insert the element at middle i.e. from the array index 1(as per the example)@Mihail Malostanidis

@Mihail Malostanidis 2018-08-12 20:05:04

Oh, I thought the assumption was that arrName was of length 1.

@Flavio Copes 2018-06-19 15:26:27

Append a single item

To append a single item to an array, use the push() method provided by the Array object:

const fruits = ['banana', 'pear', 'apple']
fruits.push('mango')
console.log(fruits)

push() mutates the original array.

To create a new array instead, use the concat() Array method:

const fruits = ['banana', 'pear', 'apple']
const allfruits = fruits.concat('mango')
console.log(allfruits)

Notice that concat() does not actually add an item to the array, but creates a new array, which you can assign to another variable, or reassign to the original array (declaring it as let, as you cannot reassign a const):

const fruits = ['banana', 'pear', 'apple']
const allfruits = fruits.concat('mango')
console.log(allfruits)
let fruits = ['banana', 'pear', 'apple']
fruits = fruits.concat('mango')

Append multiple items

To append a multiple item to an array, you can use push() by calling it with multiple arguments:

const fruits = ['banana', 'pear', 'apple']
fruits.push('mango', 'melon', 'avocado')
console.log(fruits)

You can also use the concat() method you saw before, passing a list of items separated by a comma:

const fruits = ['banana', 'pear', 'apple']
const allfruits = fruits.concat('mango', 'melon', 'avocado')
console.log(allfruits)

or an array:

const fruits = ['banana', 'pear', 'apple']
const allfruits = fruits.concat(['mango', 'melon', 'avocado'])
console.log(allfruits)

Remember that as described previously this method does not mutate the original array, but it returns a new array.

Originally posted at

@José Antonio Postigo 2017-02-22 12:46:18

Now, you can take advantage of ES6 syntax and just do:

let array = [1, 2];
console.log([...array, 3]);

keeping the original array immutable.

@Inconnu 2016-12-02 10:08:56

There are a couple of ways to append an array in JavaScript:

1) The push() method adds one or more elements to the end of an array and returns the new length of the array.

var a = [1, 2, 3];
a.push(4, 5);
console.log(a);

Output:

[1, 2, 3, 4, 5]

2) The unshift() method adds one or more elements to the beginning of an array and returns the new length of the array:

var a = [1, 2, 3];
a.unshift(4, 5);
console.log(a); 

Output:

[4, 5, 1, 2, 3]

3) The concat() method is used to merge two or more arrays. This method does not change the existing arrays, but instead returns a new array.

var arr1 = ["a", "b", "c"];
var arr2 = ["d", "e", "f"];
var arr3 = arr1.concat(arr2);
console.log(arr3);

Output:

[ "a", "b", "c", "d", "e", "f" ]

4) You can use the array's .length property to add an element to the end of the array:

var ar = ['one', 'two', 'three'];
ar[ar.length] = 'four';
console.log( ar ); 

Output:

 ["one", "two", "three", "four"]

5) The splice() method changes the content of an array by removing existing elements and/or adding new elements:

var myFish = ["angel", "clown", "mandarin", "surgeon"];
myFish.splice(4, 0, "nemo");
//array.splice(start, deleteCount, item1, item2, ...)
console.log(myFish);

Output:

["angel", "clown", "mandarin", "surgeon","nemo"]

6) You can also add a new element to an array simply by specifying a new index and assigning a value:

var ar = ['one', 'two', 'three'];
ar[3] = 'four'; // add new element to ar
console.log(ar);

Output:

["one", "two","three","four"]

@Phil Calvin 2017-05-24 15:17:28

For 1), this says "without modifying the original array." But that's literally what push does: it modifies the original array by pushing new elements onto it. Am I reading this wrong, or should this be edited?

@Satyapriya Mishra 2016-02-17 18:31:48

If you want to append a single value into an array, simply use the push method. It will add a new element at the end of the array.

But if you intend to add multiple elements then store the elements in a new array and concat the second array with the first array...either way you wish.

arr=['a','b','c'];
arr.push('d');
//now print the array in console.log and it will contain 'a','b','c','d' as elements.
console.log(array);

@Aditya 2018-08-22 04:53:12

You can use the push() if you want to add values e.g. arr.push("Test1", "Test2");

If you have array you can use concat() e.g. Array1.concat(Array2)

If you have just one element to add you can also try length menthod e.g. array[aray.length] = 'test';

@Ir Calif 2018-08-07 09:48:46

Appending items on an array

let fruits =["orange","banana","apple","lemon"]; /*array declaration*/

fruits.push("avacado"); /* Adding an element to the array*/

/*displaying elements of the array*/

for(var i=0; i < fruits.length; i++){
  console.log(fruits[i]);
}

@Harunur Rashid 2018-05-30 09:48:21

push() adds a new element to the end of an array.
pop() removes an element from the end of an array.

To append an object (such as a string or number) to an array use -
array.push(toAppend);

@Lior Elrom 2018-05-26 22:01:08

Append a value to an array

Since Array.prototype.push adds one or more elements to the end of an array and returns the new length of the array, sometimes we want just to get the new up-to-date array so we can do something like so:

const arr = [1, 2, 3];
const val = 4;

arr.concat([val]); // [1, 2, 3, 4]

Or just:

[...arr, val] // [1, 2, 3, 4]

@monikapatelIT 2018-06-07 21:49:10

Correct with ES6 for rest operator.

@Sanu Uthaiah Bollera 2018-01-17 10:11:36

You can use push method.

Array.prototype.append = function(destArray){
     destArray = destArray || [];
     this.push.call(this,...destArray);
     return this;
}
var arr = [1,2,5,67];
var arr1 = [7,4,7,8];
console.log(arr.append(arr1));// [7, 4, 7, 8, 1, 4, 5, 67, 7]
console.log(arr.append("Hola"))//[1, 2, 5, 67, 7, 4, 7, 8, "H", "o", "l", "a"]

@Hoque MD Zahidul 2017-10-24 10:44:14

you can do it using new javascript Es 6 feature :

// initialize array

var arr = [
    "Hi",
    "Hello",
    "Bangladesh"
];

// append new value to the array

arr= [...arr , "Feni"];

// or you can put a variable value

var testValue = "Cool";

arr = [...arr , testValue ];

console.log(arr); 

// final output  [ 'Hi', 'Hello', 'Bangladesh', 'Feni', 'Cool' ]

@Richard Matheson 2018-09-19 10:03:26

This doesn't append the value to the array, which is what the OP asked. This creates a new array, with the contents of the old array and the new elements. Really, this is Array.concat.

@Jens Roland 2010-09-29 22:40:47

Some quick benchmarking (each test = 500k appended elements and the results are averages of multiple runs) showed the following:

Firefox 3.6 (Mac):

  • Small arrays: arr[arr.length] = b is faster (300ms vs. 800ms)
  • Large arrays: arr.push(b) is faster (500ms vs. 900ms)

Safari 5.0 (Mac):

  • Small arrays: arr[arr.length] = b is faster (90ms vs. 115ms)
  • Large arrays: arr[arr.length] = b is faster (160ms vs. 185ms)

Google Chrome 6.0 (Mac):

  • Small arrays: No significant difference (and Chrome is FAST! Only ~38ms !!)
  • Large arrays: No significant difference (160ms)

I like the arr.push() syntax better, but I think I'd be better off with the arr[arr.length] Version, at least in raw speed. I'd love to see the results of an IE run though.


My benchmarking loops:

function arrpush_small() {
    var arr1 = [];
    for (a = 0; a < 100; a++)
    {
        arr1 = [];
        for (i = 0; i < 5000; i++)
        {
            arr1.push('elem' + i);
        }
    }
}

function arrlen_small() {
    var arr2 = [];
    for (b = 0; b < 100; b++)
    {
        arr2 = [];
        for (j = 0; j < 5000; j++)
        {
            arr2[arr2.length] = 'elem' + j;
        }
    }
}


function arrpush_large() {
    var arr1 = [];
    for (i = 0; i < 500000; i++)
    {
        arr1.push('elem' + i);
    }
}

function arrlen_large() {
    var arr2 = [];
    for (j = 0; j < 500000; j++)
    {
        arr2[arr2.length] = 'elem' + j;
    }
}

@yoel halb 2012-08-15 18:55:29

The question is if .length is a stored value or is calculated when being accessed, since if the latter one is true then it might be that using a simple variable (such as j) as the index value might be even faster

@Justin 2013-04-30 00:10:14

Would love to see concat() in the same test!

@Paul Draper 2014-05-26 20:07:24

I wonder how much this has changed in the past four years. (jsperf would be handy right now.)

@LessQuesar 2014-09-25 21:59:20

This type of benchmarking is interesting, but ironically not very helpful in making apps faster. The rendering loop is by far much much more expensive during any cycle. In addition these internals of the JS language are continuously being optimized by browser developers. Thats the reason for my downvote, not the interestingness of this answer. If you want faster apps, benchmark first and see what to change - 99 out of 100 times it won't be an issue like this test shows. Often its poor developer JS/CSS - not browser internals that is making it slow.

@Henrik Aronsson 2015-06-17 13:30:52

For the ease of others, I created a jsperf with @JensRoland's tests: jsperf.com/pushetc go ahead and add your own comparations and update it.

@Beejor 2015-08-13 00:35:54

I agree with LessQuesar in sticking to the builtins whenever possible. Not that micro-optimization is bad in itself, but he's right that browsers are always improving their engine speed. Case in point: as of this writing, the per-browser performance is nearly identical for all the techniques listed above. Meaning a lot of fuss a few years ago for such a small gain, when now there is no gain.

@wizzwizz4 2016-04-07 09:26:13

Oh, and Chrome is only fast because it forces its priority, in cases speeding up the interrupt cycle to ensure its speed, and opening lots and lots of processes.

@Jayme 2017-06-13 11:28:22

You .push() that value in. Example: array.push(value);

@Alireza 2017-05-14 12:18:18

We don't have append function for Array in javascript, but we have push and unshift, imagine you have the array below:

var arr = [1, 2, 3, 4, 5];

and we like append a value to this array, we can do, arr.push(6) and it will add 6 to the end of the array:

arr.push(6); // return [1, 2, 3, 4, 5, 6];

also we can use unshift, look at how we can apply this:

arr.unshift(0); //return [0, 1, 2, 3, 4, 5];

They are main functions to add or append new values to the arrays.

@Danil Gaponov 2015-07-21 14:38:37

Just want to add a snippet for non-destructive addition of an element.

var newArr = oldArr.concat([newEl]);

@JmLavoier 2016-09-29 22:10:31

If you are using the ES6 you can use spread operator to do it.

var arr = [
    "apple",
    "banana",
    "cherry"
];

var arr2 = [
    "dragonfruit",
    "elderberry",
    "fig"
];

arr.push(...arr2);

@Maarten Peels 2015-05-07 13:55:57

The push() method adds new items to the end of an array, and returns the new length. Example:

var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.push("Kiwi");

// The result of fruits will be:
Banana, Orange, Apple, Mango, Kiwi

The exact answer to your question is already answered, but let's look at some other ways to add items to an array.

The unshift() method adds new items to the beginning of an array, and returns the new length. Example:

var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.unshift("Lemon", "Pineapple");

// The result of fruits will be:
Lemon, Pineapple, Banana, Orange, Apple, Mango

And lastly, the concat() method is used to join two or more arrays. Example:

var fruits = ["Banana", "Orange"];
var moreFruits = ["Apple", "Mango", "Lemon"];
var allFruits = fruits.concat(moreFruits);

// The values of the children array will be:
Banana, Orange, Apple, Mango, Lemon

@Downhillski 2015-11-29 17:12:38

Javascript with ECMAScript 5 standard which is supported by most browsers now, you can use apply() to append array1 to array2.

var array1 = [3, 4, 5];
var array2 = [1, 2];

Array.prototype.push.apply(array2, array1);

console.log(array2); // [1, 2, 3, 4, 5]

Javascript with ECMAScript 6 standard which is supported by Chrome and FF and IE Edge, you can use the spread operator:

"use strict";
let array1 = [3, 4, 5];
let array2 = [1, 2];

array2.push(...array1);

console.log(array2); // [1, 2, 3, 4, 5]

The spread operator will replace array2.push(...array1); with array2.push(3, 4, 5); when the browser is thinking the logic.

Bonus point

If you'd like to create another variable to store all the items from both array, you can do this:

ES5 var combinedArray = array1.concat(array2);

ES6 const combinedArray = [...array1, ...array2]

The spread operator (...) is to spread out all items from a collection.

@Pawan Singh 2014-08-29 13:22:21

If you want to append two arrays -

var a = ['a', 'b'];
var b = ['c', 'd'];

then you could use:

var c = a.concat(b);

And if you want to add record g to array (var a=[]) then you could use:

a.push('g');

@Emil Reña Enriquez 2016-03-18 08:24:44

if you want to combine 2 arrays without the duplicate you may try the code below

array_merge = function (arr1, arr2) {
  return arr1.concat(arr2.filter(function(item){
    return arr1.indexOf(item) < 0;
  }))
}

usage:

array1 = ['1', '2', '3']
array2 = ['2', '3', '4', '5']
combined_array = array_merge(array1, array2)

Output: [1,2,3,4,5]

@Karl 2015-10-28 09:09:09

concat(), of course, can be used with 2 dimensional arrays as well. No looping required.

var a = [ [1, 2], [3, 4] ];

var b = [ ["a", "b"], ["c", "d"] ];

b = b.concat(a);

alert(b[2][1]); // result 2

@hawkeye126 2014-09-18 18:40:39

Let the array length property do the work:

myarray[myarray.length] = 'new element value added to the end of the array';

myarray.length returns the number of strings in the array. JS is zero based so the next element key of the array will be the current length of the array. EX:

var myarray = [0, 1, 2, 3],
    myarrayLength = myarray.length; //myarrayLength is set to 4

@yoel halb 2012-08-15 19:02:11

If you know the highest index (such as stored in a variable "i") then you can do

myArray[i + 1] = someValue;

However if you don't know then you can either use

myArray.push(someValue);

as other answers suggested, or you can use

myArray[myArray.length] = someValue; 

Note that the array is zero based so .length return the highest index plus one.

Also note that you don't have to add in order and you can actually skip values, as in

myArray[myArray.length + 1000] = someValue;

In which case the values in between will have a value of undefined.

It is therefore a good practice when looping through a JavaScript to verify that a value actually exists at that point.

This can be done by something like the following:

if(myArray[i] === "undefined"){ continue; }

if you are certain that you don't have any zeros in the array then you can just do:

if(!myArray[i]){ continue; }

Of course make sure in this case that you don't use as the condition myArray[i] (as some people over the internet suggest based on the end that as soon as i is greater then the highest index it will return undefined which evaluates to false)

@Tino 2019-12-01 13:30:38

You actually do not mean "undefined". It must read void 0! "undefined" is a string and "undefined" !== void 0, hence your if(myArray[i] is false unless the array at index i is set to the string with the contents equivalent of 'u'+'n'+'d'+'e'+'f'+'i'+'n'+'e'+'d'. Also note that you should not use undefined, instead use void 0. Because void 0 always is the undefined value, while undefined can be defined via something like function x(undefined) { alert(undefined) } x("hello world"), so you cannot be sure if somebody accidentally set window["undefined"]=1 or similar.

Related Questions

Sponsored Content

40 Answered Questions

[SOLVED] Loop through an array in JavaScript

86 Answered Questions

[SOLVED] How do JavaScript closures work?

19 Answered Questions

[SOLVED] How to insert an item into an array at a specific index (JavaScript)?

54 Answered Questions

97 Answered Questions

[SOLVED] How can I remove a specific item from an array?

  • 2011-04-23 22:17:18
  • Walker
  • 7126367 View
  • 8647 Score
  • 97 Answer
  • Tags:   javascript arrays

47 Answered Questions

[SOLVED] Sort array of objects by string property value

58 Answered Questions

[SOLVED] How do I redirect to another webpage?

40 Answered Questions

[SOLVED] For-each over an array in JavaScript

28 Answered Questions

[SOLVED] What does "use strict" do in JavaScript, and what is the reasoning behind it?

39 Answered Questions

[SOLVED] How do you get a timestamp in JavaScript?

Sponsored Content