Skip to lesson content
Web Technologies โ€บ Level 14
LEVEL 14 ยท JAVASCRIPT

JavaScript Fundamentals

Understand values, predict expressions and turn validated input into useful results.

๐Ÿ“ฆ Values + types๐Ÿงฎ Expressions๐Ÿงญ Logic + functions๐Ÿงช Lab + MCQs
01

Learning Objectives

Level 13 arranged content with CSS. This lesson adds decisions and calculations with JavaScript. You will declare variables, identify value types, evaluate expressions, convert text deliberately, compare values, and write small conditions, loops and functions.

Our running task is a workshop seat check: read the available seats and reserved seats, validate the input and calculate the remaining places. The important skill is explaining each step, including why text from a form cannot simply be treated as an already validated number.

Values

Distinguish a binding from the value it currently holds.

Expressions

Predict an operation from the operand types.

Logic

Choose a branch and stop a bounded loop correctly.

Checks

Test ordinary, zero, blank and invalid input deliberately.

02

HTML, CSS and JavaScript โ€” Three Roles

HTML gives the workshop page meaningful structure. CSS arranges and styles its cards. JavaScript can calculate remaining seats, react to an action and update feedback. These roles cooperate: JavaScript does not replace a native button or make an unclear page understandable by itself.

JavaScript and Java are different languages. The similar names do not mean the same syntax, runtime or type system. This lesson uses JavaScript in a browser; some of the same language features also run in environments such as Node.js.

Keep useful learning content in the document even when scripting is unavailable. Add behavior to meaningful controls rather than making a styled paragraph pretend to be a button.

Workshop page responsibilities
HTML

Heading, labeled inputs, button and result region.

CSS

Readable layout, spacing and visible focus.

JavaScript

Validate values, calculate and report a result.

03

Language and Runtime โ€” Know Where Code Runs

The JavaScript language defines values, expressions, functions and control flow. A browser supplies additional facilities such as document, event handling and developer tools. Console is supplied by common runtimes rather than being an ECMAScript language keyword.

A page script normally runs with the pageโ€™s environment. Node.js supplies a different environment and does not provide a page document by default. If a browser example uses document.getElementById, copying it into a plain Node program is not enough to create a webpage.

Use the browser console for small trusted experiments. A console log is a diagnostic output, not automatically visible lesson content. A real user-facing result should appear in an appropriate page element.

const seats = 30;
const reserved = 12;
console.log(seats - reserved); // 18

This pure calculation does not need document. The later DOM lesson will develop element selection and events in detail; here we concentrate on the values and logic behind the result.

04

Load a Script Deliberately

For a classic external script that needs the parsed HTML, defer is a useful loading choice. The browser can fetch the file while parsing, then execute deferred classic scripts after parsing and before DOMContentLoaded. Deferred classic scripts execute in document order.

Async serves a different purpose: it does not promise document order or wait for parsing in the same way. Avoid choosing it for two dependent page scripts simply because the word sounds faster. Module scripts have their own rules and are deferred by default; modules are beyond this introduction.

<script src="workshop.js" defer></script>

Put this element in the page head and keep the file path correct. If the behavior is absent, inspect the Network panel for a failed request and the Console for an error. The defer attribute is intended for external classic scripts; it is not a repair for inline code placed before the elements it uses.

Do not paste unfamiliar code into a console or run downloaded scripts merely to test a tutorial. All examples in this lesson are small and explained.

05

Statements, Expressions and Comments

An expression produces a value, such as seats - reserved. A statement performs an action or controls execution, such as a declaration or an if statement. A declaration can contain an expression that supplies its initial value.

JavaScript is case-sensitive: remaining and Remaining are different names. Choose names that explain the role of a value. Comments explain intent; they should not contradict what the code actually does.

This lesson writes semicolons explicitly. Automatic semicolon insertion exists, but it is not a reason to put a return value on a new line and assume the result is unchanged.

const seats = 30; // total workshop capacity
let reserved = 12;
reserved = reserved + 3;
const remaining = seats - reserved;
console.log(remaining); // 15

Trace in order: reserved begins as 12, is reassigned to 15, then remaining receives 30 - 15. Reassigning reserved after that calculation would not automatically recalculate remaining. A stored result is not a spreadsheet formula linked to the other bindings.

06

let and const โ€” Binding Rules

