Chuyển tới nội dung
Home » Js Map Console Log | Description

Js Map Console Log | Description

Beyond Console Log in 100 Seconds

Solution

The solution is to convert Sets and Maps to arrays before logging out. The following code checks the type and applies the correct logging rule

const objectPrintFormatter = (toPrint) => { if(toPrint instanceof Set || toPrint instanceof Map) { return JSON.stringify(Array.from(toPrint)); } else if(toPrint instanceof Object) { return JSON.stringify(toPrint); } return toPrint; } const array = [‘sun’, ‘sea’, ‘surf’]; const set = new Set([‘sun’, ‘sea’, ‘surf’]); const map = new Map([[1, ‘sun’], [2, ‘sea’], [3, ‘surf’]]); const object = { sun: 1, sea: 2, surf: 3 }; console.log(`array ${objectPrintFormatter(array)}`); console.log(`set ${objectPrintFormatter(set)}`); console.log(`map ${objectPrintFormatter(map)}`); console.log(`object ${objectPrintFormatter(object)}`);

Output

array [“sun”,”sea”,”surf”] set [“sun”,”sea”,”surf”] map [[1,”sun”],[2,”sea”],[3,”surf”]] object {“sun”:1,”sea”:2,”surf”:3}

Now each type logs its contents to the console rather than appearing empty. The key thing to remember is that if ES6 Sets and Maps appear empty, they may not be. It could just be the way they are being logged out to the console.

Examples

Printing the contents of a Map object

The following code logs a line for each element in an

Map

object:


function logMapElements(value, key, map) { console.log(`map.get('${key}') = ${value}`); } new Map([ ["foo", 3], ["bar", {}], ["baz", undefined], ]).forEach(logMapElements); // Logs: // "map.get('foo') = 3" // "map.get('bar') = [object Object]" // "map.get('baz') = undefined"

Beyond Console Log in 100 Seconds
Beyond Console Log in 100 Seconds

Console.log for ….

All examples have been run through Node.js. The same holds true if running through a browser i.e. with React or Angular.

Array

Example

const array = [‘sun’, ‘sea’, ‘surf’]; console.log(array); console.log(`array ${array}`); console.log(`array ${JSON.stringify(array)}`);

Output

[ ‘sun’, ‘sea’, ‘surf’ ] array sun,sea,surf array [“sun”,”sea”,”surf”]

The array plays most nicely with console.log. It displays it’s contents in all circumstances

Object

Example

const object = { sun: 1, sea: 2, surf: 3 }; console.log(object); console.log(`array ${object}`); console.log(`array ${JSON.stringify(object)}`);

Output

{ sun: 1, sea: 2, surf: 3 } object [object Object] object {“sun”:1,”sea”:2,”surf”:3}

Objects will only display correctly in a template literal if the JSON is stringified first. This is why I habitually use JSON.stringify when logging to the console.

ES6 Set

Example

const set = new Set([‘sun’, ‘sea’, ‘surf’]); console.log(set); console.log(`set ${set}`); console.log(`set ${JSON.stringify(set)}`);

Output

Set(3) { ‘sun’, ‘sea’, ‘surf’ } set [object Set] set {}

As with arrays and objects, logging the object directly works nicely but wrapping in a template literal hides the content i.e. when it is coerced to a string. The trick of JSON.stringifying the set doesn’t help now.

ES6 Map

Example

const map = new Map([[1, ‘sun’], [2, ‘sea’], [3, ‘surf’]]); console.log(map); console.log(`map ${map}`); console.log(`map ${JSON.stringify(map)}`);

Output

Map(3) { 1 => ‘sun’, 2 => ‘sea’, 3 => ‘surf’ } map [object Map] map {}

As with the Set, Map only logs directly, not when combined in a template literal

Overall

  • Logging directly always works
  • Arrays can be logged in a template literal
  • Objects can be logged in a template literal if the JSON is stringified first
  • Sets and Maps don’t log with template literals – they appear empty

Advantages of Map:

Map object provided by ES6. A key of a Map may occur once, which will be unique in the map’s collection. There are slight advantages to using a map rather than an object.

  • Accidental Keys & Security: No default keys are stored, only contain what’s explicitly put into them. Because of that, it’s safe to use.
  • Key Types & Order: It can be any value as a key function, object anything. And the order is straightforward way in the order of entry insertion.
  • Size: Because of the size property a map can be easily retrieved.
  • Performance: Any operation can be performed on math so easily in a better way.
  • Serialization and parsing: We can create our own serialization and parsing support for Map by using JSON.stringify() and JSON.parse() methods.
JavaScript map() method in 7 minutes! 🗺
JavaScript map() method in 7 minutes! 🗺

Solution

The solution is to convert Sets and Maps to arrays before logging out. The following code checks the type and applies the correct logging rule

const objectPrintFormatter = (toPrint) => { if(toPrint instanceof Set || toPrint instanceof Map) { return JSON.stringify(Array.from(toPrint)); } else if(toPrint instanceof Object) { return JSON.stringify(toPrint); } return toPrint; } const array = [‘sun’, ‘sea’, ‘surf’]; const set = new Set([‘sun’, ‘sea’, ‘surf’]); const map = new Map([[1, ‘sun’], [2, ‘sea’], [3, ‘surf’]]); const object = { sun: 1, sea: 2, surf: 3 }; console.log(`array ${objectPrintFormatter(array)}`); console.log(`set ${objectPrintFormatter(set)}`); console.log(`map ${objectPrintFormatter(map)}`); console.log(`object ${objectPrintFormatter(object)}`);

Output

array [“sun”,”sea”,”surf”] set [“sun”,”sea”,”surf”] map [[1,”sun”],[2,”sea”],[3,”surf”]] object {“sun”:1,”sea”:2,”surf”:3}

Now each type logs its contents to the console rather than appearing empty. The key thing to remember is that if ES6 Sets and Maps appear empty, they may not be. It could just be the way they are being logged out to the console.

Advantages of Map:

