Explain Codes LogoExplain Codes Logo

How can I compare software version number using JavaScript? (only numbers)

javascript
version-comparison
semver
npm-packages
Anton ShumikhinbyAnton Shumikhin·Feb 9, 2025
TLDR

Here's a quick, yet robust function that compares software versions. It relies on JavaScript's innate ability to split strings and compare numbers:

// Hey, I'm just a small function, but I pack a punch! 💪 function compareVersions(v1, v2) { const parts1 = v1.split('.').map(Number), parts2 = v2.split('.').map(Number); for (let i = 0; i < Math.max(parts1.length, parts2.length); i++) { const num1 = parts1[i] || 0, num2 = parts2[i] || 0; if (num1 != num2) return num1 > num2 ? 1 : -1; } return 0; } // Watch me tackling these examples like a pro athlete! compareVersions('1.0', '1.0.5'); // -1 (1.0 < 1.0.5, I guess 1.0 needs to hit the gym more!) compareVersions('1.1', '1.0'); // 1 (1.1 > 1.0, no surprise there) compareVersions('2.0', '2.0.0'); // 0 (2.0 == 2.0.0, they're basically twins)

This function is lightweight and dangerously efficient, handling the brunt of version comparison logic without breaking a sweat! It fearlessly tackles any array to reduced it to a digestible number.

<< add here any content>>

Breaking down Semantic Versioning (SemVer)

Semantic versioning or SemVer is the indispensable standard amongst software developers to designate version numbers. It follows an x.y.z format: x is the major release, y embodies the minor release, and z stands for the patch. This presupposes a uniform method for version pivoting and confers developers the lay of the land regarding software updating implications.

The semver library on npm offers a diversified toolbox for handling semantic versioning. Observe its might with methods like semver.compare, semver.satisfies, and semver.maxSatisfying to undertake comparison and execute validations in line with semantic versioning regulations.

Demystifying npm Packages

semver: Cracking down the complex

For those intricate version requirements or when a strict adherence to semantic versioning is paramount, the semver package is a go-to tool. It automates the intricate process of version comparison with its pre-set functions. Here's how the magic happens:

const semver = require('semver'); // Watch semver making these comparisons look easy: semver.gt('1.2.3', '1.2.0'); // true (1.2.3 has been hitting the gym lately) semver.lt('1.2.0', '1.2.3'); // true (1.2.0 has been skipping the leg day) semver.eq('2.0.0', '2.0.0'); // true (These versions are doppelgangers)

localeCompare: When simplicity meets adequacy

For rudimentary comparisons, JavaScript's localeCompare function belts numeric: true, enabling it to appropriately compare version numbers:

'1.10.0'.localeCompare('1.2.0', undefined, { numeric: true }); // 1 (1.10.0 laughed in the face of 1.2.0)

However, it falls short when dealing with pre-release numbers or versions with extraneous metadata.

References