What's the difference between a tilde (~) and a caret (^) in a npm package.json file?

Written on July 13, 2017
Updated on February 27, 2024

If you use npm to manage packages in your Node application, you’re probably familiar with the package.json file.

{
  "devDependencies": {
    "ember-cli": "~2.14.0"
  }
}

The syntax is in JSON format where the key is the name of the package and the value is the version of the package to be used.

npm uses the package.json file to specify the version of a package that your app depends on.

The version number is in semver syntax which designates each section with different meaning. semver is broken into three sections separated by a dot.

major.minor.patch

1.0.2

Major, minor and patch represent the different releases of a package.

npm uses the tilde (~) and caret (^) to designate which patch and minor versions to use respectively.

So if you see ~1.0.2 it means to install version 1.0.2 or the latest patch version such as 1.0.4. If you see ^1.0.2 it means to install version 1.0.2 or the latest minor or patch version such as 1.1.0.

But if in your npm package.json file you’re referencing a package that hasn’t reached version 1.0 yet, using the caret (^) symbol will only grab the patch version.

Use tilde (~) for stable dependencies

If you’re working with a stable dependency that you don’t want to break frequently, using the tilde (~) can be a good option. This will ensure you get the latest bug fixes and security patches without introducing potentially breaking changes.

Use caret (^) for dependencies that are actively being developed

If you’re working with a dependency that is actively being developed and may introduce new features or bug fixes, using caret (^) can be a good option. This will ensure you get the latest minor or patch versions, which may include new features or bug fixes, while still maintaining compatibility with your existing code.

Consider the potential impact of breaking changes

When deciding between the tilde (~) and caret (^), it’s important to consider the potential impact of breaking changes. Tilde (~) is more likely to introduce breaking changes than caret (^), as it allows for a wider range of patch versions.

Ultimately, the best choice between tilde (~) and caret (^) depends on your specific needs and risk tolerance. If you’re unsure, it’s always best to err on the side of caution and use caret (^).

Stay in touch

Thanks for reading this article. I'd love to stay in touch and share more tips on programming and side projects with you. Sign up and I'll send you my articles straight to your email, you'll also get a free copy of the light themed version of my Git cheat sheet.
Git cheat sheet preview image