Learning path · Level 4 · Tutorial 1

Work with JavaScript Values and Variables

Run JavaScript from a local HTML page and use named values and expressions to calculate and display results in the browser console.

  • Level: Beginner
  • Duration: 25 min
  • 8 steps
Start tutorial Back to the path
Work with JavaScript Values and Variables

What you will go through

  1. Run Your First Local Script Connect a local JavaScript file to HTML and verify a saved change through browser Console output. 3 min
  2. Read Statements, Expressions, and Comments Distinguish value-producing expressions, executable statements, and explanatory comments in a short JavaScript script. 2 min
  3. Name Values with const and let Declare readable names for notebook-order values, use const for fixed bindings, and use let when quantity needs reassignment. 4 min
  4. Recognize Everyday Primitive Values Recognize numbers, strings, booleans, null, and undefined in a notebook-order script. 3 min
  5. Inspect Values with typeof Inspect notebook-order values with typeof and recognize the historical null result. 3 min
  6. Calculate with Arithmetic Expressions Use arithmetic precedence, parentheses, and statement order to calculate notebook-order totals. 4 min
  7. Build Readable Strings Produce a readable Console summary with concatenation and template-literal interpolation. 4 min
  8. Apply and Review: An Order Summary Complete a local notebook-order script, verify its Console output, and review variables, primitive values, arithmetic, and interpolation. 4 min

What you will learn

  • Create a local JavaScript file, link it to HTML, and confirm its execution in the console.
  • Choose const or let according to whether a binding must be reassigned.
  • Identify common primitive values and inspect their types.
  • Predict and produce results from arithmetic expressions and string interpolation.

Before you start

  • How Browsers Display Web Pages
  • Create and Inspect a Local HTML Page
  • Link Local Pages with Relative Paths

Step 1 of 8

Run Your First Local Script

Connect a local JavaScript file to HTML and verify a saved change through browser Console output.

Connect the Files

From local files to Console output

JavaScript source for this tutorial belongs in a plain-text .js file. Keep index.html and app.js together in the same local folder.

The <script> element in index.html connects the page to app.js. Because this external classic script has defer, the browser can parse the HTML while it downloads the script, then runs the script after HTML parsing finishes.

console.log(...) sends a message to the browser’s Console. It does not add visible text to the page.

Follow the script path

A flow diagram showing index.html and app.js in one local folder, the browser opening the HTML file and running the JavaScript file, then a message appearing in the Console.

Open index.html; its deferred script connection loads and runs app.js after the HTML is parsed, and console.log sends output to the Console.

Run the first script

Create the two-file setup

Create a folder for this tutorial. Inside it, create two plain-text files named exactly index.html and app.js. Replace the complete contents of each file with the matching code below. Save both files.

Then open index.html in your browser, or refresh it if it is already open. Open the browser developer tools and select the Console panel to inspect the logged message.

index.html

Complete runnable replacement — index.html. Replace the entire contents of index.html with this file.

html
<!doctype html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Notebook Order</title>
  <script src="app.js" defer></script>
</head>
<body>
  <h1>Notebook Order</h1>
</body>
</html>
Expected output
Notebook order ready.

When you open or refresh index.html after also saving app.js below, the linked script writes this line in the Console.

app.js

Complete runnable replacement — app.js. Replace the entire contents of app.js with this file, then save it.

javascript
console.log("Notebook order ready.");
Expected output
Notebook order ready.

Expected console output after saving both files and opening or refreshing index.html.

Check the local workflow

Complete the script connection

Complete the opening script tag so the HTML page connects to the external script using this tutorial’s setup.

html
<script ></script>

Put the workflow in order

After index.html is already open, arrange the workflow for checking a changed message in the Console.

  1. Inspect the Console
  2. Save app.js
  3. Edit app.js
  4. Refresh index.html in the browser

Confirm your own result

Verify your saved change

In your own app.js, replace only the message inside the double quotes with a different short English message of your choice. Save the file, refresh index.html, and inspect the Console.

Write exactly the changed Console line you observed.

Write at least 1 characters (0/1).

Step 2 of 8

Read Statements, Expressions, and Comments

Distinguish value-producing expressions, executable statements, and explanatory comments in a short JavaScript script.

Read a short script