Map object provided by ES6. A key of a Map may occur once, which will be unique in the map’s collection. There are slight advantages to using a map rather than an object.

  • Accidental Keys & Security: No default keys are stored, only contain what’s explicitly put into them. Because of that, it’s safe to use.
  • Key Types & Order: It can be any value as a key function, object anything. And the order is straightforward way in the order of entry insertion.
  • Size: Because of the size property a map can be easily retrieved.
  • Performance: Any operation can be performed on math so easily in a better way.
  • Serialization and parsing: We can create our own serialization and parsing support for Map by using JSON.stringify() and JSON.parse() methods.
JS Basic - 10 : Hàm console.log trong Javascript
JS Basic – 10 : Hàm console.log trong Javascript

Problem

Here’s something that has tripped me up a few times now – when you console.log out the contents of a Set or Map in ES6 the it looks empty which isn’t true.

Example

const set = new Set([‘sun’, ‘sea’, ‘surf’]); console.log(`Set output ${JSON.stringify(set)}`);

Output

Set output {}

The console tells me it is empty and it’s not. This is the same with Maps. This contrasts with Arrays and objects which show the content if logged out using this code.

If you are using console.log to quickly debug then this is a pain. I often wrap the output in template literals to add context and it’s that string conversion that hides the content. It turns out that objects, arrays, maps, sets and objects all behave slightly differently when logging to the console. So in detail …

Javascript


let map1 =


new


Map();


map1.set(


"first name"


"sumit"


);


map1.set(


"last name"


"ghosh"


);


map1.set(


"website"


"geeksforgeeks"


.set(


"friend 1"


"gourav"


.set(


"friend 2"


"sourav"


);


console.log(map1);


console.log(


"map1 has website ? "


map1.has(


"website"


));


console.log(


"map1 has friend 3 ? "


map1.has(


"friend 3"


));


console.log(


"get value for key website "


map1.get(


"website"


));


console.log(


"get value for key friend 3 "


map1.get(


"friend 3"


));


console.log(


"delete element with key website "


+ map1.


delete


"website"


));


console.log(


"map1 has website ? "


map1.has(


"website"


));


console.log(


"delete element with key website "


map1.


delete


"friend 3"


));


map1.clear();


console.log(map1);

Output

Map(5) {
‘first name’ => ‘sumit’,
‘last name’ => ‘ghosh’,
‘website’ => ‘geeksforgeeks’,
‘friend 1’ => ‘gourav’,
‘friend 2’ => ‘sourav’
}
map1 has website ? true
map1 has friend 3 ? false
get…

You're not using these Console Logging Tricks... Yet!!!
You’re not using these Console Logging Tricks… Yet!!!

Javascript


let map1 =


new


Map();


map1.set(


"FirstName"


"Shobhit"


);


map1.set(


"LastName"


"Sharma"


);


map1.set(


"website"


"GeeksforGeeks"


);


console.log(map1);

Output

Map(3) {
‘FirstName’ => ‘Shobhit’,
‘LastName’ => ‘Sharma’,
‘website’ => ‘GeeksforGeeks’
}

Example 3: This example explains the use of Map methods like has(), get(), delete(), and clear().

new Map()

In this we use

new Map()

constructor,

Example: In this example, a Map named

prices

is created to associate product names with their respective prices, allowing for efficient retrieval and management of price information.

// Creating a Map for product pricesconst prices = new Map([ [“Laptop”, 1000], [“Smartphone”, 800], [“Tablet”, 400] ]);

What is console.log in JavaScript? | JS for Beginners Ep. 1
What is console.log in JavaScript? | JS for Beginners Ep. 1


Note: This answer is only relevant to the repl.it sandbox environment OP is using

Since you said in the comments that you’re using

repl.it

, there’s a trick you can use to write your own “logging strategy”.

Note that you shouldn’t use this trick in production, mainly because it edits a native prototype. In some Node environment, in your own code, it could be useful though.

The idea is to create an

inspect

method for

Map

that iterates over the

entries

:

Map.prototype.inspect = function() {
  return `Map(${mapEntriesToString(this.entries())})`
}

function mapEntriesToString(entries) {
  return Array
    .from(entries, ([k, v]) => `\n  ${k}: ${v}`)
    .join("") + "\n";
}

You can see that repl.it supports it


here

console.log(new Map([["a", 1], ["b", 2]]));
// Logs:
/*
Map(
  a: 1
  b: 2
)
*/


Note: This answer is only relevant to the repl.it sandbox environment OP is using

Since you said in the comments that you’re using

repl.it

, there’s a trick you can use to write your own “logging strategy”.

Note that you shouldn’t use this trick in production, mainly because it edits a native prototype. In some Node environment, in your own code, it could be useful though.

The idea is to create an

inspect

method for

Map

that iterates over the

entries

:

Map.prototype.inspect = function() {
  return `Map(${mapEntriesToString(this.entries())})`
}

function mapEntriesToString(entries) {
  return Array
    .from(entries, ([k, v]) => `\n  ${k}: ${v}`)
    .join("") + "\n";
}

You can see that repl.it supports it


here

console.log(new Map([["a", 1], ["b", 2]]));
// Logs:
/*
Map(
  a: 1
  b: 2
)
*/

Map

The

Map

object holds key-value pairs and remembers the original insertion order of the keys.
Any value (both objects and primitive values) may be used as either a key or a value.

Javascript


let map1 =


new


Map([


[1, 2],


[2, 3],


[4, 5]


]);


console.log(


"Map1"


);


console.log(map1);


let map2 =


new


Map([


"firstname"


"sumit"


],


"lastname"


"ghosh"


],


"website"


"geeksforgeeks"


]);


console.log(


"Map2"


);


console.log(map2);

Output

Map1
Map(3) { 1 => 2, 2 => 3, 4 => 5 }
Map2
Map(3) {
‘firstname’ => ‘sumit’,
‘lastname’ => ‘ghosh’,
‘website’ => ‘geeksforgeeks’
}

Example 2: This example adds elements to the map using set() method.

