// Immediately Invoked Function Expression (IIFE) to detect the browser and version
const browser = (function() {
// Get user agent string from navigator
const userAgent = navigator.userAgent;
// Regular expression to match browser name and version
const match = userAgent.match(/(chrome|firefox|safari|opera|edge|msie)\/(\d+(\.\d+)?)/i);
// Return the detected browser information or 'Unknown' if not matched
return match ? { name: match[1], version: match[2] } : 'Unknown';
})();
// Logging the detected browser information
console.log('Browser:', browser);
code
Detecting Browser and Version
This JavaScript code uses an Immediately Invoked Function Expression (IIFE) to detect the browser and its version based on the user agent string. The comments provide explanations for each part of the code.
Console.log
Regular Expression
Browser Detection
User Agent