Find out the way JavaScript provides you to append items to the array and the canonical way you should use
Attach a single item
To append a single item to the array, usepush()
The methods provided by the Array object:
const fruits = ['banana', 'pear', 'apple']
fruits.push('mango')
push()
Change the original array.
To create a new array, useconcat()
Array method:
const fruits = ['banana', 'pear', 'apple']
const allfruits = fruits.concat('mango')
noteconcat()
No items are actually added to the array, but a new array is created, which you can assign to another variable, or reassign to the original array (declare it aslet
Because you cannot reassignconst
):
let fruits = ['banana', 'pear', 'apple']
fruits = fruits.concat('mango')
Append multiple items
To append multiple items to the array, you can usepush()
Call it by using multiple parameters:
const fruits = ['banana', 'pear', 'apple']
fruits.push('mango', 'melon', 'avocado')
You can also useconcat()
The method you saw earlier, passing a comma-separated list of items:
const fruits = ['banana', 'pear', 'apple']
const allfruits = fruits.concat('mango', 'melon', 'avocado')
Or array:
const fruits = ['banana', 'pear', 'apple']
const allfruits = fruits.concat(['mango', 'melon', 'avocado'])
Remember, as mentioned earlier, this method will not mutate the original array, but will return a new array.
Download mine for freeJavaScript beginner's manual
More js tutorials:
- Things to avoid in JavaScript (bad parts)
- Delays and promises in JavaScript (+ Ember.js example)
- How to upload files to the server using JavaScript
- JavaScript coding style
- Introduction to JavaScript arrays
- Introduction to JavaScript programming language
- The complete ECMAScript 2015-2019 guide
- Understanding the JavaScript promise
- The lexical structure of JavaScript
- JavaScript type
- JavaScript variables
- Sample web application prompt list
- Introduction to JavaScript functional programming
- Modern asynchronous JavaScript with Async and Await
- JavaScript loops and ranges
- Map JavaScript data structure
- Set up JavaScript data structure
- JavaScript template text guide
- Roadmap for learning JavaScript
- JavaScript expression
- Discover JavaScript timer
- JavaScript event description
- JavaScript loop
- Use map, filter, reduce and find to write JavaScript loops
- JavaScript event loop
- JavaScript function
- JavaScript glossary
- JavaScript closure description
- JavaScript Arrow function tutorial
- JavaScript regular expression guide
- How to check if a string contains substrings in JavaScript
- How to delete items from an array in JavaScript
- How to clone JavaScript objects in depth
- Introduction to Unicode and UTF-8
- Unicode in JavaScript
- How to capitalize the first letter of a string in JavaScript
- How to format a number as a currency value in JavaScript
- How to convert a string to a number in JavaScript
- This in javascript
- How to get the current timestamp in JavaScript
- JavaScript strict mode
- JavaScript immediate call function expression (IIFE)
- How to redirect to another webpage using JavaScript
- How to remove attributes from JavaScript objects
- How to append items to an array in JavaScript
- How to check if JavaScript object property is undefined
- Introduction to ES Module
- Introduction to CommonJS
- JavaScript asynchronous programming and callbacks
- How to replace all occurrences of strings in JavaScript
- A quick reference guide to modern JavaScript syntax
- How to trim leading zeros in numbers in JavaScript
- How to inspect JavaScript objects
- The definitive guide to JavaScript dates
- Moment.js tutorial
- Semicolon in JavaScript
- JavaScript arithmetic operators
- JavaScript Math object
- Generate random and unique strings in JavaScript
- How to put your JavaScript function to sleep
- JavaScript prototypal inheritance
- JavaScript exception
- How to use JavaScript classes
- JavaScript recipes
- Quotation marks in JavaScript
- How to verify email address in JavaScript
- How to get the unique attributes of a group of objects in a JavaScript array
- How to check if a string starts with another string in JavaScript
- How to create a multi-line string in JavaScript
- ES6 guide
- How to get the current URL in JavaScript
- ES2016 Guidelines
- How to initialize a new array with values in JavaScript
- ES2017 guide
- ES2018 guide
- How to use Async and Await in Array.prototype.map()
- Asynchronous and synchronous code
- How to generate a random number between two numbers in JavaScript
- HTML Canvas API tutorial
- How to get the index of iteration in a for-of loop in JavaScript
- What is a single page application?
- Introduction to WebAssembly
- Introduction to JSON
- JSONP guide
- Should you use or learn jQuery in 2020?
- How to hide DOM elements using pure JavaScript
- How to merge two objects in JavaScript
- How to clear JavaScript array
- How to encode URL using JavaScript
- How to set default parameter values in JavaScript
- How to sort an array of objects by attribute value in JavaScript
- How to count the number of attributes in a JavaScript object
- Call() and apply() in JavaScript
- Introduction to WebRTC library PeerJS
- Use Rest and Spread to process objects and arrays
- Decompose objects and arrays with JavaScript
- The definitive guide to debugging JavaScript
- TypeScript guide
- Methods of dynamically selecting objects in JavaScript
- Pass undefined to the function expression that JavaScript calls immediately
- Loosely typed and strongly typed languages
- How to style DOM elements using JavaScript
- Served with JavaScript
- JavaScript generator tutorial
- The size of the node_modules folder is not a problem. This is a privilege
- How to resolve unexpected identifier errors when importing modules in JavaScript
- How to list all methods of an object in JavaScript
- String replace() method
- String search() method
- How do I run some JavaScript code snippets
- ES2019 guide
- String charAt() method
- String charCodeAt() method
- String codePointAt() method
- String concat() method
- String endsWith() method
- String include() method
- String indexOf() method
- String lastIndexOf() method
- String localeCompare() method
- String match() method
- String normalize() method
- String padEnd() method
- String padStart() method
- String repeat() method
- String slice() method
- String split() method
- String startsWith() method
- String substring() method
- String toLocaleLowerCase() method
- String toLocaleUpperCase() method
- String toLowerCase() method
- String toString() method
- String toUpperCase() method
- String trim() method
- String trimEnd() method
- String trimStart() method
- Memoization of JavaScript
- String valueOf() method
- JavaScript reference: strings
- Number isInteger() method
- Number isNaN() method
- Number isSafeInteger() method
- Number parseFloat() method
- Number parseInt() method
- Number toString() method
- Number valueOf() method
- Number toPrecision() method
- Number toExponential() method
- Number toLocaleString() method
- Number toFixed() method
- Number isFinite() method
- JavaScript reference: numbers
- JavaScript attribute descriptor
- The assign() method of the object
- Object's create() method
- Object defineProperties() method
- Object defineProperty() method
- Object entry() method
- Object Frozen() method
- Object getOwnPropertyDescriptor() method
- Object getOwnPropertyDescriptors() method
- Object getOwnPropertyNames() method
- Object getOwnPropertySymbols() method
- Object getPrototypeOf() method
- Object is() method
- Object isExtensible() method
- Object isFrozen() method
- Object isSealed() method
- Object keys() method
- The preventExtensions() method of the object
- Object seal() method
- Object setPrototypeOf() method
- Object values() method
- Object hasOwnProperty() method
- Object isPrototypeOf() method
- The object's propertyIsEnumerable() method
- Object toLocaleString() method
- Object toString() method
- Object valueOf() method
- JavaScript reference: objects
- JavaScript assignment operator
- JavaScript internationalization
- JavaScript typeof operator
- JavaScript new operators
- JavaScript comparison operators
- JavaScript operator precedence rules
- JavaScript instanceof operator
- JavaScript statement
- JavaScript scope
- JavaScript type conversion (broadcast)
- JavaScript equality operator
- JavaScript if / else conditions
- JavaScript switching conditions
- JavaScript delete operator
- JavaScript function parameters
- JavaScript spread operator
- JavaScript return value
- JavaScript logical operators
- JavaScript ternary operator
- JavaScript recursion
- JavaScript object properties
- JavaScript error object
- JavaScript global objects
- JavaScript filter() function
- JavaScript map() function
- JavaScript reduce() function
- JavaScript `in` operator
- JavaScript operator
- How to get the value of a CSS property in JavaScript
- How to add event listeners to multiple elements in JavaScript
- JavaScript private class field
- How to sort array by date value in JavaScript
- JavaScript public class field
- JavaScript symbols
- How to use the JavaScript bcrypt library
- How to rename fields when using object destructuring
- How to check the type in JavaScript without using TypeScript
- How to check if JavaScript array contains a specific value
- What is the double negation operator! Do it with JavaScript?
- Which equals operator should be used in JavaScript comparisons? == vs ===
- Is JavaScript still worth learning?
- How to return the result of an asynchronous function in JavaScript
- How to check if an object is empty in JavaScript
- How to break through the for loop in JavaScript
- How to add an item to an array at a specific index in JavaScript
- Why shouldn't JavaScript object prototype be modified
- What is the difference between using let and var in JavaScript?
- Link to activate JavaScript function
- How to concatenate two strings in JavaScript
- How to concatenate two arrays in JavaScript
- How to check whether the JavaScript value is an array?
- How to get the last element of an array in JavaScript?
- How to send urlencoded data using Axios
- How to get tomorrow's date using JavaScript
- How to get yesterday's date using JavaScript
- How to get month name from JavaScript date
- How to check if two dates are the same day in JavaScript
- How to check if the date points to the past day in JavaScript
- Statements marked with JavaScript
- How to wait for 2 or more Promises to resolve in JavaScript
- How to get the date between two dates in JavaScript
- How to use extraction to upload files
- How to format date in JavaScript
- How to traverse object properties in JavaScript
- How to calculate the number of days between two dates in JavaScript
- How to use top-level waits in ES modules
- JavaScript dynamic import
- JavaScript optional link
- How to replace spaces in a string in JavaScript
- JavaScript empty merge
- How to flatten an array in JavaScript
- Ten years of JavaScript
- How to send authorization header using Axios
- List of keywords and reserved words in JavaScript
- How to convert an array to a string in JavaScript
- How to delete all node_modules folder contents
- How to remove duplicates from JavaScript array
- Let vs const in JavaScript
- The same POST API call in various JavaScript libraries
- How to get the first n items in an array in JS
- How to divide an array into multiple equal parts in JS
- How to slow down the loop in JavaScript
- How to load images in HTML canvas
- How to cut a string into words in JavaScript
- How to split an array in half in JavaScript
- How to write text to HTML canvas
- How to delete the last character of a string in JavaScript
- How to delete the first character of a string in JavaScript
- How to fix TypeError: Cannot assign property "exports" error as read-only object "#<Object>"
- How to create an exit intent pop-up window
- How to check if an element is a descendant of another element
- How to force the use of credentials for every Axios request
- How to solve the "not a function" error in JavaScript
- Gatsby, how to change the icon
- Use Gatsby to load external JS files
- How to detect dark mode using JavaScript
- Package, how to fix "regeneratorRuntime is not defined" error
- How to detect whether Adblocker is used with JavaScript
- Object decomposition using types in TypeScript
- Deno Manual: A brief introduction to Deno🦕
- How to get the last paragraph of a path or URL using JavaScript
- How to shuffle the elements in a JavaScript array
- How to check if a key exists in a JavaScript object
- Event bubbling and event capture
- event.stopPropagation and event.preventDefault() and return false in DOM events
- Primitive types and objects in JavaScript
- How to determine the type of value in JavaScript?
- How to return multiple values from a function in JavaScript
- Arrow functions and regular functions in JavaScript
- In what ways can we access the value of an object property?
- What is the difference between null and undefined in JavaScript?
- What is the difference between method and function?
- How can we get rid of the JavaScript loop?
- JavaScript for..of loop
- What is object deconstruction in JavaScript?
- What does JavaScript suspend?
- How to change comma to dot using JavaScript
- The importance of timing when using the DOM
- How to reverse JavaScript array
- How to check if a value is a number in JavaScript
- How to accept unlimited parameters in JavaScript functions
- JavaScript proxy object
- Use vanilla JavaScript for event delegation in the browser
- JavaScript super keyword
- Introduction to XState
- Is the value passed by reference or passed by value in JavaScript?
- Custom events in JavaScript
- Custom errors in JavaScript
- Namespaces in JavaScript
- The strange usage of commas in JavaScript
- Link method call in JavaScript
- How to deal with promise rejection
- How to swap two array elements in JavaScript
- How to solve "cb.apply is not a function" error when using Gitbook
- How to add items at the beginning of an array in JavaScript
- Gatsby, fix "Cannot find module gatsby-cli/lib/reporter" error
- How to get the index of an item in a JavaScript array
- How to test for empty objects in JavaScript
- How to deconstruct an object into an existing variable in JavaScript
- Array JavaScript data structure
- Stacked JavaScript data structure
- JavaScript data structure: queue
- JavaScript data structure: sets
- JavaScript data structure: dictionary
- JavaScript data structure: list of links
- JavaScript, how to export functions
- JavaScript, how to export multiple functions
- JavaScript, how to exit the function
- JavaScript, how to find characters in a string
- JavaScript, how to filter an array
- JavaScript, how to extend classes
- JavaScript, how to find duplicates in an array
- JavaScript, how to replace items in an array
- JavaScript algorithm: linear search
- JavaScript algorithm: binary search
- JavaScript algorithm: selection sort
- JavaScript algorithm: Quicksort
- JavaScript algorithm: merge sort
- JavaScript algorithm: bubble sort