Learn JavaScript ARROW FUNCTIONS in 8 minutes! 🎯
Learn JavaScript ARROW FUNCTIONS in 8 minutes! 🎯

Description


Map

objects are collections of key-value pairs. A key in the

Map

may only occur once; it is unique in the

Map

‘s collection. A

Map

object is iterated by key-value pairs — a

for...of

loop returns a 2-member array of

[key, value]

for each iteration. Iteration happens in insertion order, which corresponds to the order in which each key-value pair was first inserted into the map by the

set()

method (that is, there wasn’t a key with the same value already in the map when

set()

was called).

The specification requires maps to be implemented “that, on average, provide access times that are sublinear on the number of elements in the collection”. Therefore, it could be represented internally as a hash table (with O(1) lookup), a search tree (with O(log(N)) lookup), or any other data structure, as long as the complexity is better than O(N).

Key equality

Value equality is based on the SameValueZero algorithm. (It used to use SameValue, which treated and

-0

as different. Check browser compatibility.) This means

NaN

is considered the same as

NaN

(even though

NaN !== NaN

) and all other values are considered equal according to the semantics of the

===

operator.

ObjectsMaps


Object

is similar to

Map

—both let you set keys to
values, retrieve those values, delete keys, and detect whether something is
stored at a key. For this reason (and because there were no built-in
alternatives),

Object

has been used as

Map

historically.

However, there are important differences that make

Map

preferable in some
cases:

Map Object
Accidental Keys

An

Note: This can be bypassed by using

Security

Setting user-provided key-value pairs on an

Key Types The keys of an
Key Order

The keys in

Although the keys of an ordinary

