Sign In
Sign In

How to Use the Date Object in JavaScript

How to Use the Date Object in JavaScript
Kolawole Mangabo
Technical writer
JavaScript
15.10.2024
Reading time: 8 min

JavaScript provides a built-in Date object that simplifies working with dates and times. This tutorial will guide developers through the essential aspects of the Date object, including its creation, retrieval of date and time information, formatting, manipulation, and handling of time zones.

Introduction to JavaScript Date Object

The Date object in JavaScript represents datetime values, enabling developers to manage temporal data with ease. It is essential for tasks such as scheduling, time tracking, and logging. The Date object helps:

  • Represent specific date and time values, such as "2022-07-25T14:30:00.000Z".

  • Perform operations like retrieving, formatting, and manipulating dates and times.

  • Simplify date and time calculations across different time zones.

Understanding the basics of the Date object will help in managing time-sensitive data efficiently in web applications.

Creating a Date Object

Creating a Date object in JavaScript is straightforward. Here are the two common ways to achieve it: 

  • Using the current time

  • Using a timestamp

Creating a Date Object for the Current Time

The simplest way to create a Date object is by instantiating the current date and time:

const currentDate = new Date();
console.log(currentDate);

Image1

This creates an object representing the current date and time in the user's local timezone.

Creating a Date Object Using a Timestamp

You can also create a Date object from a specific timestamp (milliseconds since January 1, 1970):

const timestamp = 1643723400000;
const dateObject = new Date(timestamp);
console.log(dateObject);

Image3

This is useful for manipulating dates stored in timestamp format. Now that we know how to create a date object, let’s see how to retrieve date and time information.

Retrieving JS Date and Time Information

The Date object provides methods for extracting various components of a date, such as a year, month, and hour. Key methods include

  • getDate(): Returns the day of the month.

  • getFullYear(): Returns the four-digit year.

  • getMonth(): Returns the month (0-11, where 0 represents January).

  • getHours(): Returns the hour (0-23).

  • getMinutes(): Returns the minutes (0-59).

  • getSeconds(): Returns the seconds (0-59).

For example, to retrieve the current date and format it as MM/DD/YYYY HH:MM:ss:

function formatDate(dateObject) {
  const year = dateObject.getFullYear();
  const month = dateObject.getMonth() + 1; // Months are zero-indexed
  const day = dateObject.getDate();
  const hours = dateObject.getHours();
  const minutes = dateObject.getMinutes();
  const seconds = dateObject.getSeconds();
  
  return `${month}/${day}/${year} ${hours}:${minutes}:${seconds}`;
}
console.log(formatDate(new Date()));

Here is the result when executing the function. 

Image2

There are however interesting methods we can use to format datetime into readable formats. 

Formatting Date and Time

JavaScript provides methods to format datetime values into human-readable strings. This allows developers to convert a Date object to a string or vice versa.

Formatting a Date as a String

To output a Date object as a human-readable string, use methods like toDateString() and toTimeString():

const currentDate = new Date();
const dateString = currentDate.toDateString();
console.log(dateString);

const timeString = currentDate.toTimeString();
console.log(timeString);

Here is the output:

Image5

Converting Strings to Date Objects

Developers can also convert readable strings into Date objects using the Date constructor:

const dateFromString = new Date("October 10, 2024");
console.log(dateFromString);

Image4

However, it’s better to use recommended formats. 

Recommended Formats

To avoid errors when working with date strings, it is advisable to use reliable formats:

  1. ISO 8601 Format (Recommended): The safest and most reliable format is the ISO 8601 date format: YYYY-MM-DDTHH:mm:ss.sssZ. If only the date part is provided, it assumes the time as midnight 00:00:00.

const date = new Date("2024-10-10T14:48:00Z");
console.log(date);

Image7

  1. RFC2822 Format: Another accepted format is the RFC2822 format commonly used in email headers: Day, DD Mon YYYY HH:mm:ss GMT.

const date = new Date("Wed, 10 Oct 2024 14:48:00 GMT");
console.log(date);

Image6

We now know how to format datetime values using the Date object. Let’s see how to manipulate date values for simple scheduling and calculations.

Manipulating Date Values

Date manipulation is essential for tasks like scheduling and calculating deadlines. JavaScript provides setter methods for modifying specific components of a Date object.

Modifying Date Components

Developers can modify specific components of a Date object using setter methods. Note that months are zero-indexed:

let date = new Date();
date.setFullYear(2025);
date.setMonth(5);        // Set month to June
date.setDate(15);        // Set day to 15th
date.setHours(10);       // Set hour to 10 AM
date.setMinutes(30);     // Set minutes to 30
date.setSeconds(45);     // Set seconds to 45
console.log(date);

Image9

Adding or Subtracting Days

Developers can easily add or subtract days using setDate():

let date = new Date();
date.setDate(date.getDate() + 5); // Add 5 days
console.log(date);

Image8

Date arithmetic can be accomplished using timestamps (milliseconds since January 1, 1970):

let now = new Date();
let oneDayInMs = 24 * 60 * 60 * 1000;
let tomorrow = new Date(now.getTime() + oneDayInMs);
console.log(tomorrow);

Image12

Comparing Date Objects

Date objects can be compared using their timestamps:

let date1 = new Date('2024-10-10');
let date2 = new Date('2024-12-25');
console.log(date1 > date2);  // false (October 10 is earlier than December 25)
console.log(date1 < date2);  // true
console.log(date1.getTime() === date2.getTime());  // false

Image10

Now that we now how to manipulate dates values for calculation, let’s see how we can handle dates with time zones.

Working with Time Zones

The Date object is timezone-agnostic, meaning it doesn't have a built-in concept of time zones. However, JavaScript’s Date object handles dates in local time (system time zone) and UTC. When creating Date objects, it is essential to be aware of time zone conversions, especially when performing operations across different regions.

Local Time vs. UTC

JavaScript can work with localtime and UTC. Local time allows you to represent the time by the Date object when created without any specific time zone information, reflecting the local time of the environment in which JavaScript is executed. For example, creating a Date object in Paris will reflect the central European time zone.

UTC is the time standard not affected by time zones or DayLight Saving Time (DST). Using Coordinated Universal Time (UTC) ensures consistency and avoids ambiguity when working with dates and times across different time zones, simplifying time calculations, logging, and user experience management in applications that serve users in multiple regions.

Creating Date Objects in UTC

To create a Date object in UTC, use the ISO 8601 format:

const utcDate = new Date("2024-10-10T14:30:00Z");
console.log(utcDate);

Image11

Converting Local Time to UTC

To retrieve UTC date components, use getUTCDate(), getUTCMonth(), etc.:

const localDate = new Date();
console.log(localDate.getUTCDate(), localDate.getUTCMonth() + 1, localDate.getUTCFullYear());

Image13

Converting UTC to Local Time

Similarly, to convert a UTC date to local time, you can use the local equivalent methods:

const utcDate = new Date("2024-10-10T14:30:00Z"); // UTC date
const localDay = utcDate.getDate();
const localMonth = utcDate.getMonth() + 1; // Months are zero-indexed
const localYear = utcDate.getFullYear();

console.log(`Local Date: ${localMonth}/${localDay}/${localYear}`);

Image14

Being mindful of time zones when working with dates in JavaScript is essential for ensuring accurate datetime representation, especially in applications that require coordination across different regions.

Let’s learn more about common Date Object methods.

Common Date Object Methods

JavaScript provides several static and instance methods that simplify working with dates. Here are some key methods:

  • Date.now(): Returns the current timestamp in milliseconds since January 1, 1970.

  • Date.parse(): Parses a date string and returns the number of milliseconds since the Unix Epoch (January 1, 1970). If the string cannot be parsed, it returns NaN.

  • Date.UTC(): Creates a Date object from UTC values.

  • Date.toString(): Returns a string representation of the Date object in a readable format.

  • valueOf(): Returns the primitive value of the Date object.

These methods provide essential functionality for working with dates in JavaScript, enabling developers to efficiently manage and manipulate date values in their applications. 

Conclusion

The JavaScript Date object is an essential tool for managing datetime in web development. From creating dates to formatting and performing date arithmetic, mastering this object will enable developers to handle time-sensitive data efficiently, regardless of time zone or locale.

By using built-in methods and libraries like Moment.js, date-fns, or Day.js, developers can ensure their applications deliver a smooth user experience when working with dates.

JavaScript
15.10.2024
Reading time: 8 min

Similar

JavaScript

Looping through Objects’s Keys and Values in JavaScript