Expressions inside statements

An expression is code that produces a value. A literal is a simple expression written directly in code: "Notebook" produces a string value, and 12 produces a number value.

A statement is an instruction in the script. In console.log("Notebook");, the complete line is a logging statement, while "Notebook" is the expression inside it. In this tutorial, end each statement with a semicolon.

One line, two roles

A diagram highlights the whole console.log line as a statement and the quoted Notebook value inside it as an expression.

The complete instruction is the statement; the value-producing literal within it is the expression.

app.js

Complete runnable replacement — app.js

javascript
// Log two literal expressions.
console.log("Notebook");
console.log(12);
Expected output
Notebook
12

After saving app.js, refresh index.html and inspect the Console.

Identify what each line does

Classify the fragments

Match each code fragment to its role.

Tap an item and then its matching pair.

Write the missing part

Complete a logging statement

Complete the statement so it displays the product name in the Console.

javascript
console.("Notebook");

Trace the output

Predict Console order

A script contains these lines in this exact source order:

console.log("Notebook");
// Log the price next.
console.log(12);
console.log("Done");

Arrange the values that appear in the Console from first to last. Do not include a value for the comment.

  1. Done
  2. Notebook
  3. 12

Step 3 of 8

Name Values with const and let

Declare readable names for notebook-order values, use const for fixed bindings, and use let when quantity needs reassignment.

Give each order value a name

Names for values

A variable gives a value a readable name so the script can use that value later. A declaration introduces the name; initialization supplies its first value.

In const unitPrice = 12;, unitPrice is the name and 12 is the initial value. Use descriptive lowerCamelCase names such as unitPrice and productName. Names are case-sensitive, so productName and productname are different names.

A diagram showing declaration parts connecting readable variable names to initial values for a notebook order.

A declaration connects a readable name to the value that initializes it.

Example — app.js fragment

javascript
const productName = "Notebook";
const unitPrice = 12;
const shippingFee = 5;

Allow quantity to change

Choose const or let

Choose the declaration keyword from whether the variable will need reassignment:

  • Use const when the binding will keep the same assigned value. It must be initialized on its declaration, and it prevents later reassignment of that binding.
  • Use let when the variable needs a new assigned value later.

For this order, the product name, unit price, and shipping fee stay the same. The quantity changes from 2 to 3, so quantity uses let. Prefer const whenever reassignment is unnecessary.

Notebook-order declarations

The declaration and initialization happen together in each row.

Use `let` only for the value that will be reassigned.
NameInitial valueKeywordWhy
productName"Notebook"constDoes not change
unitPrice12constDoes not change
quantity2letChanges later
shippingFee5constDoes not change

Tip

One declaration, then reassignment

Do not write let or const again when changing an existing variable. The line quantity = 3; is a reassignment: = assigns the value on the right to the existing name on the left. It is not an equality test.

Read values before and after reassignment

app.js — complete runnable replacement

javascript
const productName = "Notebook";
const unitPrice = 12;
let quantity = 2;
const shippingFee = 5;

console.log(quantity);
quantity = 3;
console.log(quantity);
Expected output
2
3

Expected console output

Trace the changing value

Statements run in source order. The first console.log reads the initialized value, 2. After quantity = 3;, the second console.log reads the new value, 3.

Replace the contents of your local app.js with the code above, save it, refresh index.html, and inspect the Console.

Before and after

The first log happens before reassignment; the second happens after it.

A variable name can refer to a newly assigned value later in the script.
Source-order momentquantity valueConsole output
Initialization2—
First log22
Reassignment3—
Second log33

Practice: declarations and a value trace

Complete and predict

Complete this app.js script. Choose declaration keywords, make the valid reassignment, and predict the first and second values logged to the Console.

javascript
 productName = "Notebook";
const unitPrice = 12;
 quantity = 2;
const shippingFee = 5;

console.log(quantity);
quantity = ;
console.log(quantity);

// Expected console output:
// 
// 

Step 4 of 8

Recognize Everyday Primitive Values

Recognize numbers, strings, booleans, null, and undefined in a notebook-order script.

Meet five primitive values

Basic values in an order

