Array.map vs Array.forEach

forEach can be used just like a traditional ‘for loop’ that iterates each of the array element once.

If you are working with JavaScript, then you must have come across these two similar looking array methods: Array.prototype.map() and Array.prototype.forEach().

Most of the developers thinks that Array.map function and forEach for an Array is the same, but it is not. Lets see some examples:
1. Array.prototype.forEach
forEach can be used just like a traditional ‘for loop’ that iterates each of the array element once.

let arrayElements = ['A','C','D'];  
arrayElements.forEach((ele)=>{  
  console.log(ele);  
 })  

The above example will generate the following –
A
C
D

2. Array.prototype.map
The map() function creates a new Array with the results of calling a function for every element of the calling array.

let arrayElements = [1, 4, 6];  
var result = arrayElements .map((ele)=>{  
  return (ele * 2);  
});  
console.log(result);  

The output of the code is:
[ 2, 8, 12 ]
In the above example we are iterating through each element of Array and multiplying it by 2.

How to stop an event propagation in javascript?

You can stop the event propagation by doing this – 

function stopEventPropagation(event) {

if (event.stopPropagation) {
event.stopPropagation();   // W3C model
} else {
event.cancelBubble = true; // IE model
}

}

How to get XML string in javascript?

Here is the function:

function getXmlString(xmlDoc) {
try {
return ((new XMLSerializer()).serializeToString(xmlDoc));
}
catch (e) {
try {
// Internet Explorer.
return (xmlDoc.xml);
}
catch (e) {
//Strange Browser ??
return (‘Xmlserializer not supported’);
}
}
}

How to apply xml to xslt in javascript?

Here is the function:

 

function transFormXml(xmlData, xsltData) {
try {
try {
return xmlData.transformNode(xsltData);
}
catch (e) {
var xsltProcessor = new XSLTProcessor();
xsltProcessor.importStylesheet(xsltData);
return getXmlString(xsltProcessor.transformToFragment(xmlData, document));
}
} catch (e)
{ alert(e); }

return null;
}

How to get time zone offset in javascript?

Here is the function:

 

function getTimeZoneOffset() {
var currentDate = new Date();
var date1 = new Date(currentDate.getFullYear(), 0, 1, 0, 0, 0, 0);
var temp = date1.toGMTString();
var date3 = new Date(temp.substring(0, temp.lastIndexOf(” “)));
var hoursDiffStdTime = ((date1 – date3) / (1000 * 60 * 60)) * 60;
return hoursDiffStdTime;
}

And if you want to get the offset with daylight saving then look at the below function:

 

function getTimeZoneOffsetDayLightSaving() {
var currentDate = new Date();
var date2 = new Date(currentDate.getFullYear(), 6, 1, 0, 0, 0, 0);
var temp = date2.toGMTString();
var date4 = new Date(temp.substring(0, temp.lastIndexOf(” “)));
var hoursDiffDaylightTime = ((date2 – date4) / (1000 * 60 * 60)) * 60;

return hoursDiffDaylightTime;
}