JavaScript • Getting Started and Tooling

npm Basics — Use npm to initialize a project and install packages (conceptual workflow)

Learn how npm helps you organize JavaScript projects and reuse code written by other developers.

JavaScript emblem with code brackets, braces, and a code file.
Inside this lesson 10 sections 5 questions 5 figures

SECTION 1

Historical Context & Motivation

Before tools like npm existed, JavaScript developers had a frustrating problem: sharing and reusing code was messy. If you wanted to use a helpful library someone else wrote — say, a date-formatting tool or a color-picker widget — you had to manually download files, drop them into your project folder, and hope everything worked together. There was no standard way to track which version of a library you were using or to update it when bugs were fixed.

Other programming languages had already solved this problem. Python had pip, Ruby had gem, and Java had Maven. JavaScript needed its own package manager — a tool that could automatically download, install, and manage reusable chunks of code called packages. That's exactly what npm was built to do.

2009 • Node.js Is Released

Ryan Dahl creates Node.js, allowing JavaScript to run outside the browser on servers and local machines. This opened the door for JavaScript tooling.

2010 • npm v1.0 Launches

Isaac Z. Schlueter releases npm (Node Package Manager) as a command-line tool bundled with Node.js. Developers can now publish and install packages with a single command.

2014 • npm Registry Hits 100,000 Packages

The npm registry — the online database where packages are stored — crosses 100,000 available packages, making it one of the largest open-source ecosystems in the world.

2020 • npm Becomes Part of GitHub

GitHub (owned by Microsoft) acquires npm, ensuring long-term support. The registry now hosts over 1.3 million packages and serves billions of downloads per week.

2024 • Over 2 Million Packages

The npm registry surpasses 2 million packages. Nearly every modern JavaScript project — from small school assignments to massive apps like Instagram and Netflix — relies on npm.

So the central question npm answers is simple: How do you efficiently organize a JavaScript project and bring in code that others have already written and tested? Understanding this workflow is one of the first steps to building real-world applications.

SECTION 2

Core Principles & Definitions

Before diving into commands, let's nail down the key ideas. npm revolves around a few core concepts that work together to keep your project organized and reproducible.

1

Package

A package is a reusable bundle of JavaScript code — like a pre-built Lego set you can snap into your project. Examples include libraries for making HTTP requests, formatting dates, or running tests.
2

Registry

The npm registry is a massive online database (at npmjs.com) where developers publish their packages. Think of it as an app store, but for code libraries instead of phone apps.
3

package.json

The package.json file is your project's ID card. It records the project name, version, description, and — most importantly — a list of every package your project depends on.
4

node_modules

The node_modules folder is where npm actually downloads and stores all the package files on your computer. You never edit files in here — npm manages it for you.
5

Dependencies

A dependency is any package your project needs to run. Dependencies are listed in package.json so anyone who downloads your project can install the exact same packages.
✦

KEY TAKEAWAY

Think of npm like a recipe system. Your package.json is the recipe card listing every ingredient (package) you need. The npm registry is the grocery store where you get those ingredients. And the node_modules folder is your kitchen pantry where everything is stored and ready to use. When you share a project with a friend, you just share the recipe card — they can get their own groceries from the same store by running npm install.

SECTION 3

Visual Explanation — The npm Workflow

The diagram below shows the complete conceptual workflow of using npm in a project, from initialization to installing packages and how the pieces connect.

npm Conceptual WorkflowSTEP 1npm initInitialize projectCREATEDpackage.jsonProject ID cardSTEP 2npm install <package>Install a dependencynpm REGISTRY (npmjs.com)2+ million packages availablelodashexpresschalkdownloadsnode_modules/Downloaded package fileschalk/...package.json (updated){"name": "my-project","dependencies": { "chalk": "^5.3.0" }}auto-updates
The workflow flows from left to right: npm init creates package.json, then npm install fetches packages from the registry into node_modules and automatically records them as dependencies.

Notice that the workflow has two main steps. First, you initialize your project with npm init, which creates the package.json file. Second, you install packages using npm install <package-name>. When you install a package, npm does three things simultaneously: it downloads the package code into node_modules, it adds the package name and version to your package.json, and it creates or updates a package-lock.json file that records the exact versions of everything installed.

SECTION 4

How It Works — The Command-Line Workflow

npm is a command-line tool, which means you interact with it by typing commands into a terminal (also called a console or shell). You don't click buttons — you type instructions. This might feel unfamiliar at first, but it's how professional developers work every day. Let's walk through the two essential commands.

Step A: Initializing a Project with npm init

When you start a new JavaScript project, you navigate to your project folder in the terminal and type npm init. npm will ask you a series of questions — your project name, version number, description, and so on. You can press Enter to accept the defaults for each question. Once you finish, npm creates a package.json file in your project folder.

💡

SHORTCUT

If you want to skip all the questions and accept every default, use npm init -y. The -y flag means "yes to everything." This creates a package.json instantly with sensible defaults.

Step B: Installing Packages with npm install