JavaScript, a user-friendly programming language with important components such as object keys and values, serves as a robust creator of dynamic and interactive web applications. Complex and constantly changing data require efficient iterating over the object's keys and values. It is precisely the 'iterating through object keys and values' concept, or simply JS looping through object keys and values that provides access and performs required actions. You can expand the functionality of your applications and manipulate data with skill once you have mastered these strategies. A fundamental ability for any JavaScript developer enhances the processing and manipulation of intricate data sets, increasing the flexibility and dynamic nature of your code. This cost-effective solution allows developers to readily access and change data without repeating code, even when the data is continually changing and updating. In this article, we’ll delve into various techniques and methods to loop through object keys and values in JS, so you’ll learn how to apply them in your code. Whether you are a beginner or an experienced developer, read on to discover how to improve your data manipulation skills and efficiently apply them in your own projects. Explore the world of looping through object keys and values in JavaScript. JavaScript Object: Key-Value Pairs Objects in JavaScript Before diving into the theory and practice, let's start with understanding what objects are in JavaScript. So, they are a collection of key-value pairs, where the key is a unique identifier and the corresponding value is any data type. They allow data to be stored and manipulated in a structured and organized way. Also they contain any number of key-value pairs with different data types. The loop through object feature in JS stands for creating complex objects, suitable for storing, sorting, filtering, searching and manipulating large amounts of data. Objects can have functions as their values, known as methods, which perform specific actions or operations on the object's data. New key-value pairs can be added to an object, existing values can be modified, or even deleted if required. Basic for loop through object keys and values in JS The JS for loop is commonly used for iterating through arrays and objects as well as for looping through object keys and values, especially to get access and manipulate specific properties within an object.  To start, learn the basic for loop method for looping through an array: for (var i = 0; i < array.length; i++) {// code to be executed} This for loop has three parts: the initialization (var i = 0) the condition (i < array.length) the increment (i++). The loop runs as long as the condition is true, and each time it loops, the i value is increased. This feature gives access to each element in the array with the help of the i index. To use a similar for loop to iterate through object keys and values, you should apply the for...in loop designed specifically for objects: for (var key in object) {// code to be executed} In this loop, the variable key takes on the value of each key in the object as it loops through the JS object. This feature gives access to the corresponding value for each key via object[key]. For instance, for an object called site with the properties web name, age, and occupation, each property and its value can be accessed via the for...in loop: var site = { web name: 'Hostman', age: 5, occupation: 'cloud service provider' }; for (var key in site) { console.log(key + ': ' + site[key]); } // Output: // name: Hostman // age: 5 // occupation: cloud service provider This means without knowing the precise names of the properties beforehand, the for...in loop provides quick access to all of the keys and values in an object. When working with big and complicated items, this is helpful. The for...in loop is also used to check if a specific property exists in an object, and modify its value by using the hasOwnProperty() method: for (var key in site) { if (site.hasOwnProperty(key)) { // code to be executed } } The for loop feature for iterating through object keys and values in JS provides quick access to the properties and the ability to manipulate them within an object. By understanding the syntax and usage of the feature, you can improve the functionality of working with objects and shorten your code. The Object.keys() method to loop through objects in JS The built-in Object.keys() method in JavaScript allows you to get an array of all the keys of a given object. The JS feature is designed to loop over all the properties of an object because it is a simple way to access and manipulate each key individually. The idea is to pass the object you want to get the keys from as a parameter, and the method returns an array of all the keys in that object. Static method syntax is called directly on the Object class, not on the object instance. That's why it got its name Object.keys(). The parentheses after the method name are used to pass the object from which you want to get the keys. For instance, for an object called site with properties such as web name, age, and occupation, apply the following Object.keys() method: Object.keys(site) The JS method will loop over the properties of the passed object and return an array of all keys. The keys in the array are arranged in the same order in which they appear in the object due to the fact that objects in JavaScript are unordered, meaning there is no guarantee that the properties will be returned in a particular order. However, the Object.keys() method ensures that the keys are returned in the order in which they were added to the object. The Object.values() method to loop through objects in JS The Object.values() method allows you to quickly access and retrieve all the values ​​of an object as an array, simplifying the way you manipulate and loop through an array of objects in JS. For instance, for an object called site that contains various properties such as web name, age, occupation, using the Object.values() method allows retrieving all the values of this object in the form of an array. The syntax is simple and consists of passing the object site as a parameter: const siteValues = Object.values(site); This feature will return an array with all the site object values in the same order as they are defined in the object. This array helps performing various operations, such as filtering or sorting the data. Combining Object.keys() and Object.values() for efficient object iteration in JavaScript A more effective method for looping through an object in JavaScript is to use the Object.keys() and Object.values() methods. While the second one gives an array of all the corresponding values, the first one returns an array of all the keys that are present in an object. When both approaches are used together, an object's keys and values can be accessed. For instance, for an object called site with properties like web name, age, occupation, apply the following code. const site = { web name: 'Hostman', age: 5, occupation: 'cloud service provider' }; const keys = Object.keys(site); const values = Object.values(site); console.log(keys); // Output: ['web name', 'age', 'occupation'] console.log(values); // Output: ['Hostman', 5, 'cloud service provider'] As a result of the synergy of both methods, two arrays were returned containing the keys and values of the site object. They are easily accessed and manipulated to perform any operation on the object, including loop through object properties in JS. The for...of method to loop through object in JS The for...of loop provides a simplified syntax compared to the traditional for...in loop, iterating over the values of an object while working with arrays, strings, and other iterable objects. The feature eliminates errors or bugs in code as there is no need for manual counting or using a counter variable. Automatically iterating over each element of the iterable object and assigning it to a variable improves the loop through object keys in JS. The feature can be used with any iterable object, regardless of its length or size, with a variable number of elements, such as arrays. For instance, if you want to print out each flower separately, use the for...of loop.  To start, declare the array of flowers: const flowers = ['rose', 'daisy', 'violet']; Next, apply the for...of loop to iterate over the elements in the flowers array and print out each flower: for (const flower of flowers) {console.log(flower);} In this code, the variable flower is automatically assigned to each element in the flowers array in every iteration of the loop, allowing the value of each flower to be accessed and printed without manually declaring and incrementing a counter variable. The Object.entries() method in JavaScript The Object.entries() method stands for efficient iteration through the keys and values of an object. Simple access to and manipulation of object properties eliminates the need for complex syntax or methods. It takes an object as a parameter and returns an array of arrays. Each inner array consists of two elements, where the first is the object's property key, and the second is the corresponding value. This is a useful feature to loop through an object and access both the keys and values at the same time in JS. For instance, for an object called site with properties such as web name, age, and occupation, apply the Object.entries() method to loop through this object and access both the keys and values. The syntax looks as follows: Object.entries(site); This will return an array of arrays with the following structure: [['web name', 'Hostman'], ['age', 5], ['occupation', 'cloud service provider']] Each inner array contains two elements, the key and value of the object property to access both of them in a single iteration. This method can be used in conjunction with a for loop to iterate through the array and perform any desired operations with the objects in JS. It also allows us to convert an object into an array of key-value pairs to manipulate or transform an object into a different data structure. For instance, apply the Object.entries() method to convert an object into a Map, which is a data structure with key-value pairs. To do this, use the following syntax: const map = new Map(Object.entries(site)); This will create a new Map with the same key-value pairs as the original object. The Object.getOwnPropertyNames() method in JavaScript The getOwnPropertyNames is a method that retrieves all of an object's own properties, including both enumerable and non-enumerable ones, but it excludes Symbol-keyed properties. Let’s try this method. First, we define an object.  const appConfig = { theme: 'dark', language: 'en' }; We can then add a non-enumerable internal property to the object.  // Add non-enumerable internal properties Object.defineProperty(appConfig, 'version', { value: '1.0.0', enumerable: false }); We can then use Object.getOwnPropertyNames(appConfig) to display the properties.  console.log(Object.getOwnPropertyNames(appConfig)); // Output: ["theme", "language", "version"] getOwnPropertyNames will display all internal properties, including hidden ones (version). We can then use the result to loop through the object and display the properties and their values. Object.getOwnPropertyNames(appConfig).forEach(key => { console.log(`${key}: ${appConfig[key]}`); }); // Output: // theme: dark // language: en // version: 1.0.0 The Reflect.ownKeys() method retrieves all own properties of an object, including string keys and symbol keys. By default, symbol keys are not visible for Object.keys() and Object.getOwnPropertyNames() methods. const plugin = { name: 'AuthPlugin', settings: { enable2FA: true, }, [Symbol('id')]: 'auth123', }; // Iterate over all keys Reflect.ownKeys(plugin).forEach(key => { console.log(`${String(key)}: ${plugin[key]}`); }); // Output: // name: AuthPlugin // settings: { enable2FA: true } // Symbol(id): auth123 Looping Through a Nested Object When a JavaScript object contains other objects as values, a simple loop won’t be enough to traverse the whole object. To resolve this issue, we can use recursion combined with the Object.keys().forEach() method.  Here is an example.  const nestedObject = { name: "Alice", details: { age: 25 } }; function traverse(obj) { Object.keys(obj).forEach(key => { if (typeof obj[key] === "object" && obj[key] !== null) { traverse(obj[key]); // Recursively handle nested objects } else { console.log(`${key}: ${obj[key]}`); } }); } traverse(nestedObject); // Output: // name: Alice // age: 25 Iterating Objects with Object.entries / Object.keys Conclusion Loop through object keys and values in JS provides quick access to data stored in objects for manipulation and makes a code more dynamic and flexible. In this tutorial we showed you the basic methods for looping through object keys and values. Mastering these techniques is essential for a developer looking to create complex and efficient applications. By constantly learning and exploring new techniques and resources, you will become more adept at working with objects in your code. Keep practicing and experimenting with different approaches to find the one that works best for your specific project.
25 August 2025 · 11 min to read
JavaScript