A primitive value is a basic value used directly in JavaScript. In this notebook-order example, you will work with five everyday kinds:

  • numbers, such as 12
  • strings, such as "Notebook"
  • booleans, true or false
  • null for an intentionally absent value
  • undefined when a declared variable has no supplied value

Quotes matter: 12 is a number, while "12" is text—a string.

A visual comparison

Five visual cards distinguish a numeric price, quoted numeric text, a false toggle, an empty discount value, and a delivery note with no supplied value.

The same order can contain a number, text, a yes-or-no value, an intentional absence, and an unsupplied value.

Value forms and roles

Each form has a different role in the notebook order.

A quoted value is text even when its characters look numeric.
Value formPrimitive categoryOrder role
`12`numberUnit price
`"Notebook"`stringProduct name
`false`booleanGift-wrap choice
`null`nullNo discount code
`let deliveryNote;`undefinedNo note supplied

Read values by their form

Two kinds of absence

null and undefined both describe an absent value, but they communicate different situations.

Use null when absence is intentional: discountCode currently has no code. Use a let declaration with no initializer when a variable exists but no value was supplied: deliveryNote is therefore undefined.

That differs from a name that was never declared at all: in that case, there is no variable with that name.

Example

Example

javascript
const unitPrice = 12;
const displayedUnitPrice = "12";
const hasGiftWrap = false;
const discountCode = null;
let deliveryNote;

Tip

Quotes change the value category

Do not put quotation marks around false or null. With quotation marks, they would be strings of text instead of the boolean or intentionally absent value shown here.

Practice: classify the forms

Check the value forms

Match each JavaScript form to its primitive category or meaning.

Tap an item and then its matching pair.

Apply: complete the order values

Complete the primitive-value examples

Complete the declarations so that each comment describes the value or declaration below it.

javascript
// Numeric amount
const unitPrice = ;

// Numeric-looking text
const displayedUnitPrice = ;

// Gift-wrap choice
const hasGiftWrap = ;

// No discount code entered
const discountCode = ;

// Note declared but not supplied

Step 5 of 8

Inspect Values with typeof

Inspect notebook-order values with typeof and recognize the historical null result.

Inspect the current value type

Ask JavaScript about a value

typeof is an operator: it evaluates an operand and produces a string that describes that operand’s current value type.

Use it inside a logging statement:

console.log(typeof variableName);

console.log displays the string returned by typeof in the Console. It does not add content to the web page.

From value to type-description string

A flow diagram showing notebook-order values passing through typeof and producing the descriptive strings number, string, boolean, object, and undefined.

typeof produces a descriptive string; it does not change the value it inspects.

Run and compare the results

app.js — complete runnable replacement

Replace the contents of app.js, save the file, refresh index.html, and inspect the Console.

javascript
const productName = "Notebook";
const unitPrice = 12;
const quantity = 2;
const shippingFee = 5;
const hasGiftWrap = false;
const discountCode = null;
let deliveryNote;

// Inspect the current value types.
console.log(typeof unitPrice);
console.log(typeof productName);
console.log(typeof hasGiftWrap);
console.log(typeof discountCode);
console.log(typeof deliveryNote);
Expected output
number
string
boolean
object
undefined

Expected console output (one line per logging statement). The Console displays the strings without quotation marks.

Value versus result

Each Console line is a result string returned by typeof. Compare that result with the value being inspected.

The inspected value stays the same; `typeof` only reports a description.
VariableCurrent valuetypeof result
unitPrice12number
productName"Notebook"string
hasGiftWrapfalseboolean
discountCodenullobject
deliveryNoteno supplied valueundefined

Warning

Important exception

typeof null returns the string "object". This is a historical limitation in JavaScript—not a classification of null as an object. null is still a primitive value that can represent intentional absence.

Practice the typeof form

Example: Complete the statements

Complete both Console statements so they inspect the values’ types.

javascript
console.log( unitPrice);
console.log( hasGiftWrap);

Apply and explain

Final check

Write two complete console.log statements: one that inspects quantity, and one that inspects discountCode.

Assume quantity currently holds 2. Then predict the two Console lines in order. Finally, state whether the second result proves that null is an object, and explain why in one sentence.

Write at least 80 characters (0/80).

Step 6 of 8

Calculate with Arithmetic Expressions

Use arithmetic precedence, parentheses, and statement order to calculate notebook-order totals.

