-
Hajipur, Bihar, 844101
Hajipur, Bihar, 844101
JS Basics
JS Variables & Operators
JS Data Types & Conversion
JS Numbers & Math
JS Strings
JS Dates
JS Arrays
JS Control Flow
JS Loops & Iteration
JS Functions
JS Functions
Function Definitions
Function Parameters
Function Invocation
Function Call
Function Apply
Function Bind
Function Closures
JS Arrow Function
JS Objects
JS Objects
JS Object Properties
JS Object Methods
JS Object Display
JS Object Constructors
Object Definitions
Object Get / Set
Object Prototypes
Object Protection
JS Classes & Modules
JS Async Programming
JS Advanced
JS Destructuring
JS Bitwise
JS RegExp
JS Precedence
JS Errors
JS Scope
JS Hoisting
JS Strict Mode
JS this Keyword
JS HTML DOM
DOM Intro
DOM Methods
DOM Document
DOM Elements
DOM HTML
DOM Forms
DOM CSS
DOM Animations
DOM Events
DOM Event Listener
DOM Navigation
DOM Nodes
DOM Collections
DOM Node Lists
JS BOM (Browser Object Model)
JS Web APIs
Web API Intro
Web Validation API
Web History API
Web Storage API
Web Worker API
Web Fetch API
Web Geolocation API
JS AJAX
AJAX Intro
AJAX XMLHttp
AJAX Request
AJAX Response
AJAX XML File
AJAX PHP
AJAX ASP
AJAX Database
AJAX Applications
AJAX Examples
JS JSON
JSON Intro
JSON Syntax
JSON vs XML
JSON Data Types
JSON Parse
JSON Stringify
JSON Objects
JSON Arrays
JSON Server
JSON PHP
JSON HTML
JSON JSONP
JS Graphics & Charts
JavaScript arrays are powerful not just because they store multiple values, but also because they come with a wide range of built-in methods that make manipulating, transforming, and querying arrays straightforward. Knowing array methods is essential for writing efficient and clean code, whether you are handling user input, processing data, or building complex applications. This tutorial covers the most commonly used array methods, practical examples, common mistakes, and best practices.
Array methods simplify tasks such as:
Adding or removing elements dynamically
Searching for specific items
Transforming arrays into new structures
Sorting and filtering data
Iterating over arrays efficiently
Without these methods, developers would have to write complex loops and manual operations, which can be error-prone and harder to maintain.
Adds one or more elements to the end of an array and returns the new length.
let fruits = ["Apple", "Banana"];
fruits.push("Cherry");
console.log(fruits); // ["Apple", "Banana", "Cherry"]
Removes the last element of an array and returns it.
let lastFruit = fruits.pop();
console.log(lastFruit); // "Cherry"
console.log(fruits); // ["Apple", "Banana"]
Adds one or more elements to the beginning of an array.
fruits.unshift("Mango");
console.log(fruits); // ["Mango", "Apple", "Banana"]
Removes the first element from an array and returns it.
let firstFruit = fruits.shift();
console.log(firstFruit); // "Mango"
console.log(fruits); // ["Apple", "Banana"]
Merges two or more arrays into a new array without modifying the originals.
let citrus = ["Orange", "Lemon"];
let allFruits = fruits.concat(citrus);
console.log(allFruits); // ["Apple", "Banana", "Orange", "Lemon"]
Returns a shallow copy of a portion of an array.
let someFruits = allFruits.slice(1, 3);
console.log(someFruits); // ["Banana", "Orange"]
Adds or removes elements at a specific index. This method modifies the original array.
allFruits.splice(2, 1, "Grapes");
console.log(allFruits); // ["Apple", "Banana", "Grapes", "Lemon"]
indexOf() returns the first index of a value; lastIndexOf() returns the last occurrence.
let letters = ["A", "B", "C", "A"];
console.log(letters.indexOf("A")); // 0
console.log(letters.lastIndexOf("A")); // 3
Checks if an array contains a certain element.
console.log(letters.includes("B")); // true
console.log(letters.includes("D")); // false
Combines array elements into a single string with a specified separator.
let colors = ["Red", "Green", "Blue"];
console.log(colors.join(", ")); // "Red, Green, Blue"
Reverses the order of elements in an array.
colors.reverse();
console.log(colors); // ["Blue", "Green", "Red"]
Sorts elements. By default, it converts elements to strings and sorts lexicographically. For numbers, a compare function is needed.
let numbers = [40, 100, 1, 5];
numbers.sort(); // default string sort
console.log(numbers); // [1, 100, 40, 5]
numbers.sort((a, b) => a - b); // numeric ascending sort
console.log(numbers); // [1, 5, 40, 100]
Creates a new array by applying a function to each element.
let nums = [1, 2, 3];
let squared = nums.map(n => n * n);
console.log(squared); // [1, 4, 9]
Creates a new array with elements that pass a test.
let scores = [65, 82, 45, 90];
let passing = scores.filter(score => score >= 50);
console.log(passing); // [65, 82, 90]
Reduces an array to a single value by applying a function cumulatively.
let total = scores.reduce((sum, score) => sum + score, 0);
console.log(total); // 282
Executes a function on each element but does not return a new array.
scores.forEach(score => console.log(score));
find() returns the first element satisfying a condition; findIndex() returns its index.
let highScore = scores.find(score => score > 80);
console.log(highScore); // 82
let highScoreIndex = scores.findIndex(score => score > 80);
console.log(highScoreIndex); // 1
some() checks if at least one element passes a test; every() checks if all elements pass.
console.log(scores.some(score => score > 90)); // false
console.log(scores.every(score => score >= 45)); // true
let shopping = ["Milk", "Eggs", "Bread"];
shopping.push("Butter");
shopping.splice(1, 1); // Remove "Eggs"
console.log(shopping); // ["Milk", "Bread", "Butter"]
let numbers = [1, 2, 3, 4];
let doubled = numbers.map(n => n * 2);
console.log(doubled); // [2, 4, 6, 8]
let studentScores = [45, 78, 90, 60];
let passed = studentScores.filter(score => score >= 60);
console.log(passed); // [78, 90, 60]
let sales = [150, 200, 100, 250];
let totalSales = sales.reduce((sum, sale) => sum + sale, 0);
console.log(totalSales); // 700
let names = ["Emma", "Lily", "Sophia"];
console.log(names.find(name => name.startsWith("S"))); // Sophia
Using sort() without a compare function for numbers.
Forgetting that splice() modifies the original array.
Expecting forEach() to return a new array; it does not.
Mixing up map(), filter(), and reduce() and using them incorrectly.
Confusing some() and every() in conditional checks.
Choose the correct method based on whether you need a new array or to modify the existing one.
Always consider performance for large arrays, especially with methods like reduce() and filter().
Use arrow functions for cleaner and more readable callbacks.
Keep transformations immutable when possible to avoid side effects.
Chain array methods carefully to maintain clarity.
JavaScript array methods provide an extensive toolkit to manipulate and process arrays efficiently. From adding and removing elements to searching, sorting, filtering, and transforming data, these methods reduce the need for manual loops and make your code more readable and maintainable. Understanding the nuances of each method, their return values, and side effects is essential for writing effective JavaScript code and handling data in real-world applications such as lists, forms, tables, and API responses. Mastering these methods allows developers to write cleaner, more robust, and scalable applications.
Q1. How do you double all values in an array using a method?
Q2. Which method allows you to filter numbers greater than 50 in an array?
Q3. How do you find the sum of all numbers in an array?
Q4. Which method runs a function on each item but does not return a new array?
Q5. How do you remove the last element of an array?
Q6. What method is used to sort an array alphabetically?
Q7. How do you join elements of an array into a string separated by dashes (-)?
Q8. What method returns the index of a given value in an array?
Q9. How can you combine two arrays without modifying the original ones?
Q10. How do you reverse the order of elements in an array?
JS Basics
JS Variables & Operators
JS Data Types & Conversion
JS Numbers & Math
JS Strings
JS Dates
JS Arrays
JS Control Flow
JS Loops & Iteration
JS Functions
JS Functions
Function Definitions
Function Parameters
Function Invocation
Function Call
Function Apply
Function Bind
Function Closures
JS Arrow Function
JS Objects
JS Objects
JS Object Properties
JS Object Methods
JS Object Display
JS Object Constructors
Object Definitions
Object Get / Set
Object Prototypes
Object Protection
JS Classes & Modules
JS Async Programming
JS Advanced
JS Destructuring
JS Bitwise
JS RegExp
JS Precedence
JS Errors
JS Scope
JS Hoisting
JS Strict Mode
JS this Keyword
JS HTML DOM
DOM Intro
DOM Methods
DOM Document
DOM Elements
DOM HTML
DOM Forms
DOM CSS
DOM Animations
DOM Events
DOM Event Listener
DOM Navigation
DOM Nodes
DOM Collections
DOM Node Lists
JS BOM (Browser Object Model)
JS Web APIs
Web API Intro
Web Validation API
Web History API
Web Storage API
Web Worker API
Web Fetch API
Web Geolocation API
JS AJAX
AJAX Intro
AJAX XMLHttp
AJAX Request
AJAX Response
AJAX XML File
AJAX PHP
AJAX ASP
AJAX Database
AJAX Applications
AJAX Examples
JS JSON
JSON Intro
JSON Syntax
JSON vs XML
JSON Data Types
JSON Parse
JSON Stringify
JSON Objects
JSON Arrays
JSON Server
JSON PHP
JSON HTML
JSON JSONP
JS Graphics & Charts