JavaScript Array Methods

Arrays in JavaScript are a data structure that stores various elements, often of the same type. Their main feature is storing multiple values in a single variable. Thanks to their integrated methods and properties, you can add, delete, process, or search the data based on your needs.  All array values are elements. In turn, they have their own index. Variables can be either of the same or different data types, allowing you to organize more complex data structures. Creating an array There are two ways to initialize an array: 1. Using a literal syntax. In this case, elements are listed inside square brackets and separated by commas.  const ExampleArr = [element0, element1, …, elementN]; 2. using the Array() constructor. Syntax: const ExampleArr = new Array(element0, element1[, …[, elementN]]);const ExampleArr = new Array(arrayLenght); In both methods, we pass elementN as parameters. These are the variables that create the set of ExampleArr values. ArrayLength is the number of elements. Their default value is not defined.  After creating the array, let’s fill it in. Let's create a set of values that stores employees' names. Using the first method: var EmployeeArr = [‘Alex’, ‘Bob’, ‘Oliver’]; Using the second one: var EmployeeArr = new Array(‘Alex’, ‘Bob’, ‘Oliver’); Access to array elements  To access an array element, we use square brackets with an integer value of its index inside them. Let's get the value of two elements of the previously created value set EmployeeArr: var EmployeeArr = new Array(‘Alex’, ‘Bob’, ‘Oliver’);console.log (EmployeeArr[1]);  The index numbering starts from 0, which we should remember when referring to the N-th element. Its index will be N-1. In our case, it will equal 1. To change the value of an element, you need to assign a new value to the variable, as shown below: var EmployeeArr = new Array(‘Alex’, ‘Bob’, ‘Oliver’);EmployeeArr[1] = ‘Jack’; Now EmployeeArr contains 'Alex', 'Jack', and 'Oliver.' Now let's look at length, an important property that returns the length of an array in JavaScript. var EmployeeArr = new Array(‘Alex’, ‘Bob’, ‘Oliver’);console.log (EmployeeArr.length);  The length of EmployeArr in our case will be 3. - Array methods Array methods in JavaScript allow developers to work with data more efficiently and conveniently. Their use will help with conversion, sorting, searching, adding or removing elements.  In this article, we'll look at most of the existing JavaScript array methods, grouped by their work logic. Adding and removing elements There are four main methods to add or remove elements from an array: push(), pop(), shift(), and unshift(). push() adds one or more elements to the end of the value set. pop() deletes the last element. shift() deletes the first element. unshift() adds one or more elements to the beginning. Let's look at examples. We'll indicate the output of each method in the comment. var arr = new Array(‘Alex’, ‘Bob’, ‘Oliver’);arr.push (‘Jack’); // ‘Alex’, ‘Bob’, ‘Oliver’, ‘Jack’arr.unshift (‘Jacob’, ‘George’); //; ‘Jacob’, ‘George’, ‘Alex’, ‘Bob’, ‘Oliver’, ‘Jack’arr.pop (); // ‘Jacob’, ‘George’, ‘Alex’, ‘Bob’, ‘Oliver’arr.shift (); // ‘George’, ‘Alex’, ‘Bob’, ‘Oliver’ The pop() and shift() methods return the value of the deleted element, while push() and unshift() return the length of the modified array. In addition to the above methods, we should mention the universal splice() method. It allows you to insert, delete, or replace elements. Syntax of the splice() method: array.splice(startIndex, deleteCount, element1, element2, ...); Parameters:  startIndex is the index where the splice should begin. If this parameter exceeds the array length, the startIndex value will equal the length or take the difference between array.length and this number if a negative number is entered.  deleteCount is the number of elements to delete starting from startIndex. It can be equal to 0. In this case, nothing happens.  element1, element2, .... are the elements we add to the array (optional parameter). The splice() method returns the set of deleted values. In the example, let's look at several ways to apply splice(). The comments will specify the set of values after the method is executed. Below, we will remove two elements, starting with 3: var Dog = new Array(‘Beagle’, ‘Boxer’, ‘Bulldog’, ‘Corgi’, ‘Dachshund’, ‘Dalmatian’);Dog.splice ( 2, 2 ); // ‘Beagle’, ‘Boxer’, ‘Dachshund’, ‘Dalmatian’ Now let's remove one element starting at 4 and add 'Doberman': var Dog = new Array(‘Beagle’, ‘Boxer’, ‘Bulldog’, ‘Corgi’, ‘Dachshund’, ‘Dalmatian’);Dog.splice (3, 1, ‘Doberman’); // ‘Beagle’, ‘Boxer’, ‘Bulldog’, ‘Doberman’, ‘Dachshund’, ‘Dalmatian’ Iterating through an array The forEach() method is responsible for iterating array elements. arr.forEach(function callback(currentValue, index, array), thisValue); Parameters: callback is the main parameter, namely the callback function that will be executed once for each element. Its arguments are currentValue, index, array. currentValue is the element to be processed in the set. index is this element's index. array is the array of the selected element. thisValue is an optional parameter. It takes the value used as this when calling the function. The returned value is always undefined. Here are two examples: one using thisValue and one without it. The example without thisValue parameter: var Dog = new Array(‘Beagle’, ‘Boxer’, ‘Bulldog’, ‘Corgi’, ‘Dachshund’, ‘Dalmatian’);var NewDog = [ ];Dog.forEach (function (element) {NewDog.push (element);}) The result will be a new set of NewDog values that completely replicates Dog. Example with the thisValue parameter: var numbers = [1, 2, 3, 4, 5];var doubleNumbers = [ ];var myObject = {    double: function(element) {        return element * 2;    }};numbers.forEach (    function (element) {        doubleNumbers.push(this.double(element));     }, myObject); The result is a doubleNumbers set, which consists of numbers multiplied by two. Searching for an element in an array Such methods as indexOf(), lastIndexOf(), includes(), find(), findIndex(), and filter() help to search for items.  The indexOf() and lastIndexOf() methods search for the required value among all the elements and return its index at the first match. The former searches from the beginning of the array, while the latter searches from the end. Both methods will return -1 if the searched value is not found. Syntax of indexOf() and lastIndexOf() methods: array.indexOf( searchElement, fromIndex )array.lastIndexOf( searchElement, fromIndex ) The searchElement parameter is the same in both cases. It is the element we need to find. This is not the case with the fromIndex parameter. This is the starting index of the element to search for. When indexOf() is used, the fromIndex parameter defaults to zero. In the lastIndexOf() method, it is equal to array.length.  Let's try using these methods in the example below.  var Employee = new Array(‘Jacob’, ‘George’, ‘Alex’, ‘George’, ‘Oliver’, ‘Jack’);Employe.indexOf (‘George’);Employe.lastIndexOf (‘George’); The result of the indexOf() method will be 1 because the first match occurred with an element whose index is 1. In the case of lastIndexOf(), the result will be 3. The next search method is includes(). It determines whether the set of values contains a certain element, returning true or false depending on the result. The syntax of the includes() method: array.includes(searchElement, fromIndex) The parameters are exactly the same as in the previously discussed indexOf() and lastIndexOf() methods. The only difference between them is the return value. The fromIndex parameter is 0 by default. Here's an example of using the includes() method: var Employe = new Array(‘Jacob’, ‘George’, ‘Alex’, ‘Bob’, ‘Oliver’, ‘Jack’);Employe.includes (‘Alex’);Employe.includes (‘Jacob’, 3); The result in the first case will be true. In the second case, false. In practice, JavaScript often uses arrays of objects. In this case, you should search using the find() and findIndex() methods. arr.find(function callback(currentValue, index, array), thisValue); arr.findIndex(function callback(currentValue, index, array), thisValue);  Parameters of find() and findIndex() methods are similar to forEach(), so you can find their descriptions above. Let's look at an example of using the find() and findIndex() methods: var Employee = new Array(‘Jacob’, ‘George’, ‘Alex’, ‘Bob’, ‘Oliver’, ‘Jack’);Employee.find (element => element == ‘Jacob’);Employee.findIndex (element => element == ‘Jacob’); The return value of the find() method is 'Jacob', and of the findIndex() method is 0. The find() and findIndex() methods are suitable for searching one object. If the task is to find several objects, we can use another method: filter().  Syntax of the filter() method: var filteredArray = arr.filter(function(currentValue, index, array), thisValue);  The parameters of this method are also similar to the parameters of the forEach() method. Let's try it. Here we will search for employees who have worked in the company for less than two years: var Employee = [ {name: “Jacob”, experience: 3},{name: “George”, experience: 1},{name: “Alex”, experience: 1},{name: “Bob”, experience: 4}];var result = Employee.filter(element => element.experience <2); The method will result in a new array consisting of two employees with less than two years of experience. Methods for converting arrays The last group of array methods in JavaScript that we will describe in this article are array transformation methods. These include map(), flat(), flatmap(), sort(), and reverse(). Let's look at each of them in more detail below. map() organizes a new set of values with the result of calling the specified callback function for each element. The syntax of the map() method: var newArray = array.map(function(currentValue, index, arr), thisValue);  Once again, we see the same parameters as in the previously discussed methods. The return value of this method will be a new array with the elements of the callback function result. Let's consider the example that we already used earlier with forEach(), where all the set data were doubled. Now, let's use map() instead of forEach(). var numbers = [1, 2, 3, 4, 5];var doubleNumbers = numbers.map(     function double( element ) {        return element * 2;    });console.log(doubleNumbers); The result is doubleNumbers, a new set of values consisting of numbers 2, 4, 6, 8, 10.  When we use the map() method, the number of lines of code is noticeably reduced compared to forEach(). Also, the forEach() method is used only for iteration and returns nothing. map() returns a new array of the same length as the original array. Flat() allows you to interact with a nested set of values. It returns a new array with all sub-array values merged into it recursively  up to the specified level. The syntax of the flat() method: var newArray = arr.flat(depth); Here, depth specifies the level, i.e. how deep a nested array structure should be flattened. If the nesting depth is unknown, you can set the value of the parameter as Infinity. By default, it is equal to one. Let's consider an example of using the flat() method: var arr = [1, 2, , [4, 5, [6, 7]]];var NewArr = arr.flat(Infinity); The result is NewArr [1, 2, 4, 5, 6, 7]. It is worth noting that one was missing in the set of arr values. The flat() method removed the empty slots. We can combine the previous two methods into one: flatmap().  The syntax of the flatmap() method: var new_array = arr.flatMap(function callback(currentValue, index, arr), thisValue) Here is an example of using flatmap(): var arr = [[1], [2], [3], [4], [5]];var NewArr = arr.flatMap(element => element * 2); The result will be NewArr [2, 4, 6, 8, 10]. The sort() method allows sorting the data set. The default sorting order corresponds to the order of Unicode code characters. Syntax of the sort() method: array.sort(function(firstValue, secondValue));  You can specify a function that determines the sort order as a parameter. Example: var EmployeeArr = new Array(‘Jacob’, ‘George’, ‘Alex’, ‘Bob’, ‘Oliver’, ‘Jack’);EmployeeArr.sort (); The result of sorting will be EmployeArr ['Alex', 'Bob', 'George', 'Jack', 'Jacob', 'Oliver']. The reverse() method is also worth mentioning.  Syntax of the reverse() method: array.reverse(); In the example, let's change the order of employees’ names in the previously sorted array. var EmployeeArr = new Array(‘Jacob’, ‘George’, ‘Alex’, ‘Bob’, ‘Oliver’, ‘Jack’);EmployeeArr.sort ();var reversed = EmployeeArr.reverse(); The result of the reverse() method is EmployeArr ['Oliver', 'Jacob', 'Jack', 'George', 'Bob', 'Alex']. Conclusion This article has covered the basic, but not all, array methods in JavaScript. It is not easy to memorize them all at once. But it will become easier with experience in solving problems and using the methods in code. The main thing is to memorize how they work and what they are used for, and if necessary, you can always refer to this article to remember the syntax or see examples. Frequently Asked Questions What are the most commonly used JavaScript array methods? In day-to-day dev work, .map(), .filter(), .reduce(), .forEach(), and .slice() are your best friends — powerful and versatile. What is the difference between map and forEach in JavaScript? .map() transforms and returns a new array. .forEach() just runs code for each element without returning anything. How do I remove elements from an array in JavaScript? Use .filter() or .splice() depending on whether you need immutability or not.
16 June 2025 · 12 min to read
JavaScript