Read arithmetic in the intended order

Arithmetic order

Arithmetic expressions combine numeric values with operators and produce a number. JavaScript uses + for addition, - for subtraction, * for multiplication, / for division, and % for the remainder after division.

Multiplication, division, and remainder happen before addition and subtraction. Operators at the same precedence level run from left to right: 20 / 5 * 2 becomes 4 * 2, so it produces 8. Parentheses make an intended group explicit.

Core arithmetic operators

Use these operators with numeric values.

The remainder operator (%) reports what is left after an integer division.
OperatorMeaningExampleResult
+Addition12 + 517
-Subtraction12 - 57
*Multiplication12 * 224
/Division12 / 26
%Remainder17 % 52

Precedence and grouping

A comparison between evaluating multiplication before addition and evaluating a parenthesized addition before multiplication.

Without parentheses, 12 + 2 * 5 produces 22 because multiplication happens first. With parentheses, (12 + 2) * 5 produces 70 because the addition is grouped first.

Store a total, then calculate again

Calculate at the right moment

For a notebook order, multiply the unit price by the quantity, then add shipping. The parentheses are not required by JavaScript for this particular formula, but they clearly show that the item subtotal is calculated before shipping is added.

A calculated value is stored when its declaration executes. If you later reassign an input, JavaScript does not go back and update an earlier calculated value automatically. Calculate again when you need a new total.

app.js — Complete runnable replacement

Replace the contents of app.js with this complete file. Save it, refresh index.html, and inspect the Console.

JavaScript
const productName = "Notebook";
const unitPrice = 12;
let quantity = 2;
const shippingFee = 5;

// Calculate totals at two execution moments.
const initialTotal = (unitPrice * quantity) + shippingFee;

quantity = 3;
const updatedTotal = (unitPrice * quantity) + shippingFee;

console.log(initialTotal);
console.log(updatedTotal);
Expected output
29
41

The first total was calculated while quantity was 2. The second calculation occurs after quantity is reassigned to 3.

Practice precedence

Same-level operators

What number does this expression produce?

20 / 5 * 2

Compare the grouping

Which pair gives the results of these expressions in order?

8 + 4 * 3
(8 + 4) * 3

Apply the complete calculation

Final calculation challenge

Complete the script. Use the changed quantity before calculating the total, then record the results of the grouped and ungrouped expressions in their comments.

JavaScript
const unitPrice = 12;
let quantity = 2;
const shippingFee = 5;

quantity = ;
const total = (unitPrice * quantity)  shippingFee;

const groupedResult = (10 + 2) * 3; // 
const ungroupedResult = 10 + 2 * 3; // 

console.log(total);
console.log(groupedResult);
console.log(ungroupedResult);

Step 7 of 8

Build Readable Strings

Produce a readable Console summary with concatenation and template-literal interpolation.

When + Builds Text

Concatenation joins pieces of text

The + operator can add numbers or join text. When both operands are numbers, it performs numeric addition. When you combine a string with a number, the result is text—a concatenated string.

For a readable message, include every space and punctuation mark deliberately. JavaScript does not add a space between pieces for you.

Example

Example

javascript
const total = unitPrice * quantity + shippingFee;
const totalLabel = "Total: $" + total;

console.log(totalLabel);

Build the Notebook Summary

Use backticks and placeholders

A template literal is often clearer for a message with several values. It uses backticks instead of ordinary double quotes.

Inside a template literal, ${...} inserts the value produced by an expression. Text outside a placeholder stays exactly as written, including spaces, commas, dollar signs, and periods.

From values to one Console message

Diagram showing three values flowing into placeholder slots in a template literal and becoming one Console message.

Literal text remains fixed; each ${...} placeholder contributes the current value of its expression to the final Console line.

app.js

Replace the contents of app.js with this complete runnable file. Save it, refresh index.html, and inspect the Console.

javascript
const productName = "Notebook";
const unitPrice = 12;
let quantity = 2;
const shippingFee = 5;

quantity = 3;

// Calculate the total.
const total = unitPrice * quantity + shippingFee;
console.log(`${productName}: ${quantity} items, total $${total}.`);
Expected output
Notebook: 3 items, total $41.

Expected console output after the saved file runs in the linked local page.

