← Back to Node.js Course | Chapter 3: npm & Packages | Lesson 5 of 7

Semantic versioning

Version numbers like 2.4.1 follow a pattern that tells you how risky an upgrade is.

In this page:

  1. Semantic versioning
Syntax
javascript
"package_name": "MAJOR.MINOR.PATCH"
"package_name": "^MAJOR.MINOR.PATCH"
"package_name": "~MAJOR.MINOR.PATCH"

Semantic versioning

Semver uses MAJOR.MINOR.PATCH. Patch fixes bugs, minor adds backward-compatible features, and major may break things. In package.json, a caret allows minor and patch updates, a tilde allows only patch updates, and an exact version pins it.

Note: ^1.2.3 allows anything from 1.2.3 up to (but not including) 2.0.0.

Example: Semantic versioning

javascript
function allowsCaret(range, version) {
  const [rM, rm, rp] = range.replace("^", "").split(".").map(Number);
  const [vM, vm, vp] = version.split(".").map(Number);
  return vM === rM && (vm > rm || (vm === rm && vp >= rp));
}
console.log("^1.2.3 allows 1.9.0:", allowsCaret("^1.2.3", "1.9.0"));
console.log("^1.2.3 allows 2.0.0:", allowsCaret("^1.2.3", "2.0.0"));
console.log("^1.2.3 allows 1.2.2:", allowsCaret("^1.2.3", "1.2.2"));

// Output:
// ^1.2.3 allows 1.9.0: true
// ^1.2.3 allows 2.0.0: false
// ^1.2.3 allows 1.2.2: false

⚠️ Run this in your own terminal or Node.js environment.

Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Assuming any upgrade is safe
  2. Confusing caret and tilde
  3. Not committing the lock file
Chapter Summary
  • MAJOR.MINOR.PATCH
  • Caret allows minor and patch
  • Tilde allows patch only
  • Lock files pin exact versions
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.