Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 2

Choosing JavaScript Primitive Values and Declarations

Recommended resources

Hello! Last time, you saved app.js, ran it with node app.js, and used console.log(...) to see the result. That program printed a fixed message. This time, you’ll give meaningful names to values so the program can remember and display information. You’ll choose among JavaScript’s primitive values and decide when a name should be declared with const or let. Allow about 40 minutes, including time to edit and rerun your file.


Give values names

A variable lets you refer to a value later in a program. The image below treats variables as boxes: the contents could be text, a true-or-false value, or a number. It is a useful picture for getting started, though it is not a literal diagram of computer memory.

Three boxes illustrate different values a variable can hold: the string “Bob”, the boolean `true`, and the number `35`.

The following short video introduces declaration and the values you’ll use most often. It demonstrates JavaScript in a browser; you can type the same declarations into app.js and run them with Node instead.

JavaScript Variables and Datatypes in 6 Minutes

Watch “JavaScript Variables and Datatypes in 6 Minutes” by Learndev for a quick demonstration of named values, reassignment, and the main everyday data types.

Watch variables and declarations, focusing on the difference between giving a variable its first value and assigning it another value later. Then watch kinds of values, especially the distinction between quoted text, unquoted booleans, undefined, and null. The video briefly uses arithmetic and string joining; you’ll study expressions in the next lesson.

Consider a small task-tracking program. A title is text, so it is a string and needs quotes. A remaining-task count is a number, without quotes. Whether a task is complete is a boolean: true or false, also without quotes.

const taskTitle = "Review notes";
let tasksRemaining = 3;
const isComplete = false;

console.log(taskTitle);
console.log(tasksRemaining);
console.log(isComplete);

Put this in app.js, save, and run node app.js. You should see Review notes, 3, and false on separate lines. In console.log(taskTitle), the name has no quotes: JavaScript retrieves its value. In console.log("taskTitle"), the quotes would instead make JavaScript print the literal text taskTitle.

Choose a value by what it means, not just by the characters it displays. "35" is text, while 35 is a number. A count you intend to calculate with should normally be a number. An identifier such as "0042" should normally be a string: its leading zeros are part of the identifier, not a quantity. Likewise, "false" is text; false is a boolean.

JavaScript has seven primitive types in total. Read the compact list in MDN’s guide to see where the everyday values fit. You do not need to memorize the less common types yet.

Grammar and types - JavaScript - MDN Web Docs - Mozilla

Read MDN Web Docs’ list of JavaScript data types to get the complete picture of what counts as a primitive.

In “Data structures and types,” under “Data types,” read the type list and the paragraph immediately after it. Notice that seven entries are primitives, while Object is the other data-type category; arrays and objects will get their own lessons.

For now, your practical choices are:

  • String: text, including codes and identifiers such as "0042".
  • Number: ordinary counts and decimal quantities such as 3 or 12.5.
  • Boolean: a yes-or-no state such as false.
  • null: an intentional “no value” choice, such as no task currently selected.
  • undefined: often the value of a variable declared with let before you give it a value.

The other two primitives serve narrower purposes. BigInt can represent integers too large for ordinary numbers to hold exactly, and Symbol can provide a unique identifier. You should recognize their names, but an ordinary task count does not need BigInt, and an ordinary task ID does not need Symbol.



Decide whether to use const or let

In const taskTitle = "Review notes";, const taskTitle declares the name and = "Review notes" initializes it with a value. JavaScript also has an older declaration keyword, var; for new code in this course, use const and let.

The decision is about reassignment: will this name need to refer to a different value later? If not, use const. If yes, use let.

const taskId = "0042";
let tasksRemaining = 3;

tasksRemaining = 2; // Reassign the existing variable; don't write "let" again.

Here, the task ID remains the same throughout this example, while the remaining count changes. const must receive a value when declared, and trying to reassign it causes an error. The rule to remember is use const when you can; use let when you need to reassign.

Read MDN’s explanation to check exactly what const protects. In particular, it protects the assignment to the name; later, when you study objects, you’ll see why that is not quite the same as making every kind of value unchangeable.

Storing the information you need — Variables - MDN Web Docs

Read the “Constants in JavaScript” and “When to use const and when to use let” sections from MDN Web Docs. They clarify the rule behind the examples above.

In “Constants in JavaScript,” read the declaration rules, including the examples where const fails. You can leave the following bird-object example for the objects lesson. Then, in “When to use const and when to use let,” read from the opening question about why you would prefer const through the practical rule.

One nuance makes the rule easier to apply: a value need not be universally permanent to justify const. It simply must not be reassigned by this part of your program. Conversely, if you start with let tasksRemaining = 3 and later assign 2, writing const would prevent the program from running as intended.

Variable names should explain what they hold. Names such as tasksRemaining and isComplete are more useful than x and flag. For ordinary multiword names, use camelCase: begin with a lowercase word and capitalize later words. Names cannot contain spaces or begin with a digit, and JavaScript treats taskId and taskID as different names.



Build a tiny task-status program

Replace the contents of app.js with this complete program:

const taskId = "0042";
const taskTitle = "Review notes";
let tasksRemaining = 3;
const isComplete = false;
let selectedTaskId = null;
let lastSyncMessage;

console.log("Task ID:", taskId);
console.log("Title:", taskTitle);
console.log("Remaining:", tasksRemaining);
console.log("Complete:", isComplete);
console.log("Selected task:", selectedTaskId);
console.log("Last sync:", lastSyncMessage);

tasksRemaining = 2;
selectedTaskId = taskId;
lastSyncMessage = "Sync complete";

console.log("Updated remaining:", tasksRemaining);
console.log("Updated selection:", selectedTaskId);
console.log("Updated sync:", lastSyncMessage);

Save and run node app.js. The first six lines show the initial values, including null for the deliberately empty selection and undefined for lastSyncMessage, which was declared without an initial value. The last three lines should show 2, 0042, and Sync complete after reassignment.

Notice why the declarations differ. taskId, taskTitle, and isComplete are initialized and never reassigned, so they use const. The other three names receive new values later, so they use let. In particular, let lastSyncMessage; creates a name whose initial value is undefined; const lastSyncMessage; would be an error because const requires an initial value.

The program also illustrates two different kinds of absence. selectedTaskId = null explicitly says no task is selected right now. lastSyncMessage initially has no assigned message, so JavaScript gives it undefined. These are values, not variable names in quotes.

As a final check on value types, add these lines at the end of the file and rerun it:

console.log(typeof taskId);        // string
console.log(typeof tasksRemaining); // number
console.log(typeof isComplete);    // boolean
console.log(typeof lastSyncMessage); // string, after its assignment above

typeof lets you inspect the type of the current value. lastSyncMessage began as undefined, but by the time these lines run it holds "Sync complete", a string. This ability for a JavaScript variable to receive values of different types is one reason the later TypeScript lessons will focus on describing intended types clearly.



What to carry forward

You can now name and reuse values, choose strings for text and identifiers, numbers for quantities, booleans for yes-or-no states, and distinguish intentional null from an as-yet-unassigned undefined. Use const unless you need to reassign the name; use let when you do.

Next, you’ll make these values interact by constructing arithmetic, comparison, logical, and nullish expressions. That will let a program calculate a new count or answer a question rather than only display stored values.