Check the Result Type

Check numeric addition versus text

With unitPrice equal to 12, quantity equal to 3, and shippingFee equal to 5, which expression produces the number 41 rather than a string?

Apply the Full Message Pattern

Write and Predict the Summary

Use these bindings: productName is "Notebook", unitPrice is 12, quantity is 3, and shippingFee is 5.

Write three lines:

  1. A statement that calculates the numeric total.
  2. A console.log statement using a template literal for the notebook summary.
  3. The exact Console output.

Preserve the required spaces, comma, dollar sign, and final period.

Write at least 100 characters (0/100).

Step 8 of 8

Apply and Review: An Order Summary

Complete a local notebook-order script, verify its Console output, and review variables, primitive values, arithmetic, and interpolation.

Run the baseline script

Run the integrated baseline

Use the two local files you created earlier. Keep index.html connected to app.js with the deferred classic script. Then replace the entire contents of app.js with the runnable script below.

This first run uses quantity 2. The total is calculated when the total statement runs, and console.log sends two different results to the Console: a readable order summary and a type description.

app.js — complete runnable replacement

javascript
const productName = "Notebook";
const unitPrice = 12;
let quantity = 2;
const shippingFee = 5;

// Calculate the total.
const total = unitPrice * quantity + shippingFee;

console.log(`${productName}: ${quantity} items, total $${total}.`);
console.log(typeof total);
Expected output
Notebook: 2 items, total $29.
number

Expected console output after saving app.js, refreshing index.html, and opening the Console.

Two kinds of Console output

A diagram shows app.js running in a browser and producing a summary line followed by a type-description line in the Console.

The first Console line communicates the order result. The second line is the string produced by typeof total.

Apply declarations and arithmetic

Complete the changed-order script

Complete the missing declaration keyword and arithmetic operators in this updated order script.

javascript
const productName = "Notebook";
const unitPrice = 12;
 quantity = 2;
const shippingFee = 5;

quantity = 3;

// Calculate the total.
const total = unitPrice  quantity  shippingFee;

console.log(`${productName}: ${quantity} items, total $${total}.`);
console.log(typeof total);

Verify the quantity change

Change, save, refresh, inspect

Now verify both quantities in your own local file.

  1. Run the baseline version again and confirm that quantity 2 produces total $29.
  2. Insert the reassignment below immediately before the const total calculation.
  3. Save app.js, refresh index.html, and inspect the Console again.

Placement matters: a calculated value does not automatically change when an input changes later. With the reassignment before calculation, the new summary total is $41. The type inspection still reports number.

Example

Example

javascript
quantity = 3;

Summary

Review the connections

This small script brings together the core workflow:

  • A deferred external script runs from your local app.js file.
  • const names initialized bindings that are not reassigned; let supports the changing quantity.
  • Strings, numbers, booleans such as hasGiftWrap = false, intentional absence such as discountCode = null, and an uninitialized let deliveryNote; are everyday primitive-value examples.
  • Arithmetic creates a numeric total, and a template literal builds a readable message.
  • typeof describes the current value with a string.
  • Edit, save, refresh, then inspect the Console.
  • Use let only when reassignment is needed.
  • The total uses multiplication before addition.
  • Template literals insert named values with ${...}.
  • typeof total reports the type-description string "number".

Report and finish

Report your observed result

After completing both local runs, report what you actually observed after the run with the changed quantity. Write the full summary line, the type-inspection result, and a brief explanation of why the declaration for quantity differs from the declarations for bindings that are not reassigned.

Write at least 90 characters (0/90).

Tutorial complete

Congratulations! You completed: Work with JavaScript Values and Variables

You ran a local JavaScript script, named and reassigned values appropriately, inspected a type, calculated totals, and logged an interpolated order summary.

Download the App now to have access to + 5000 free courses, exercises, certificates and lots of content without paying anything!

  • 100% free online courses from start to finish

    Thousands of online courses in video, ebooks and audiobooks.

  • More than 60 thousand free exercises

    To test your knowledge during online courses

  • Valid free Digital Certificate with QR Code

    Generated directly from your cell phone's photo gallery and sent to your email

Cursa app on the ebook screen, the video course screen and the course exercises screen, plus the course completion certificate