Use const when the binding should not be reassigned. Use let when a later assignment is part of the intended algorithm. Both are block-scoped. A const declaration needs an initializer; a let binding declared without one starts with undefined after its declaration executes.

Const does not freeze an object or an array. It prevents assigning a different value to the binding. Changing an allowed property of the object is a separate operation. Var has older function-scoping behavior and is useful to recognize, but our new examples use let and const.

A let or const binding cannot be safely read before its declaration executes in its scope. The interval before initialization is often called the temporal dead zone; an early access throws ReferenceError. Do not describe it as automatically yielding undefined.

const workshop = { seats: 30 };
workshop.seats = 32; // allowed property update
// workshop = { seats: 40 }; // TypeError if executed

let reserved = 12;
reserved = 15; // allowed reassignment

Keep reassignment and mutation separate when explaining this example. Object handling will be developed in Level 15.

07

Values Have Types

JavaScript is dynamically typed: a let binding can hold values of different types over time. Each value still has a type that affects an operation. The string "12" is different from the number 12 even when both look similar on a screen.

Primitive types include string, number, boolean, undefined, null, bigint and symbol. Objects form another major category; arrays and functions are objects with specialized behavior. This lesson focuses on ordinary strings, numbers, booleans and missing-value cases.

Number commonly represents both integer and fractional numeric values. It uses binary floating-point, so not every decimal fraction is represented exactly. BigInt handles integers differently and is not interchangeable with Number in every operation.

String

"12" is text; quotes are part of the code notation.

Number

12 and 12.5 are Number values.

Boolean

true and false express a logical result.

Missing values

undefined often represents an absent value; null can represent an intentional empty value.

const label = "Workshop";
const seats = 30;
const full = false;
let note; // undefined
const selectedSession = null;
08

typeof โ€” Useful, with Limits

Typeof produces a string describing the operandโ€™s type category. It helps explain an unexpected expression, but it is not a complete validation function. Typeof NaN is "number" even though NaN is not a usable finite result for the seat calculation.

Typeof null is historically "object". That result does not make null an ordinary object you can safely read properties from. Arrays also report "object"; use Array.isArray when an actual array test is needed. Functions report "function".

typeof "12";       // "string"
typeof 12;         // "number"
typeof false;      // "boolean"
typeof undefined;  // "undefined"
typeof null;       // "object"
typeof NaN;        // "number"

For a value expected to be a finite Number, Number.isFinite checks both the type and finiteness without first converting a string. Number.isFinite("12") is false. Explicit conversion and validation are separate decisions.

09

Arithmetic and Evaluation Order

Arithmetic operators include +, -, *, /, ** and %. The percent operator computes a remainder; calling it mathematical modulo can be misleading for negative operands. Use parentheses when grouping is part of the meaning you want to communicate.

Multiplication has higher precedence than addition. Assignment stores the evaluated result in a binding. Increment and decrement change a binding; prefix and postfix forms produce different expression values, so begin with clear standalone updates.

The + operator can concatenate strings as well as add numbers. Most other basic arithmetic operators can also convert operands, but relying on surprise conversions makes input handling harder to explain.

2 + 3 * 4;     // 14
(2 + 3) * 4;   // 20
17 % 5;        // 2
-17 % 5;       // -2
2 ** 3;        // 8

let reserved = 12;
reserved += 3; // 15

For approximate measurements, a tiny floating-point difference may be expected: 0.1 + 0.2 is not exactly 0.3. Our seat count is restricted to small integers; currency or scientific computations require a deliberate representation and rounding policy.

10

Strings, Concatenation and Templates

A string stores text. Single quotes, double quotes and backticks offer different literal syntax. Template literals use backticks and interpolate expressions inside ${...}; they are convenient for a readable message.

If one operand is a string after the relevant conversion steps, + concatenates instead of doing ordinary numeric addition. "30" + "12" produces "3012". Converting after the concatenation cannot reconstruct the sum you intended.

const seatsText = "30";
const reservedText = "12";
console.log(seatsText + reservedText); // "3012"

const remaining = 18;
const message = `Remaining seats: ${remaining}`;
console.log(message); // Remaining seats: 18

String length counts UTF-16 code units, so it is not always the number of user-perceived characters. For this lessonโ€™s numeric input, the important distinction is text versus Number, not an advanced character-counting algorithm.

11