The order was first defined for own properties only in ECMAScript
2015; ECMAScript 2020 defines order for inherited properties as well.
But note that no single mechanism
iterates
all of an object’s properties; the various mechanisms
each include different subsets of properties.
(

Size

The number of items in a Determining the number of items in an
Iteration

Note:

Performance

Performs better in scenarios involving frequent additions and removals of key-value pairs.

Not optimized for frequent additions and removals of key-value pairs.

Serialization and parsing

No native support for serialization or parsing.

(But you can build your own serialization and parsing support for

Native support for serialization from

Native support for parsing from JSON to

Setting object properties

Setting Object properties works for Map objects as well, and can cause considerable confusion.

Therefore, this appears to work in a way:


const wrongMap = new Map(); wrongMap["bla"] = "blaa"; wrongMap["bla2"] = "blaaa2"; console.log(wrongMap); // Map { bla: 'blaa', bla2: 'blaaa2' }

But that way of setting a property does not interact with the Map data structure. It uses the feature of the generic object. The value of ‘bla’ is not stored in the Map for queries. Other operations on the data fail:


wrongMap.has("bla"); // false wrongMap.delete("bla"); // false console.log(wrongMap); // Map { bla: 'blaa', bla2: 'blaaa2' }

The correct usage for storing data in the Map is through the

set(key, value)

method.


const contacts = new Map(); contacts.set("Jessie", { phone: "213-555-1234", address: "123 N 1st Ave" }); contacts.has("Jessie"); // true contacts.get("Hilary"); // undefined contacts.set("Hilary", { phone: "617-555-4321", address: "321 S 2nd St" }); contacts.get("Jessie"); // {phone: "213-555-1234", address: "123 N 1st Ave"} contacts.delete("Raymond"); // false contacts.delete("Jessie"); // true console.log(contacts.size); // 1

Map-like browser APIs

Browser

Map

-like objects (or “maplike objects”) are Web API interfaces that behave in many ways like a

Map

.

Just like

Map

, entries can be iterated in the same order that they were added to the object.

Map

-like objects and

Map

also have properties and methods that share the same name and behavior.
However unlike

Map

they only allow specific predefined types for the keys and values of each entry.

The allowed types are set in the specification IDL definition.
For example,

RTCStatsReport

is a

Map

-like object that must use strings for keys and objects for values.
This is defined in the specification IDL below:


interface RTCStatsReport { readonly maplike

; };


Map

-like objects are either read-only or read-writable (see the

readonly

keyword in the IDL above).

  • Read-only

    Map

    -like objects have the property

    size

    , and the methods:

    entries()

    ,

    forEach()

    ,

    get()

    ,

    has()

    ,

    keys()

    ,

    values()

    , and

    @@iterator

    .
  • Writeable

    Map

    -like objects additionally have the methods:

    clear()

    ,

    delete()

    , and

    set()

    .

The methods and properties have the same behavior as the equivalent entities in

Map

, except for the restriction on the types of the keys and values.

The following are examples of read-only

Map

-like browser objects:

Problem

Here’s something that has tripped me up a few times now – when you console.log out the contents of a Set or Map in ES6 the it looks empty which isn’t true.

Example

const set = new Set([‘sun’, ‘sea’, ‘surf’]); console.log(`Set output ${JSON.stringify(set)}`);

Output

Set output {}

The console tells me it is empty and it’s not. This is the same with Maps. This contrasts with Arrays and objects which show the content if logged out using this code.

If you are using console.log to quickly debug then this is a pain. I often wrap the output in template literals to add context and it’s that string conversion that hides the content. It turns out that objects, arrays, maps, sets and objects all behave slightly differently when logging to the console. So in detail …

Best VSCode Extensions I'm in Love with
Best VSCode Extensions I’m in Love with

The complete map() method syntax

The syntax for the

map()

method is as follows:


arr.map(function(element, index, array){ }, this);

The callback

function()

is called on each array element, and the

map()

method always passes the current

element

, the

index

of the current element, and the whole

array

object to it.

The

this

argument will be used inside the callback function. By default, its value is

undefined

. For example, here’s how to change the

this

value to the number

80

:


let arr = [2, 3, 5, 7] arr.map(function(element, index, array){ console.log(this) // 80 }, 80);

You can also test the other arguments using

console.log()

if you’re interested:


let arr = [2, 3, 5, 7] arr.map(function(element, index, array){ console.log(element); console.log(index); console.log(array); return element; }, 80);

Here’s an interactive scrim that goes over the complete syntax:

And that’s all you need to know about the

Array.map()

method. Most often, you will only use the

element

argument inside the callback function while ignoring the rest. That’s what I usually do in my daily projects 🙂

Instance methods


Map.prototype.clear()

Removes all key-value pairs from the


Map

object.


Map.prototype.delete()

Returns


true

if an element in the

Map

object existed and has been removed, or

false

if the element does not exist.

map.has(key)

will return

false

afterwards.


Map.prototype.entries()

Returns a new Iterator object that contains a two-member array of


[key, value]

for each element in the

Map

object in insertion order.


Map.prototype.forEach()

Calls


callbackFn

once for each key-value pair present in the

Map

object, in insertion order. If a

thisArg

parameter is provided to

forEach

, it will be used as the

this

value for each callback.


Map.prototype.get()

Returns the value associated to the passed key, or


undefined

if there is none.


Map.prototype.has()

Returns a boolean indicating whether a value has been associated with the passed key in the


Map

object or not.


Map.prototype.keys()

Returns a new Iterator object that contains the keys for each element in the


Map

object in insertion order.


Map.prototype.set()

Sets the value for the passed key in the


Map

object. Returns the

Map

object.


Map.prototype.values()

Returns a new Iterator object that contains the values for each element in the


Map

object in insertion order.


Map.prototype[@@iterator]()

Returns a new Iterator object that contains a two-member array of


[key, value]

for each element in the

Map

object in insertion order.

O que você não sabia sobre Programação Reativa - Recriando o RxJS com Web Streams
O que você não sabia sobre Programação Reativa – Recriando o RxJS com Web Streams

Javascript


let map1 =


new


Map();


map1.set(


"FirstName"


"Shobhit"


);


map1.set(


"LastName"


"Sharma"


);


map1.set(


"website"


"GeeksforGeeks"


);


console.log(map1);

Output

Map(3) {
‘FirstName’ => ‘Shobhit’,
‘LastName’ => ‘Sharma’,
‘website’ => ‘GeeksforGeeks’
}

Example 3: This example explains the use of Map methods like has(), get(), delete(), and clear().

Description

The

forEach

method executes the provided

callback

once for each key of the
map which actually exist. It is not invoked for keys which have been deleted.
However, it is executed for values which are present but have the value

undefined

.


callback

is invoked with three arguments:

  • the entry’s

    value
  • the entry’s

    key
  • the

    Map

    object being traversed

If a

thisArg

parameter is provided to

forEach

, it will be passed to

callback

when invoked, for use as its

this

value. Otherwise, the value

undefined

will be passed for use as its

this

value. The

this

value
ultimately observable by

callback

is determined according to
the usual rules for determining the

this

seen by a function.

Each value is visited once, except in the case when it was deleted and re-added
before

forEach

has finished.

callback

is not invoked for values deleted
before being visited. New values added before

forEach

has finished will be
visited.

JavaScript reduce() method in 5 minutes! ♻
JavaScript reduce() method in 5 minutes! ♻

Examples

Mapping an array of numbers to an array of square roots

The following code takes an array of numbers and creates a new array containing the square roots of the numbers in the first array.


const numbers = [1, 4, 9]; const roots = numbers.map((num) => Math.sqrt(num)); // roots is now [1, 2, 3] // numbers is still [1, 4, 9]

Using map to reformat objects in an array

The following code takes an array of objects and creates a new array containing the newly reformatted objects.


const kvArray = [ { key: 1, value: 10 }, { key: 2, value: 20 }, { key: 3, value: 30 }, ]; const reformattedArray = kvArray.map(({ key, value }) => ({ [key]: value })); console.log(reformattedArray); // [{ 1: 10 }, { 2: 20 }, { 3: 30 }] console.log(kvArray); // [ // { key: 1, value: 10 }, // { key: 2, value: 20 }, // { key: 3, value: 30 } // ]

Using parseInt() with map()

It is common to use the callback with one argument (the element being traversed). Certain functions are also commonly used with one argument, even though they take additional optional arguments. These habits may lead to confusing behaviors. Consider:


["1", "2", "3"].map(parseInt);

While one might expect

[1, 2, 3]

, the actual result is

[1, NaN, NaN]

.


parseInt

is often used with one argument, but takes two. The first is an expression and the second is the radix to the callback function,

Array.prototype.map

passes 3 arguments: the element, the index, and the array. The third argument is ignored by

parseInt

— but not the second one! This is the source of possible confusion.

Here is a concise example of the iteration steps:


/* first iteration (index is 0): */ parseInt("1", 0); // 1 /* second iteration (index is 1): */ parseInt("2", 1); // NaN /* third iteration (index is 2): */ parseInt("3", 2); // NaN

To solve this, define another function that only takes one argument:


["1", "2", "3"].map((str) => parseInt(str, 10)); // [1, 2, 3]

You can also use the

Number

function, which only takes one argument:


["1", "2", "3"].map(Number); // [1, 2, 3] // But unlike parseInt(), Number() will also return a float or (resolved) exponential notation: ["1.1", "2.2e2", "3e300"].map(Number); // [1.1, 220, 3e+300] // For comparison, if we use parseInt() on the array above: ["1.1", "2.2e2", "3e300"].map((str) => parseInt(str, 10)); // [1, 2, 3]

See A JavaScript optional argument hazard by Allen Wirfs-Brock for more discussions.

Mapped array contains undefined

When

undefined

or nothing is returned, the resulting array contains

undefined

. If you want to delete the element instead, chain a

filter()

method, or use the

flatMap()

method and return an empty array to signify deletion.


const numbers = [1, 2, 3, 4]; const filteredNumbers = numbers.map((num, index) => { if (index < 3) { return num; } }); // index goes from 0, so the filterNumbers are 1,2,3 and undefined. // filteredNumbers is [1, 2, 3, undefined] // numbers is still [1, 2, 3, 4]

Side-effectful mapping

The callback can have side effects.


const cart = [5, 15, 25]; let total = 0; const withTax = cart.map((cost) => { total += cost; return cost * 1.2; }); console.log(withTax); // [6, 18, 30] console.log(total); // 45

This is not recommended, because copying methods are best used with pure functions. In this case, we can choose to iterate the array twice.


const cart = [5, 15, 25]; const total = cart.reduce((acc, cost) => acc + cost, 0); const withTax = cart.map((cost) => cost * 1.2);

Sometimes this pattern goes to its extreme and the only useful thing that

map()

does is causing side effects.


const products = [ { name: "sports car" }, { name: "laptop" }, { name: "phone" }, ]; products.map((product) => { product.price = 100; });

As mentioned previously, this is an anti-pattern. If you don’t use the return value of

map()

, use

forEach()

or a

for...of

loop instead.


products.forEach((product) => { product.price = 100; });

Or, if you want to create a new array instead:


const productsWithPrice = products.map((product) => { return { ...product, price: 100 }; });

Using the third argument of callbackFn

The

array

argument is useful if you want to access another element in the array, especially when you don’t have an existing variable that refers to the array. The following example first uses

filter()

to extract the positive values and then uses

map()

to create a new array where each element is the average of its neighbors and itself.


const numbers = [3, -1, 1, 4, 1, 5, 9, 2, 6]; const averaged = numbers .filter((num) => num > 0) .map((num, idx, arr) => { // Without the arr argument, there's no way to easily access the // intermediate array without saving it to a variable. const prev = arr[idx - 1]; const next = arr[idx + 1]; let count = 1; let total = num; if (prev !== undefined) { count++; total += prev; } if (next !== undefined) { count++; total += next; } const average = total / count; // Keep two decimal places return Math.round(average * 100) / 100; }); console.log(averaged); // [2, 2.67, 2, 3.33, 5, 5.33, 5.67, 4]

The

array

argument is not the array that is being built — there is no way to access the array being built from the callback function.

Using map() on sparse arrays

A sparse array remains sparse after

map()

. The indices of empty slots are still empty in the returned array, and the callback function won’t be called on them.


console.log( [1, , 3].map((x, index) => { console.log(`Visit ${index}`); return x * 2; }), ); // Visit 0 // Visit 2 // [2, empty, 6]

Calling map() on non-array objects

The

map()

method reads the

length

property of

this

and then accesses each property whose key is a nonnegative integer less than

length

.


const arrayLike = { length: 3, 0: 2, 1: 3, 2: 4, 3: 5, // ignored by map() since length is 3 }; console.log(Array.prototype.map.call(arrayLike, (x) => x ** 2)); // [ 4, 9, 16 ]

This example shows how to iterate through a collection of objects collected by

querySelectorAll

. This is because

querySelectorAll

returns a

NodeList

(which is a collection of objects). In this case, we return all the selected

option

s’ values on the screen:


const elems = document.querySelectorAll("select option:checked"); const values = Array.prototype.map.call(elems, ({ value }) => value);

You can also use

Array.from()

to transform

elems

to an array, and then access the

map()

method.

Map.set():

You can add elements to a Map with the

set()

method.

Example: In this example, the

Map.set()

method is employed to add product prices to the Map named

prices

.

// Creating a Map for product prices const prices = new Map(); // Using Map.set() to add product prices prices.set(‘Laptop’, 1000); prices.set(‘Smartphone’, 800); // The Map now contains { ‘Laptop’ => 1000, ‘Smartphone’ => 800 }

Example 1: In this example, we will create a basic map object

Build and Deploy a Google Maps Travel Companion Application | React.js
Build and Deploy a Google Maps Travel Companion Application | React.js

Syntax


forEach(callbackFn) forEach(callbackFn, thisArg)

Parameters


callbackFn

A function to execute for each entry in the map. The function is called with the following arguments:


thisArg

Optional

A value to use as


this

when executing

callbackFn

.

Return value

None (

undefined

).

Thanks for reading this tutorial

If you enjoyed this article and want to take your JavaScript skills to the next level, I recommend you check out my new book Beginning Modern JavaScript here.

The book is designed to be easy to understand and accessible to anyone looking to learn JavaScript. It provides a step-by-step gentle guide that will help you understand how to use JavaScript to create a dynamic application.

Here’s my promise: You will actually feel like you understand what you’re doing with JavaScript.

Until next time!

Map.prototype.forEach()

The

forEach()

method of

Map

instances executes a provided function once per each key/value
pair in this map, in insertion order.

Auth.js V5 From Scratch
Auth.js V5 From Scratch

Useful Links

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Maphttps://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SetMap and Set official documentation fromt the ES6 standard.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringifyJSON.stringify documentation

https://codebuckets.com/2018/06/17/extending-typescript-to-serialise-map-objects-to-json/I’ve an additional post about extending the ES6 Map Typescript definition to include a

toJSON

which also solves this issue of ES6 types not displaying their content in the console. Embarrasingly, I forgot that I’d written this post a few years ago on the same topic. I think this latest post adds some additional context by comparing the functionality across several different objects, so I’ll leave both in.

// doesn’t works
[1,2,3].map(console.log);
// works
var log = function(msg) { console.log(msg); };
[1,2,3].map(log);
[1,2,3].forEach(log);

Any clue so far?

Found it.

when you call [1,2,3].map(console.log); you are detaching the log function from console, but in the log function it refers to “this”, when you use:console.log(“foo”);The “this” in function log is pointing to console, but if you:var l = console.log;l(“foo”);In this call, “this” is pointing to window.

captbaritone
commented
Feb 16, 2017

Nice! Thanks for digging into this.

I’d note that in functional programmer-speak, an array is a functor, and thus map should return an array of the same “shape”, simply with possibly transformed members. Since console.log returns undefined, I don’t know if map is the right way to do what I think you’re trying to do, which is simply console.log out all the members of a collection.

(But I’m here because I had a similar question! Why not?!)

chewdev
commented
May 28, 2018

Yeah, we can make it work by just passing each element to console.log like:[1, 2, 3].map((val) => console.log(val));It works because map isn’t being assigned to a variable, but I think the more proper way would be using forEach, as map is needlessly returning an array of undefined elements:[1, 2, 3].forEach((val) => console.log(val));

corollari
commented
May 10, 2020

For anybody looking at this, now

[1,2,3].map(console.log);

does work with the latest versions of v8.

BLWTF
commented
Jan 10, 2022

yeah @corollari but it prints a weird array.

dpecos
commented
Jan 10, 2022

To clarify with examples:


> [1,2,3].map(console.log); 1 0 [ 1, 2, 3 ] 2 1 [ 1, 2, 3 ] 3 2 [ 1, 2, 3 ] [ undefined, undefined, undefined ]

vs


> [1, 2, 3].map((val) => console.log(val)); 1 2 3 [ undefined, undefined, undefined ] >

Let’s say we want to log

obj

inside this

.map()

function here:


const arr = [ { val: 1 }, { val: 2 }, { val: 3 } ]; const nums = arr.map(obj => obj.val*2);

Well, dang! Now we have to convert this to a multi-line function, right?


const nums = arr.map(obj => { console.log(obj); return obj.val * 2; });

Instead we can use the logical OR (

||

) operator with

console.log()

to short-circuit evaluate the return statement:


const nums = arr.map(obj => console.log(obj) || obj.val*2);

This works because

console.log()

evaluates to

undefined

so our OR (

||

) opertator will evalutate the next operand which is the return portion of the function and will return the same result as the original example!

This is especially usefull with JSX where we commonly render components with implicit return statements:


export default function App() { return (

Syntax


map(callbackFn) map(callbackFn, thisArg)

Parameters


callbackFn

A function to execute for each element in the array. Its return value is added as a single element in the new array. The function is called with the following arguments:


thisArg

Optional

A value to use as


this

when executing

callbackFn

. See iterative methods.

Return value

A new array with each element being the result of the callback function.

JavaScript filter() method in 6 minutes! 🚰
JavaScript filter() method in 6 minutes! 🚰

Examples

Using the Map object


const myMap = new Map(); const keyString = "a string"; const keyObj = {}; const keyFunc = function () {}; // setting the values myMap.set(keyString, "value associated with 'a string'"); myMap.set(keyObj, "value associated with keyObj"); myMap.set(keyFunc, "value associated with keyFunc"); console.log(myMap.size); // 3 // getting the values console.log(myMap.get(keyString)); // "value associated with 'a string'" console.log(myMap.get(keyObj)); // "value associated with keyObj" console.log(myMap.get(keyFunc)); // "value associated with keyFunc" console.log(myMap.get("a string")); // "value associated with 'a string'", because keyString === 'a string' console.log(myMap.get({})); // undefined, because keyObj !== {} console.log(myMap.get(function () {})); // undefined, because keyFunc !== function () {}

Using NaN as Map keys


NaN

can also be used as a key. Even though every

NaN

is
not equal to itself (

NaN !== NaN

is true), the following example works because

NaN

s are indistinguishable from each other:


const myMap = new Map(); myMap.set(NaN, "not a number"); myMap.get(NaN); // "not a number" const otherNaN = Number("foo"); myMap.get(otherNaN); // "not a number"

Iterating Map with for...of

Maps can be iterated using a

for...of

loop:


const myMap = new Map(); myMap.set(0, "zero"); myMap.set(1, "one"); for (const [key, value] of myMap) { console.log(`${key} = ${value}`); } // 0 = zero // 1 = one for (const key of myMap.keys()) { console.log(key); } // 0 // 1 for (const value of myMap.values()) { console.log(value); } // zero // one for (const [key, value] of myMap.entries()) { console.log(`${key} = ${value}`); } // 0 = zero // 1 = one

Iterating Map with forEach()

Maps can be iterated using the

forEach()

method:


myMap.forEach((value, key) => { console.log(`${key} = ${value}`); }); // 0 = zero // 1 = one

Relation with Array objects


const kvArray = [ ["key1", "value1"], ["key2", "value2"], ]; // Use the regular Map constructor to transform a 2D key-value Array into a map const myMap = new Map(kvArray); console.log(myMap.get("key1")); // "value1" // Use Array.from() to transform a map into a 2D key-value Array console.log(Array.from(myMap)); // Will show you exactly the same Array as kvArray // A succinct way to do the same, using the spread syntax console.log([...myMap]); // Or use the keys() or values() iterators, and convert them to an array console.log(Array.from(myMap.keys())); // ["key1", "key2"]

Cloning and merging Maps

Just like

Array

s,

Map

s can be cloned:


const original = new Map([[1, "one"]]); const clone = new Map(original); console.log(clone.get(1)); // one console.log(original === clone); // false (useful for shallow comparison)

Note: Keep in mind that the data itself is not cloned.

Maps can be merged, maintaining key uniqueness:


const first = new Map([ [1, "one"], [2, "two"], [3, "three"], ]); const second = new Map([ [1, "uno"], [2, "dos"], ]); // Merge two maps. The last repeated key wins. // Spread syntax essentially converts a Map to an Array const merged = new Map([...first, ...second]); console.log(merged.get(1)); // uno console.log(merged.get(2)); // dos console.log(merged.get(3)); // three

Maps can be merged with Arrays, too:


const first = new Map([ [1, "one"], [2, "two"], [3, "three"], ]); const second = new Map([ [1, "uno"], [2, "dos"], ]); // Merge maps with an array. The last repeated key wins. const merged = new Map([...first, ...second, [1, "eins"]]); console.log(merged.get(1)); // eins console.log(merged.get(2)); // dos console.log(merged.get(3)); // three

Description

The

map()

method is an iterative method. It calls a provided

callbackFn

function once for each element in an array and constructs a new array from the results. Read the iterative methods section for more information about how these methods work in general.


callbackFn

is invoked only for array indexes which have assigned values. It is not invoked for empty slots in sparse arrays.

The

map()

method is generic. It only expects the

this

value to have a

length

property and integer-keyed properties.

Since

map

builds a new array, calling it without using the returned array is an anti-pattern; use

forEach

or

for...of

instead.

Real-Time GPS User Tracking Geolocation API JavaScript Programming
Real-Time GPS User Tracking Geolocation API JavaScript Programming

Javascript


let map1 =


new


Map([


[1, 2],


[2, 3],


[4, 5]


]);


console.log(


"Map1"


);


console.log(map1);


let map2 =


new


Map([


"firstname"


"sumit"


],


"lastname"


"ghosh"


],


"website"


"geeksforgeeks"


]);


console.log(


"Map2"


);


console.log(map2);

Output

Map1
Map(3) { 1 => 2, 2 => 3, 4 => 5 }
Map2
Map(3) {
'firstname' => 'sumit',
'lastname' => 'ghosh',
'website' => 'geeksforgeeks'
}

Example 2: This example adds elements to the map using set() method.

Supported Browsers:

  • Chrome
  • Edge
  • Firefox
  • Opera
  • Safari
  • Internet Explorer

We have a complete list of Javascript Map methods, to check them please go through the Javascript Map Reference article.

Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!

Looking for a place to share your ideas, learn, and connect? Our Community portal is just the spot! Come join us and see what all the buzz is about!

Last Updated :
16 Jan, 2024

Like Article

Save Article

Share your thoughts in the comments

Please Login to comment...

Sometimes you may need to take an array and apply some procedure to its elements so that you get a new array with modified elements.

Instead of manually iterating over the array using a loop, you can simply use the built-in

Array.map()

method.

Here's an Interactive Scrim of How to Use the JS .map() Function

The

Array.map()

method allows you to iterate over an array and modify its elements using a callback function. The callback function will then be executed on each of the array's elements.

For example, suppose you have the following array element:


let arr = [3, 4, 5, 6];

Now imagine you are required to multiply each of the array's elements by . You might consider using a

for

loop as follows:


let arr = [3, 4, 5, 6]; for (let i = 0; i < arr.length; i++){ arr[i] = arr[i] * 3; } console.log(arr); // [9, 12, 15, 18]

But you can actually use the

Array.map()

method to achieve the same result. Here's an example:


let arr = [3, 4, 5, 6]; let modifiedArr = arr.map(function(element){ return element *3; }); console.log(modifiedArr); // [9, 12, 15, 18]

The

Array.map()

method is commonly used to apply some changes to the elements, whether multiplying by a specific number as in the code above, or doing any other operations that you might require for your application.

Logging in JavaScript Best Practices
Logging in JavaScript Best Practices

Javascript


let map1 =


new


Map();


map1.set(


"first name"


"sumit"


);


map1.set(


"last name"


"ghosh"


);


map1.set(


"website"


"geeksforgeeks"


.set(


"friend 1"


"gourav"


.set(


"friend 2"


"sourav"


);


console.log(map1);


console.log(


"map1 has website ? "


map1.has(


"website"


));


console.log(


"map1 has friend 3 ? "


map1.has(


"friend 3"


));


console.log(


"get value for key website "


map1.get(


"website"


));


console.log(


"get value for key friend 3 "


map1.get(


"friend 3"


));


console.log(


"delete element with key website "


+ map1.


delete


"website"


));


console.log(


"map1 has website ? "


map1.has(


"website"


));


console.log(


"delete element with key website "


map1.


delete


"friend 3"


));


map1.clear();


console.log(map1);

Output

Map(5) {
'first name' => 'sumit',
'last name' => 'ghosh',
'website' => 'geeksforgeeks',
'friend 1' => 'gourav',
'friend 2' => 'sourav'
}
map1 has website ? true
map1 has friend 3 ? false
get...

Instance properties

These properties are defined on

Map.prototype

and shared by all

Map

instances.


Map.prototype.constructor

The constructor function that created the instance object. For


Map

instances, the initial value is the

Map

constructor.


Map.prototype.size

Returns the number of key/value pairs in the


Map

object.


Map.prototype[@@toStringTag]

The initial value of the


@@toStringTag

property is the string

"Map"

. This property is used in

Object.prototype.toString()

.

JavaScript Map and Set Explained
JavaScript Map and Set Explained

Browser compatibility

BCD tables only load in the browser

JavaScript map is a collection of elements where each element is stored as a Key, value pair. Map objects can hold both objects and primitive values as either key or value. When we iterate over the map object returns the key, and value pair in the same order as inserted. Map() constructor is used to create Map in JavaScript.

JavaScript Map has a property that represents the size of the map.

Example:

Input:let map1 = new Map([ [1 , 10], [2 , 20] , [3, 30],[4, 40] ]);console.log("Map1: ");console.log(map1);Output:// Map1: // Map(4) { 1 => 10, 2 => 20, 3 => 30, 4 => 40 }

Short-circuit Logging

    {nums.map((num) => console.log(num) || (

  • {num}
  • ))}

); }

Huzzah! 😃

Yo! I post byte-sized tips like these often. Follow me if you crave more! 🍿

I’m on Twitter, TikTok and I have a new debugging course dropping soon!

Reliable console.log output for JavaScript ES6 Map and Set

JavaScript Console Object Hidden Features - Going Beyond console.log to Learn New Features
JavaScript Console Object Hidden Features – Going Beyond console.log to Learn New Features

new Map()

In this we use

new Map()

constructor,

Example: In this example, a Map named

prices

is created to associate product names with their respective prices, allowing for efficient retrieval and management of price information.

// Creating a Map for product pricesconst prices = new Map([ [“Laptop”, 1000], [“Smartphone”, 800], [“Tablet”, 400] ]);

Console.log for ….

All examples have been run through Node.js. The same holds true if running through a browser i.e. with React or Angular.

Array

Example

const array = [‘sun’, ‘sea’, ‘surf’]; console.log(array); console.log(`array ${array}`); console.log(`array ${JSON.stringify(array)}`);

Output

[ ‘sun’, ‘sea’, ‘surf’ ] array sun,sea,surf array [“sun”,”sea”,”surf”]

The array plays most nicely with console.log. It displays it’s contents in all circumstances

Object

Example

const object = { sun: 1, sea: 2, surf: 3 }; console.log(object); console.log(`array ${object}`); console.log(`array ${JSON.stringify(object)}`);

Output

{ sun: 1, sea: 2, surf: 3 } object [object Object] object {“sun”:1,”sea”:2,”surf”:3}

Objects will only display correctly in a template literal if the JSON is stringified first. This is why I habitually use JSON.stringify when logging to the console.

ES6 Set

Example

const set = new Set([‘sun’, ‘sea’, ‘surf’]); console.log(set); console.log(`set ${set}`); console.log(`set ${JSON.stringify(set)}`);

Output

Set(3) { ‘sun’, ‘sea’, ‘surf’ } set [object Set] set {}

As with arrays and objects, logging the object directly works nicely but wrapping in a template literal hides the content i.e. when it is coerced to a string. The trick of JSON.stringifying the set doesn’t help now.

ES6 Map

Example

const map = new Map([[1, ‘sun’], [2, ‘sea’], [3, ‘surf’]]); console.log(map); console.log(`map ${map}`); console.log(`map ${JSON.stringify(map)}`);

Output

Map(3) { 1 => ‘sun’, 2 => ‘sea’, 3 => ‘surf’ } map [object Map] map {}

As with the Set, Map only logs directly, not when combined in a template literal

Overall

  • Logging directly always works
  • Arrays can be logged in a template literal
  • Objects can be logged in a template literal if the JSON is stringified first
  • Sets and Maps don’t log with template literals – they appear empty
JavaScript for Beginners — Console Logging
JavaScript for Beginners — Console Logging

Map.set():

You can add elements to a Map with the

set()

method.

Example: In this example, the

Map.set()

method is employed to add product prices to the Map named

prices

.

// Creating a Map for product prices const prices = new Map(); // Using Map.set() to add product prices prices.set(‘Laptop’, 1000); prices.set(‘Smartphone’, 800); // The Map now contains { ‘Laptop’ => 1000, ‘Smartphone’ => 800 }

Example 1: In this example, we will create a basic map object

Supported Browsers:

  • Chrome
  • Edge
  • Firefox
  • Opera
  • Safari
  • Internet Explorer

We have a complete list of Javascript Map methods, to check them please go through the Javascript Map Reference article.

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

Looking for a place to share your ideas, learn, and connect? Our Community portal is just the spot! Come join us and see what all the buzz is about!

Last Updated :
16 Jan, 2024

Like Article

Save Article

Share your thoughts in the comments

Please Login to comment…

JavaScript map is a collection of elements where each element is stored as a Key, value pair. Map objects can hold both objects and primitive values as either key or value. When we iterate over the map object returns the key, and value pair in the same order as inserted. Map() constructor is used to create Map in JavaScript.

JavaScript Map has a property that represents the size of the map.

Example:

Input:let map1 = new Map([ [1 , 10], [2 , 20] , [3, 30],[4, 40] ]);console.log(“Map1: “);console.log(map1);Output:// Map1: // Map(4) { 1 => 10, 2 => 20, 3 => 30, 4 => 40 }

How To View Javascript Output (Console.log) In Visual Studio Code
How To View Javascript Output (Console.log) In Visual Studio Code

How to use map() over an array of objects

For example, you may have an array of objects that stores

firstName

and

lastName

values of your friends as follows:


let users = [ {firstName : "Susan", lastName: "Steward"}, {firstName : "Daniel", lastName: "Longbottom"}, {firstName : "Jacob", lastName: "Black"} ];

You can use the

map()

method to iterate over the array and join the values of

firstName

and

lastName

as follows:


let users = [ {firstName : "Susan", lastName: "Steward"}, {firstName : "Daniel", lastName: "Longbottom"}, {firstName : "Jacob", lastName: "Black"} ]; let userFullnames = users.map(function(element){ return `${element.firstName} ${element.lastName}`; }) console.log(userFullnames); // ["Susan Steward", "Daniel Longbottom", "Jacob Black"]

The

map()

method passes more than just an element. Let’s see all arguments passed by

map()

to the callback function.

Here’s an interactive scrim about using map() to iterate over an array of objects:

Useful Links

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Maphttps://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SetMap and Set official documentation fromt the ES6 standard.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringifyJSON.stringify documentation

https://codebuckets.com/2018/06/17/extending-typescript-to-serialise-map-objects-to-json/I’ve an additional post about extending the ES6 Map Typescript definition to include a

toJSON

which also solves this issue of ES6 types not displaying their content in the console. Embarrasingly, I forgot that I’d written this post a few years ago on the same topic. I think this latest post adds some additional context by comparing the functionality across several different objects, so I’ll leave both in.

Map.prototype.values()

The

values()

method of

Map

instances returns a new map iterator object that contains the values for each element in this map in insertion order.

console.log() - JavaScript Basics
console.log() – JavaScript Basics

Keywords searched by users: js map console log

Easy Console.Log() Inside One Liner Functions - Dev Community
Easy Console.Log() Inside One Liner Functions – Dev Community
Hey! I'M Having A Issue Where The Console.Log() Statement Executes Before  The .Map() Function. So It Logs Out A Empty Array. I Tested By Putting The  Log Inside The Map, It Prints
Hey! I’M Having A Issue Where The Console.Log() Statement Executes Before The .Map() Function. So It Logs Out A Empty Array. I Tested By Putting The Log Inside The Map, It Prints
How To Convert Map Values To An Array In Javascript
How To Convert Map Values To An Array In Javascript
Console.Log In React - Programming - Dạy Nhau Học
Console.Log In React – Programming – Dạy Nhau Học
Map In Javascript - Youtube
Map In Javascript – Youtube

See more here: kientrucannam.vn

Trả lời

Email của bạn sẽ không được hiển thị công khai. Các trường bắt buộc được đánh dấu *