Once package.json exists, you can install any package from the registry. For example, npm install chalk downloads the popular chalk library (used to add colors to terminal output). Behind the scenes, npm contacts the registry at npmjs.com, downloads chalk and any packages that chalk itself depends on (called transitive dependencies), stores everything in node_modules, and adds an entry to the "dependencies" section of your package.json.

The Lock File — package-lock.json

Every time you install or update packages, npm also creates or updates a file called package-lock.json. While package.json says "I need chalk version 5 or higher," the lock file says "I am using chalk version 5.3.0, downloaded from this exact URL, with this exact checksum." This guarantees that every developer on your team — or your teacher grading your project — gets identical versions of every package.

SECTION 5

Anatomy of package.json

The package.json file is written in JSON (JavaScript Object Notation), a format you've likely seen before. It uses curly braces and key-value pairs to store structured data. Let's look at what each field means and which ones matter most when you're starting out.

Anatomy of package.json{"name": "my-cool-app","version": "1.0.0","description": "A school project","main": "index.js","scripts": {"start": "node index.js","test": "echo \"No tests\""},"dependencies": {"chalk": "^5.3.0","lodash": "^4.17.21"}}METADATAName, version, description & entrySCRIPTSCustom terminal shortcutsDEPENDENCIES ⭐The most important section!Lists packages your project needs.VERSION FORMAT^5.3.0 → major.minor.patch
A typical package.json with annotations. The dependencies section (shown in green) is automatically managed by npm when you install packages. The caret (^) before a version number means "this version or any compatible newer version."
FieldPurposeRequired?
nameA unique name for your project (lowercase, no spaces)Yes
versionCurrent version number using semantic versioning (e.g., 1.0.0)Yes
descriptionA short summary of what the project doesNo
mainThe entry point file — usually index.jsNo
scriptsCustom commands you can run with npm run <script-name>No
dependenciesPackages your project needs in production (added automatically by npm install)Auto-created
devDependenciesPackages needed only during development (e.g., testing tools)Auto-created

Key fields in package.json

SECTION 6

Worked Example — Building a Color Greeter

Let's walk through the complete workflow of creating a small project that prints a colorful greeting in the terminal. We'll use the chalk package to add color.

Creating a Color Greeter Project

  1. 1

    Step 1 — Create a Project Folder

    Open your terminal and create a new folder for your project, then navigate into it. You'd type: mkdir color-greeter followed by cd color-greeter. The mkdir command makes a directory (folder), and cd changes into it.
    You now have an empty folder called color-greeter
  2. 2

    Step 2 — Initialize the Project

    Run npm init -y to generate a package.json with all default values. npm will display the contents of the new file in the terminal. You should see fields like "name": "color-greeter" and "version": "1.0.0".
    package.json created ✓
  3. 3

    Step 3 — Install the chalk Package

    Run npm install chalk. npm will contact the registry, download chalk (and its dependencies if any), create the node_modules folder, and add chalk to the "dependencies" section of your package.json. You'll also see a new package-lock.json file appear.
    chalk installed ✓ — node_modules and package-lock.json created
  4. 4

    Step 4 — Verify Your Project Structure

    Your project folder should now contain three items: package.json, package-lock.json, and the node_modules folder. If you open package.json, you'll see a new "dependencies" section that wasn't there before, listing chalk and its version.
    Project structure verified ✓
  5. 5

    Step 5 — Use the Package in Your Code

    Create a file called index.js and write code that imports chalk and prints a colored message. Conceptually, you'd write something like: import chalk, then use chalk.blue('Hello, World!') to print blue text. Running node index.js in the terminal will show your colorful greeting.
    "Hello, World!" displayed in blue ✓
⚠

IMPORTANT

You should never share the node_modules folder when sending your project to someone else (or pushing to GitHub). It can contain thousands of files and is often huge. Instead, share your package.json and package-lock.json. The other person just runs npm install (with no package name), and npm will read package.json and re-download everything.

SECTION 7

npm vs. Other Approaches

npm isn't the only package manager out there, and it's not the only way to add external code to your projects. Let's compare a few approaches so you can understand where npm fits in the bigger picture.

ApproachStrengthsLimitations
npmComes bundled with Node.js; largest package registry; standard for JavaScript projects; automatic dependency trackingnode_modules folder can become large; can be slower than alternatives for very large projects
YarnFaster installations in some cases; uses the same npm registry; created by Facebook for reliabilitySeparate installation required; adds complexity; less commonly used in tutorials
Manual downloadNo tools needed; you understand exactly what files you're addingNo version tracking; no automatic updates; easy to lose track of what you've added
CDN (script tag)Quick for browser-only projects; no terminal needed; just add a URL in your HTMLOnly works in browsers; depends on internet connection; no local development workflow

Comparing ways to add external code to JavaScript projects

✦

KEY TAKEAWAY

npm is the default standard for JavaScript package management. While alternatives like Yarn exist, they use the same registry and solve the same problem. Learning npm first gives you a foundation that transfers directly to any alternative tool. Think of it like learning to drive an automatic car first — once you understand the basics, switching to a manual is much easier.