Conversion and Validation Are Different

An HTML inputโ€™s value is a string. Number converts a whole string according to numeric conversion rules. Number("12") becomes 12, while Number("12 seats") becomes NaN. Number("") and Number(" ") become 0, so conversion alone does not prove that a learner entered a value.

ParseInt can read an initial integer part: parseInt("12 seats", 10) produces 12. That behavior can be useful in another task but is unsuitable if the whole seat-count field must be valid. Decide which format is acceptable before choosing a parser.

For this workshop, accept decimal digits only, convert them, require a safe integer in the range 0โ€“1000, and require reserved not to exceed capacity. The range is a teaching policy, not a JavaScript language limit. Zero is a valid entry; blank text is not.

function readSeatCount(text) {
  const trimmed = text.trim();
  if (!/^\d+$/.test(trimmed)) return null;
  const value = Number(trimmed);
  if (!Number.isSafeInteger(value) || value > 1000) return null;
  return value;
}

Null here means invalid under our functionโ€™s contract. The caller must check it explicitly. Do not use if (!value) to reject a seat count, because that would also reject the valid Number 0.

12

Assignment, Strict Equality and Loose Equality

The single equals sign assigns. Strict equality, ===, compares without converting different operand types to match. Loose equality, ==, follows coercion rules that can match differently typed values. Use strict equality in new beginner examples when you want the type distinction to remain visible.

Both strict equality and loose equality have rules beyond a simple slogan. NaN is not equal to itself using either operator. Objects are compared by identity rather than by automatically comparing all properties. A complete sameness discussion belongs after these basics.

"12" === 12; // false: different types
"12" == 12;  // true: coercion in this case
12 === 12;   // true
NaN === NaN; // false

let remaining = 18;
remaining = 0; // assignment, not a comparison

In an if condition, an accidental assignment can change data and then test the assigned value. Inspect the operator carefully when a branch behaves unexpectedly. For NaN checks, use Number.isNaN on an already converted Number.

13

Truthiness and Logical Operators

Conditions can convert a value to boolean. Falsy values include false, 0, -0, 0n, the empty string, null, undefined and NaN. An ordinary non-empty string such as "0" or "false" is truthy. The stringโ€™s spelling does not make it the corresponding boolean value.

The && and || operators short-circuit and return one of their operands; they do not always produce a boolean. The ! operator produces a boolean negation. The ?? operator uses its fallback only for null or undefined, so it can preserve a useful zero.

Boolean("0"); // true
Boolean(0);   // false

const remaining = 0;
remaining || 10; // 10: zero is falsy
remaining ?? 10; // 0: zero is not null or undefined

A default of ten remaining seats would be wrong when the real result is zero. Match the fallback operator to the missing-value policy. For a numeric range check, compare the numeric value explicitly rather than relying only on truthiness.

14

Control Flow โ€” Conditions and Bounded Loops

An if/else statement selects a branch from a condition. Check invalid values before the main calculation. Keep mutually exclusive outcomes clear: invalid input, overbooked capacity, full workshop, or available seats.

A loop repeats a body while its control rules permit another iteration. A for loop states its initialization, condition and update together. Think about the first value, final accepted value and what changes each time. A loop whose condition never becomes false can freeze the page.

const remaining = 3;
if (remaining === 0) {
  console.log("Workshop full");
} else {
  console.log(`${remaining} seats available`);
}

for (let seat = 1; seat <= 3; seat += 1) {
  console.log(`Seat ${seat}`);
} // Seat 1, Seat 2, Seat 3

For this loop, seat begins at 1, the condition permits 1, 2 and 3, and the next update makes it 4 so the body stops. Changing <= to < would omit Seat 3. Start with a small bounded count before using a user-provided loop limit.

15

Functions โ€” Inputs, Return Values and Scope

A function packages a task. Parameters name incoming values; arguments are the actual values supplied at a call. Return gives a result to the caller and ends that function invocation. Console.log prints a diagnostic message and is not a substitute for returning the result.

A function that reaches its end without an explicit returned value yields undefined. Put the return expression on the same line as return in these beginner examples. A local binding belongs to its applicable scope rather than automatically becoming a global page variable.

function remainingSeats(capacity, reserved) {
  return capacity - reserved;
}
const result = remainingSeats(30, 12);
console.log(result); // 18

