JavaScript .set()
Published Dec 31, 2021Updated Mar 11, 2024
Contribute to Docs
Stores or updates entries of key-value pairs in a Map object.
Syntax
The .set() method accepts two parameters, the key and the value, and assigns the entry to a Map object:
const map = new Map();map.set(key, value);
The key and value can either be an object or a variable of any data type.
Example
Key-value pairs are stored in a Map object using the .set() method.
const fruits = new Map();fruits.set('Apples', 5);fruits.set('Oranges', 8);
The example above uses .set() to store two entries in the fruits map: one for 5 apples and another for 8 oranges. These entries can be overwritten and have their values changed with .set() as well:
fruits.set('Apples', 2);console.log(fruits);
The output will be:
Map(2) { 'Apples' => 2, 'Oranges' => 8 }
Chaining
Instead of executing separate calls to .set() for the same Map object, multiple .set()s can be “chained” together:
Codebyte Example
Run the example below to understand better the usage of the .set() method:
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn JavaScript on Codecademy
- Front-end engineers work closely with designers to make websites beautiful, functional, and fast.
- Includes 34 Courses
- With Professional Certification
- Beginner Friendly.115 hours
- Learn how to use JavaScript — a powerful and flexible programming language for adding website interactivity.
- Beginner Friendly.15 hours