SECTION 8

Connection to Advanced Tooling

The npm workflow you've learned is the foundation for virtually every advanced JavaScript tool. Once you're comfortable initializing projects and installing packages, you'll encounter more powerful tools that build on these same concepts.

What You Know NowWhat Comes Next
npm init to start a projectFrameworks like React and Next.js use custom init commands (e.g., npx create-react-app) that set up entire project structures automatically
npm install to add packagesTools like webpack, Vite, and Babel are installed via npm and transform your code for production (bundling, minifying, transpiling)
The scripts section in package.jsonCI/CD pipelines (automated testing and deployment) rely on npm scripts to build, test, and deploy code in the cloud
Understanding dependenciesMonorepo tools (npm workspaces, Lerna) manage multiple related projects that share dependencies

From npm basics to advanced JavaScript tooling

The key insight is that every modern JavaScript project — whether it's a simple class assignment or a massive web application used by millions — starts with the same two steps: npm init and npm install. The tools grow more sophisticated, but the core workflow remains the same. Mastering these basics now means you're building on a foundation that will serve you throughout your programming career.

SECTION 9

Practice Problems

Question 1: CONCEPTUAL

In your own words, explain the purpose of the package.json file. Why is it important to include it when sharing your project with someone else?
Show answer
The package.json file acts as a manifest or "ID card" for your project. It records metadata (name, version, description) and, most importantly, lists all the packages your project depends on. When you share your project without the node_modules folder, the recipient can run npm install to automatically download every dependency listed in package.json. Without this file, the other person would have no idea which packages your code needs, and the project would likely fail to run.

Question 2: BASIC CALCULATION

You run npm init -y in a folder called quiz-app. What will the "name" and "version" fields in the generated package.json be set to? Will there be a "dependencies" section?
Show answer
The "name" field will be set to "quiz-app" (npm uses the folder name as the default project name). The "version" will default to "1.0.0". There will NOT be a dependencies section yet, because you haven't installed any packages. The dependencies section only appears after you run npm install <package-name> for the first time.

Question 3: INTERMEDIATE

You clone a friend's project from GitHub. The repo contains package.json and package-lock.json but no node_modules folder. When you try to run the code, it throws errors about missing modules. What single command do you need to run, and what does it do?
Show answer
You need to run npm install (with no package name after it). This command reads the package.json file (and the package-lock.json for exact versions), then downloads every listed dependency from the npm registry into a freshly created node_modules folder. This is standard practice — developers intentionally exclude node_modules from version control (using a .gitignore file) because it's large and can be easily regenerated. After running this command, the project should work correctly.

Question 4: APPLIED

You're building a weather app for a class project. You need a library to make HTTP requests to a weather API (like axios) and a library to display the data nicely in the terminal (like cli-table3). Describe the exact sequence of terminal commands you would run to set up this project from scratch.
Show answer
First, create and enter a project folder: mkdir weather-app then cd weather-app. Second, initialize the project: npm init -y. Third, install both packages: npm install axios cli-table3 (you can install multiple packages in a single command by separating their names with spaces). After this, your package.json will list both axios and cli-table3 under dependencies, node_modules will contain their code, and you're ready to create your index.js file and start coding.

Question 5: CRITICAL THINKING

Imagine npm didn't exist and there was no package manager for JavaScript. How would a team of five students working on a group project manage external libraries? What problems might arise, and how does npm solve each one?
Show answer
Without npm, each student would need to manually find, download, and place library files into the correct folders. Several problems would arise. First, version inconsistency: different team members might download different versions of the same library, causing bugs that only appear on some computers. npm solves this with package-lock.json, which locks exact versions. Second, missing dependencies: a library might rely on other libraries (transitive dependencies), and students would have to track and download each one manually. npm handles this automatically. Third, project setup friction: every new team member would need detailed instructions on which files to download and where to put them. npm reduces this to a single command: npm install. Fourth, updating libraries: without npm, you'd have to re-download files manually and hope nothing breaks. npm lets you update packages with a single command and rollback if needed. In short, npm automates dependency management, ensuring consistency, reproducibility, and efficiency across a team.

SUMMARY

Summary

Summary

npm (Node Package Manager) is the standard tool for managing JavaScript project dependencies. The workflow begins with npm init, which creates a package.json file — your project's manifest that records its name, version, and list of dependencies. You add packages using npm install <package-name>, which downloads code from the npm registry (a database of over 2 million packages) into the node_modules folder and automatically updates package.json.

The package-lock.json file ensures that everyone working on the project uses the exact same versions of every package. When sharing your project, you include package.json and package-lock.json but exclude node_modules — other developers simply run npm install to regenerate everything. This two-step workflow — initialize, then install — is the foundation of every modern JavaScript project, from small school assignments to large-scale applications.

Varsity Tutors • JavaScript • npm Basics — Use npm to initialize a project and install packages (conceptual workflow)