This function assumes already validated numeric arguments. It does not read or validate an HTML input by itself. Keep those assumptions visible rather than claiming a two-line subtraction function handles every user entry.

Arrow functions offer another function syntax, such as const double = value => value * 2. Learn the task and return behavior first; different syntaxes also have differences such as their handling of this, which later lessons will cover.

16

Premium Visualizer โ€” From Text to a Result

Follow a fixed workshop example through reading, validation, conversion, calculation and reporting. Use the familiar numbered timeline and playback controls. Explain why each stage is needed instead of jumping directly from a string to an assumed answer.

JAVASCRIPT VALUE TRACE
Step 1 of 5
STEP 01

Begin with text input

The fixed teaching values are the strings "30" and "12".

capacityText = "30"
reservedText = "12"

What is happening?

Input.value provides text. Similar-looking text and numbers can behave differently.

17

Premium Interactive โ€” Values and Seat-Count Lab

Choose one of six explained operations and supply two text values. The lab uses real, fixed JavaScript operations; it does not execute arbitrary pasted code. The expression and result are displayed as text. A and B start as strings, just as values read from ordinary inputs do.

Compare string concatenation with explicit numeric addition. The equality examples compare string A with Number(B), which makes the type distinction visible. The truthiness example uses A only. The final scenario validates decimal seat counts and reports the remaining capacity.

Blank text is useful for the conversion experiment: Number("") is 0. In the seat-count scenario, blank text is rejected. General numeric addition requires finite converted values; the seat scenario has the stricter integer, range and relationship rules explained above.

Ready to check 30 capacity and 12 reserved.

Operation and inputs

Result and value type

18

Debugging โ€” Find the First Wrong Assumption

Load

Check the external script path and the first console error.

Type

Inspect the value and typeof before an unexpected operation.

Input

Distinguish blank, invalid, converted and accepted input.

Flow

Check the selected branch, loop boundary and returned value.

A SyntaxError indicates a parsing problem, such as an unmatched bracket. A ReferenceError can indicate an unknown identifier or a binding accessed too early. A TypeError can arise from an operation inappropriate for the value, such as reading a property from null. Read the first relevant message and its location before editing unrelated CSS.

If addition creates 3012, check whether both operands are strings. If a zero count is rejected, look for a truthiness check that treats zero as missing. If a function call returns undefined, inspect its return path rather than assuming the console output was returned.

After a correction, repeat the case that failed and one neighboring case. For the workshop, capacity 30/reserved 12 should give 18; capacity 30/reserved 30 should report full; capacity 30/reserved 31 should be rejected.

19

Interview Questions โ€” Flip to Explain

QUESTION

What does dynamically typed mean?

Click or press Enter to explain
ANSWER

Bindings can hold values of different types over time. The values still have types that affect operations.

QUESTION

Does const make an object immutable?

Click or press Enter to explain
ANSWER

No. It prevents reassignment of that binding; allowed properties of the referenced object can still change.

QUESTION

Why can "30" + "12" produce "3012"?

Click or press Enter to explain
ANSWER

The operands are strings, so + concatenates them. Convert deliberately before numeric addition.

QUESTION

Is Number conversion enough to validate a seat count?

Click or press Enter to explain
ANSWER

No. Blank text converts to zero, and other results still need format, integer, range and relationship checks.

QUESTION

How do === and == differ?

Click or press Enter to explain
ANSWER

Strict equality does not coerce different types to match. Loose equality applies coercion rules, which can match a string and number.

QUESTION

Why is "0" truthy while 0 is falsy?

Click or press Enter to explain
ANSWER

The first is a non-empty string; the second is numeric zero. Truthiness depends on the actual value.

QUESTION

What is the difference between returning and logging?

Click or press Enter to explain
ANSWER

Return supplies a result to the function caller and ends the invocation. Logging prints a diagnostic output.

QUESTION

Why can <= and < change a loop result?

Click or press Enter to explain
ANSWER

They include or exclude the boundary value. Trace initialization, condition, update and the intended final iteration.

20

MCQ Practice โ€” Predict Before Running

PRACTICE

1. Which binding should you use when reassignment is intended?

PRACTICE

2. What does const prevent?

PRACTICE

3. What is the result of "3" + "4"?

PRACTICE

4. What does Number("") produce?

PRACTICE

5. What does typeof null produce?

PRACTICE

6. What is the result of "12" === 12?

