Map function in JavaScript

 Map function in JavaScript



  1. The map() method creates a new array with the results of calling a function for every array element.
  2. The map() method calls the provided function once for each element in an array, in order.
  3. map() does not execute the function for empty elements.
  4. map() does not change the original array.
1. Using map function in JavaScript

<!DOCTYPE html>
<html lang="en">
<head>
   <title>Map function</title>  
</head>
<body>
    <p id="item">hello world</p>
    <script>
        const oldarr = ['shreyasdh''shubham''ganesh''ravi'];
        console.log(oldarr[0]);

        const newarr = oldarr.map(function (cvaluei){
            return i + ":" + cvalue
        });
        console.log(newarr);
        console.log(oldarr);
    </script>
</body>
</html>

Output (in console)

shreyasdh
map.html:15 (4) ['0:shreyasdh', '1:shubham', '2:ganesh', '3:ravi']
map.html:16 (4) ['shreyasdh', 'shubham', 'ganesh', 'ravi']

2. Using Map function in React use fatarrow function

<!DOCTYPE html>
<html lang="en">
<head>
   <title>Map function</title>  
</head>
<body>
    <p id="item">hello world</p>
    <script>
        const studentData = [
            {id1name : "shreyash"degree"BBACA"},
            {id2name : "ruju"degree"BBA"},
            {id3name : "srk"degree"CA"},
            {id4name : "anil"degree"BA"},
            {id5name : "pappu"degree"AC"}

        ]

        console.log(studentData);
        console.log(studentData[0].name);
        console.log(studentData[1].name);

        const newdata = studentData.map((cvalue)=>{
            return `My name is ${cvalue.name}. my degree is ${cvalue.degree}`;
        });
        // document.write(newdata);
        console.log(newdata);

        document.getElementById('item').innerHTML = newdata;
    </script>
</body>
</html>

Output (in console)

(5) [{…}, {…}, {…}, {…}, {…}]
0: {id: 1, name: 'shreyash', degree: 'BBACA'}
1: {id: 2, name: 'ruju', degree: 'BBA'}
2: {id: 3, name: 'srk', degree: 'CA'}
3: {id: 4, name: 'anil', degree: 'BA'}
4: {id: 5, name: 'pappu', degree: 'AC'}
length: 5
[[Prototype]]: Array(0)

 shreyash
 ruju
 (5) ['My name is shreyash. my degree is BBACA', 
 'My name is ruju. my degree is BBA', 'My name is srk. my degree is CA', 'My name is anil. my degree is BA', 'My name is pappu. my degree is AC']
 0: "My name is shreyash. my degree is BBACA"
 1: "My name is ruju. my degree is BBA"
 2: "My name is srk. my degree is CA"
 3: "My name is anil. my degree is BA"
 4: "My name is pappu. my degree is AC"
 length: 5
 [[Prototype]]: Array(0)