concat() combines arrays and/or values and returns a new array. It does not change the original arrays.
const scripts = ["PHP", "JavaScript"];
const databases = ["MySQL", "SQLite"];
const combined = scripts.concat(databases);
console.log(combined); // ["PHP", "JavaScript", "MySQL", "SQLite"]
console.log(scripts); // unchanged
const result = array.concat(value1, value2, value3);
Each argument can be a value or an array. The result is a new array.
const scripts = ["PHP", "ASP", "JavaScript", "HTML"];
const browsers = ["Chrome", "Firefox", "Safari"];
const both = scripts.concat(browsers);
console.log(both);
const a = [1, 2];
const b = [3, 4];
const c = [5, 6];
const all = a.concat(b, c);
console.log(all); // [1, 2, 3, 4, 5, 6]
The original page also used concat() to add normal values. They are appended to the new array.
const scripts = ["PHP", "JavaScript"];
const newArray = scripts.concat("Python", "SQL");
console.log(newArray); // ["PHP", "JavaScript", "Python", "SQL"]
const values = [1, 2];
const combined = values.concat([3, 4], [[5, 6]]);
console.log(combined); // [1, 2, 3, 4, [5, 6]]
concat() does not recursively flatten all nested arrays.
const a = [1, 2];
const b = [3, 4];
const c = a.concat(b);
console.log(a); // [1, 2]
console.log(b); // [3, 4]
console.log(c); // [1, 2, 3, 4]
Primitive values are copied as values, but object and nested-array elements remain shared references.
const user = { name: "Ravi" };
const original = [user];
const copy = original.concat();
copy[0].name = "Anita";
console.log(original[0].name); // Anita
const a = [1, 2];
const b = [3, 4];
const withConcat = a.concat(b);
const withSpread = [...a, ...b];
Both are readable for ordinary combination. concat() also has well-defined behavior for concat-spreadable values and does not require constructing one large function argument list.
Use push() to mutate the existing array. Use concat() when you want a new combined array.
const a = [1, 2];
a.push(3); // a becomes [1, 2, 3]
const b = [1, 2];
const c = b.concat(3); // b stays [1, 2]
concat() and ignoring its return value while expecting the original array to change.push(array) when you intended to merge array elements rather than add a nested array.Join Elements into a String Display Array Elements Array Reference
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.
| sophal | 25-10-2010 |
| how to write code to defend user input only number in java script? | |