PRACTICE

7. Which ordinary value is truthy?

PRACTICE

8. What does 0 ?? 10 produce?

PRACTICE

9. What does 2 + 3 * 4 produce?

PRACTICE

10. How many body executions occur for i = 1; i <= 3; i += 1?

PRACTICE

11. What does a function return when it ends without a returned value?

PRACTICE

12. Under this lessonโ€™s seat policy, capacity 30 and reserved 31 should beโ€ฆ

21

Extra Practice โ€” Specific Inputs and Expected Results

Text addition

Use A="3", B="4" in concatenation. Expected: string "34". Switch to numeric addition: number 7.

Blank input

Use A="", B="4" in numeric addition. Expected: 4 after conversion. Seat validation must reject the blank capacity.

Equality

Use A="12", B="12". Expected: strict comparison against Number(B) is false; loose comparison is true.

Zero text

Use A="0" in Boolean(A). Expected: true. Compare Boolean(0) in your own small script: false.

Available seats

Use capacity 30 and reserved 12. Expected: 18 available.

Invalid reservation

Use capacity 30 and reserved 31. Expected: relationship error; do not report a negative availability.

Loop boundary

Print seat numbers 1โ€“3 with <=. Expected: three lines. Switch to <: two lines.

Function return

Write a pure subtraction function with validated numeric arguments 10 and 4. Expected returned Number: 6.

22

Quick Revision

Binding: Use const by default and let for intended reassignment.
Types: A text numeral and a Number are different values.
Inspection: typeof is useful but not complete validation.
Operators: Read operand types and precedence before predicting.
Strings: + may concatenate; templates build clear messages.
Conversion: Convert deliberately and validate the required format.
Comparison: Distinguish assignment, strict equality and coercion.
Truthiness: Zero and missing input are not interchangeable.
Control flow: Trace branches and loop boundaries explicitly.
Functions: Separate inputs, local logic and returned results.
23

Glossary โ€” Flip to Learn

TERM

Binding

Click to see meaning
DEFINITION

Binding

A name associated with a value in an applicable scope.

TERM

Expression

Click to see meaning
DEFINITION

Expression

Code evaluated to produce a value.

TERM

Statement

Click to see meaning
DEFINITION

Statement

A unit of code that performs an action or controls execution.

TERM

Primitive

Click to see meaning
DEFINITION

Primitive

A value in a primitive type category, such as string, number or boolean.

TERM

Coercion

Click to see meaning
DEFINITION

Coercion

An implicit type conversion performed according to an operationโ€™s rules.

TERM

Validation

Click to see meaning
DEFINITION

Validation

Checking whether input meets the taskโ€™s stated acceptance rules.

TERM

Truthy

Click to see meaning
DEFINITION

Truthy

A value that converts to true in a boolean context.

TERM

Scope

Click to see meaning
DEFINITION

Scope

The region of code in which a binding is available under its rules.

TERM

Parameter

Click to see meaning
DEFINITION

Parameter

A named input in a function definition.

TERM

Return value

Click to see meaning
DEFINITION

Return value

The result supplied by a function invocation to its caller.

24

Final Challenge โ€” Explain a Workshop Seat Check

Write a small program that accepts two text values under the lessonโ€™s decimal-digit policy. Return a clear error for blank or malformed input, values above 1000, or reserved seats exceeding capacity. Otherwise calculate the remaining count and select either โ€œWorkshop fullโ€ or a message with the available count.

Separate a readSeatCount helper from the arithmetic and reporting decisions. Check null explicitly so the valid zero survives. Use const where a binding is not reassigned, strict equality for the full check and a template literal for the available message.

Test 30/12 โ†’ 18 available, 30/30 โ†’ full, 0/0 โ†’ full, blank/0 โ†’ rejected, 30/31 โ†’ rejected, 30/2.5 โ†’ rejected and 1001/0 โ†’ rejected. Explain the rejection stage, not just the final printed word.

Success criterion: predict the value and type at each stage, demonstrate a meaningful return value, preserve zero correctly and explain a loop boundary. Level 15 will extend these foundations to arrays, objects and practical data logic.

25

Level 14 Complete?

Before marking complete, explain one concatenation surprise, one strict comparison, one zero-versus-blank check, a bounded loop and a returned function value. Completion records a local learning milestone; it is not an assessment score.