How to Use .map() in JavaScript

JavaScript supports several methods for iterating over arrays. Developers commonly use the traditional for loop and the less common .forEach() method. However, the most popular method is .map(). This method creates a new array by calling a function on every element of the original array. It avoids mutations and generates truly "clean" arrays.  This is different from mutation-based methods, which inevitably alter the original array in some way. In this article, we'll explore four ways to use .map() in JavaScript (though many more exist). Method 1: Calling Functions on Individual Array Elements When using .map() in JavaScript, the callback function is treated as an argument. The value of the array element at the time of execution becomes a required parameter of this function. You can use it to modify or create functions. Example: const sweetArray = [6, 7, 11, 13, 20]; const sweeterArray = sweetArray.map(sweetItem => {     return sweetItem * 2; }); console.log(sweeterArray); Output: [12, 14, 22, 26, 40] You can clean up and simplify the code: const makeSweeter = sweetItem => sweetItem * 2; const sweetArray = [6, 7, 11, 13, 20]; const sweeterArray = sweetArray.map(makeSweeter); console.log(sweeterArray); Output: [12, 14, 22, 26, 40] Using sweetArray.map(makeSweeter) makes the code more readable compared to the first version. Method 2: Converting Strings to Arrays You can use the .map() method from the Array prototype to convert strings. Instead of working directly with arrays, we use .call() to apply .map() to a string. Keep in mind that in JavaScript, strings can be treated like arrays of characters, allowing access to some array methods. Example: const name = "Hostman"; const map = Array.prototype.map; const newName = map.call(name, eachLetter => {     return `${eachLetter}e`; }); console.log(newName); Output: ["He", "oe", "se", "te", "me", "ae", "ne"] In this example, .map() is used to transform each character in the string by appending an "e". This works similarly to .split() and other methods that operate on string characters before transforming them back into an array. Method 3: Rendering Lists in JavaScript Libraries This use case is common in JavaScript frameworks like React. Here, you’ll need JSX syntax since .map() is used within it. For example: import React from "react"; import ReactDOM from "react-dom"; const names = ["cloud", "dbaas", "vps", "storage", "kubernetes"]; const NamesList = () => ( <div> <ul>{names.map(name => <li key={name}>{name}</li>)}</ul> </div> ); const rootElement = document.getElementById("root"); ReactDOM.render(<NamesList />, rootElement); In this example, the React component renders a <div> containing a list. The JavaScript .map() method is used to iterate over the array of names and generate individual list items. Rendering is handled by ReactDOM.render on a DOM element with the ID root. Method 4: Transforming Array Object Formats Another use case for .map() in JavaScript is transforming each object in an array and returning a new array of modified objects. This works much like traditional data processing. Example: const myUsers = [ { name: 'cloud', likes: 'scalability' }, { name: 'devops', likes: 'automation' }, { name: 'kube', likes: 'orchestration' } ]; const usersByLikes = myUsers.map(item => { const container = {}; container[item.name] = item.likes; container.popularity = item.name.length * 12; return container; }); console.log(usersByLikes); Output: [   { cloud: 'scalability', popularity: 60 },   { devops: 'automation', popularity: 72 },   { kube: 'orchestration', popularity: 48 } ] In this example, each object in the array is modified using bracket notation and object property assignments. This approach is useful for transforming and condensing incoming data before using it in client-side applications. Conclusion We reviewed four main ways to use the .map() method in JavaScript. You can expand its capabilities by combining it with other methods. For more detailed information, refer to the official documentation.
11 June 2025 · 4 min to read

Do you have questions,
comments, or concerns?

Our professionals are available to assist you at any moment,
whether you need help or are just unsure of where to start.
Email us
Hostman's Support