JavaScript Essentials

Complete Learning Material

This chapter introduces two core building blocks of JavaScript:

Variables & primitive data types – how we represent and store values.

Operators – how we compute with and compare those values.

Students should come away able to:

Declare and name variables properly.

Use JavaScript’s primitive types (string, number, BigInt, boolean, symbol, undefined, null).

Inspect and convert data types.

Apply arithmetic, assignment, comparison, and logical operators correctly.

1. Variables

1.1. What is a variable?

A variable is a named storage location whose value can change while the program runs.

Example:

firstname = "Maaike";
x = 2;
firstname = "Edward";
x = 7;

Line-by-line:

firstname = "Maaike"; — assigns the text "Maaike" to firstname.
x = 2; — assigns the number 2 to x.
firstname = "Edward"; — changes firstname to "Edward".
x = 7; — changes x to 7.

Without variables, a script would always do exactly the same thing on every run; variables allow scripts to react to new information (user input, data from a server, etc.).

1.2. Declaring variables: let, var, const

In modern JavaScript, every new variable should be declared with a keyword: let, var, or const.

Example:

let firstname = "Maria";
firstname = "Jacky";
let firstname = "Maria"; — declares a new variable and gives it an initial value.
firstname = "Jacky"; — reassigns that existing variable to a new value.

1.2.1. Differences between let, var, and const

Example:

let nr1 = 12;
var nr2 = 8;
const PI = 3.14159;

let – block-scoped variable that can be reassigned.

var – function- or global-scoped variable; older and more error-prone; avoid in new code.

const – block-scoped binding that cannot be reassigned.

Illustration of const:

const someConstant = 3;

someConstant = 4; // ❌ TypeError at runtime

The second line attempts to reassign a constant and causes: Uncaught TypeError: Assignment to constant variable.

For beginners, recommend:

Use const by default.

Use let when you know the value will change.

Avoid var except when reading legacy code.

1.3. Variable naming conventions

Rules & conventions:

Start names with a letter, _, or $; not a digit.

No spaces; use camelCase for multi-word names (e.g. ageOfBuyer).

Use descriptive names: age, totalPrice instead of x, y.

Examples:

let age = 30;
let ageOfBuyer = 25;
let total_price = 199.99;  // valid, but camelCase is preferred

2. Primitive Data Types

JavaScript is loosely typed: the type is determined by the value, not declared explicitly.

There are seven primitive types:

string

number

bigint

boolean

symbol

undefined

null

Each occupies a single value (unlike arrays/objects, which group multiple values).

2.1. Strings

A string represents text (a sequence of characters).

You can create strings using:

Single quotes '...'

Double quotes "..."

Backticks `...` (template literals)

2.1.1. Basic string literals

let singleString = 'Hi there!';
let doubleString = "How are you?";

Both lines declare string values; choice of single vs double quotes is mostly stylistic.

Be careful with quotes inside strings:

let funActivity = 'Let's learn JavaScript'; // ❌ error

The ' in Let's prematurely ends the string.

Correct approach:

let funActivity = "Let's learn JavaScript"; // ✅

Using double quotes allows an unescaped single quote inside.

Similarly:

let question = 'He said "Yes!"';      // ✅
let broken  = "He said "Yes!"";       // ❌ error

2.1.2. Template literals and interpolation

Backtick strings (template literals) support expression interpolation with ${...}

let language = "JavaScript";
let message = `Let's learn ${language}`;
console.log(message);

Line-by-line:

language holds "JavaScript".

Template literal: `Let's learn ${language}` inserts the value of language into the string.

Output: Let's learn JavaScript.

Use template literals whenever you need to build strings from variables.

2.1.3. Escape characters

The escape character \ gives special meaning to the next character.

Example:

let str = "Hello, what's your name? Is it \"Mike\"?";
console.log(str);
let str2 = 'Hello, what\'s your name? Is it "Mike"?';
console.log(str2);

\" lets you include a double quote inside a double-quoted string.

\' lets you include a single quote inside a single-quoted string.

Other common escapes:

let str3 = "New \nline.";
let str4 = "I'm containing a backslash: \\!";
console.log(str3);
console.log(str4);

Output:

str3 prints as two lines: New then line.

str4 prints: I'm containing a backslash: \!

ASCII visualization of escape behavior:

text

"New \nline."

|

+---> newline inserted here

2.2. Numbers (number)

JavaScript has a single numeric type: 64-bit floating-point number.

The number type covers:

Integers: 4, -111

Decimals: 1.5, 45.78

Exponentials: 1.4e15 (≈ 1.4×10151.4×1015)

Octal: 0o10 (8 in decimal)

Hexadecimal: 0x3E8 (1000 in decimal)

Binary: 0b101 (5 in decimal)

Example:

let intNr  = 1;
let decNr  = 1.5;
let expNr  = 1.4e15;
let octNr  = 0o10;   // 8
let hexNr  = 0x3E8;  // 1000
let binNr  = 0b101;  // 5 

Each of these variables has type number.

2.3. Big integers (bigint)

number has safe integer limits of . For larger integers, JavaScript provides BigInt, written with an n suffix.

let bigNr = 90071992547409920n;  // BigInt

Mixing BigInt and number in arithmetic is not allowed:

let intNr = 1;
let result = bigNr + intNr;   // ❌ TypeError

Error message: Uncaught TypeError: Cannot mix BigInt and other types, use explicit conversions.

Note: use BigInt only when you truly need very large integers, and convert types explicitly when necessary.

2.4. Booleans (boolean)

A boolean holds exactly two values: true or false.

let bool1 = false;
let bool2 = true;
let objectIsDeleted = false;
let lightIsOn = true;

Booleans often model yes/no, on/off, or pass/fail states.

2.5. Symbols (symbol)

Symbol is a primitive introduced in ES6 for creating unique identifiers.

Compare strings and symbols:

let str1 = "JavaScript is fun!";
let str2 = "JavaScript is fun!";
console.log("These two strings are the same:", str1 === str2);
let sym1 = Symbol("JavaScript is fun!");
let sym2 = Symbol("JavaScript is fun!");
console.log("These two Symbols are the same:", sym1 === sym2);

Output:

text

These two strings are the same: true

These two Symbols are the same: false

Strings with the same characters are equal.

Symbols are always unique, even if created with the same description.

Symbols are often used as unique keys in objects (covered in later chapters).

2.6. undefined

undefined means a variable exists but has no assigned value yet.

let unassigned;
console.log(unassigned); // undefined

You can manually assign undefined, but it’s considered bad practice:

let terribleThingToDo = undefined;  // avoid this

Reason: explicit undefined can confuse equality checks and make it harder to distinguish “never set” from “intentionally set to empty”.

2.7. null

null is an explicit “empty” or “unknown” value.

let empty = null;

null is the recommended way to say “no value yet” or “reset to empty”.

Why not use undefined? Consider:

let terribleThingToDo = undefined;
let lastName;
console.log("Same undefined:", lastName === terribleThingToDo);
let betterOption = null;
console.log("Same null:", lastName === betterOption);

Output:

text

Same undefined: true

Same null: false

A never-assigned variable (lastName) is undefined.

Comparing it to an explicitly set undefined returns true, which can be misleading.

Using null makes it clear the value was explicitly chosen, and comparisons behave as expected.

Note: typeof null returns "object" — this is a historical bug in JavaScript and cannot be changed due to backward compatibility.

3. Inspecting and Converting Data Types

3.1. Determining a type with typeof

The typeof operator returns the type of a value as a string.

Two equivalent forms:

variableTypeTest1 = typeof testVariable;

variableTypeTest2 = typeof(testVariable);

Example:

let str    = "Hello";
let nr     = 7;
let bigNr  = 12345678901234n;
let bool   = true;
let sym    = Symbol("unique");
let undef  = undefined;
let unknown = null;
console.log("str", typeof str);
console.log("nr", typeof nr);
console.log("bigNr", typeof bigNr);
console.log("bool", typeof bool);
console.log("sym", typeof sym);
console.log("undef", typeof undef);
console.log("unknown", typeof unknown);

Output:

text

str string

nr number

bigNr bigint

bool boolean

sym symbol

undef undefined

unknown object

Important note:

typeof null returns "object" (known bug).

All other results match the primitive types we discussed.

3.2. Implicit type coercion

JavaScript sometimes converts types automatically (coercion).

Example 1: multiplication

let nr1 = 2;
let nr2 = "2";
console.log(nr1 * nr2);

The string "2" is coerced to number 2, result is 4.

Example 2: addition

let nr1 = 2;
let nr2 = "2";
console.log(nr1 + nr2);

Here + is also the string concatenation operator.

JavaScript coerces the number to a string and concatenates: result "22".

This behavior can be surprising and a common bug source. Prefer explicit conversion.

3.3. Explicit conversions: String(), Number(), Boolean()

JavaScript provides conversion functions:

String(value) → string

Number(value) → number (or NaN)

Boolean(value) → boolean

3.3.1. String conversion

let nrToStr = 6;

nrToStr = String(nrToStr);

console.log(nrToStr, typeof nrToStr);

Output: 6 string.

3.3.2. Number conversion

let strToNr = "12";

strToNr = Number(strToNr);

console.log(strToNr, typeof strToNr);

Output: 12 number.

Less obvious cases:

let nullToNr = null;

nullToNr = Number(nullToNr);

console.log("null", nullToNr, typeof nullToNr);
let emptyStrToNr = "";

emptyStrToNr = Number(emptyStrToNr);

console.log("empty string", emptyStrToNr, typeof emptyStrToNr);

Output:

null 0 number

empty string 0 number

Both null and "" convert to the number 0.

Non-numeric string:

let strToNr2 = "hello";

strToNr2 = Number(strToNr2);

console.log(strToNr2, typeof strToNr2);

Output: NaN number.

NaN stands for “Not a Number”; the type is still number.

3.3.3. Boolean conversion

let strToBool = "any string will return true";

strToBool = Boolean(strToBool);

console.log(strToBool, typeof strToBool);

Output: true boolean.

Special cases:

let strToBool2 = "false";

strToBool2 = Boolean(strToBool2);

console.log(strToBool2, typeof strToBool2);
let emptyStrToBool = "";

emptyStrToBool = Boolean(emptyStrToBool);

console.log(emptyStrToBool, typeof emptyStrToBool);

Output:

text

true boolean

false boolean

Boolean conversion rules to emphasize:

false only for: null, undefined, 0, NaN, and "" (empty string).

Everything else → true (even the string "false").

3.3.4. Combining explicit conversion with arithmetic

let nr1 = 2;
let nr2 = "2";
console.log(nr1 + Number(nr2));   // 4

Number(nr2) converts "2" to 2, so + performs numeric addition.

4. Arithmetic Operators

Arithmetic operators perform basic math on numbers.

Operators covered:

+ addition (also string concatenation)

- subtraction

* multiplication

/ division (Quotient)

** exponentiation

% modulus (remainder)

++ increment

-- decrement

4.1. Addition (+)

Numeric addition:

let nr1 = 12;
let nr2 = 14;
let result1 = nr1 + nr2;
console.log(result1);  // 26

String concatenation:

let str1 = "Hello ";
let str2 = "addition";
let result2 = str1 + str2;
console.log(result2);  // "Hello addition"

Emphasize to students: when either operand is a string, + concatenates.

4.2. Subtraction (-)

let nr1 = 20;
let nr2 = 4;
let str1 = "Hi";
let nr3 = 3;
let result1 = nr1 - nr2;
let result2 = str1 - nr3;
console.log(result1, result2); // 16 NaN

Numeric subtraction works as expected.

Subtracting a string from a number yields NaN (Not a Number).

4.3. Multiplication (*)

let nr1 = 15;
let nr2 = 10;
let str1 = "Hi";
let nr3 = 3;
let result1 = nr1 * nr2;
let result2 = str1 * nr3;
console.log(result1, result2); // 150 NaN

Multiplying non-numeric strings with numbers results in NaN.

4.4. Division (/)

let nr1 = 30;
let nr2 = 5;
let result1 = nr1 / nr2;
console.log(result1); // 6

Standard floating-point division.

4.5. Exponentiation (**)

Exponentiation raises a base to a power, e.g. x ** y computes xyxy.

let nr1 = 2;
let nr2 = 3;
let result1 = nr1 ** nr2;
console.log(result1); // 8  (2 * 2 * 2)

Note: roots can be represented as fractional exponents (e.g. square root as power 0.5).

4.6. Modulus (%) (Remainder)

Modulus returns the remainder after integer division.

let nr1 = 10;
let nr2 = 3;
let result1 = nr1 % nr2;
console.log(`${nr1} % ${nr2} = ${result1}`);
let nr3 = 8;
let nr4 = 2;
let result2 = nr3 % nr4;
console.log(`${nr3} % ${nr4} = ${result2}`);
let nr5 = 15;
let nr6 = 4;
let result3 = nr5 % nr6;
console.log(`${nr5} % ${nr6} = ${result3}`);

Output:

text

10 % 3 = 1

8 % 2 = 0

15 % 4 = 3

4.7. Increment and decrement (++, --)

These unary operators add or subtract 1 from a variable.

Basic usage:

let nr1 = 4;

nr1++;

console.log(nr1);  // 5
let nr2 = 4;

nr2--;

console.log(nr2);  // 3

4.7.1. Prefix vs postfix

Postfix: x++ — returns the old value, then increments.

Prefix: ++x — increments first, then returns the new value.

Example:

let nr = 2;
console.log(nr++); // logs 2, then nr becomes 3
console.log(nr);   // logs 3
let nr = 2;
console.log(++nr); // nr becomes 3, then logs 3

Combined example:

let nr1 = 4;
let nr2 = 5;
let nr3 = 2;
console.log(nr1++ + ++nr2 * nr3++);

Evaluation:

++nr2 → nr2 becomes 6, value used is 6.

nr3++ → value used is 2, then nr3 becomes 3.

6 * 2 = 12.

nr1++ uses 4, then nr1 becomes 5.

4 + 12 = 16.

Final logged value: 16.

4.8. Operator precedence and grouping

Operations are evaluated in a defined order (precedence). Parentheses (...) override precedence and are evaluated first.

From highest to lower precedence in this chapter:

Example:

let result = 3 + 4 * 2 / 8;
console.log(result); // 4

Steps:

4 * 2 = 8

8 / 8 = 1

3 + 1 = 4

5. Assignment Operators

Assignment operators update variables by combining assignment with an arithmetic operation.

Base operator: = (simple assignment). Others:

+= addition assignment

-= subtraction assignment

*= multiplication assignment

/= division assignment

**= exponentiation assignment

%= modulus assignment

Example sequence:

let x = 2;

x += 2; // x = x + 2 → 4

x -= 2; // x = x - 2 → 2

x *= 6; // x = x * 6 → 12

x /= 3; // x = x / 3 → 4

x **= 2; // x = x ** 2 → 16

x %= 3; // x = x % 3 → 1

console.log(x); // 1

Each line both updates x and uses its old value in the computation.

6. Comparison Operators

Comparison operators return booleans: true or false.

6.1. Equality: == vs ===

let x = 5;
let y = "5";
console.log(x == y);   // true
console.log(x === y);  // false

== (loose equality) compares after coercion: "5" is coerced to 5.

=== (strict equality) compares value and type: number 5 vs string "5" → not equal.

Best practice for teaching: always prefer === and !==.

6.2. Inequality: != vs !==

let x = 5;
let y = "5";
console.log(x != y);   // false
console.log(x !== y);  // true

!= is loose inequality (inverse of ==).

!== is strict inequality (inverse of ===).

6.3. Relational operators: >, <, >=, <=

Example:

let x = 5;
let y = 6;
console.log(y > x);   // true
console.log(x > y);   // false
console.log(y > y);   // false
console.log(y >= y);  // true
console.log(y < x);   // false
console.log(x < y);   // true
console.log(y < y);   // false
console.log(y <= y);  // true

These follow standard mathematical meanings.

7. Logical Operators

Logical operators combine or negate boolean conditions.

&& – logical AND

|| – logical OR

! – logical NOT

Let:

let x = 1;
let y = 2;
let z = 3;

7.1. Logical AND (&&)

A && B is true only if both A and B are true.

console.log(x < y && y < z); // true  (1 < 2 and 2 < 3)
console.log(x > y && y < z); // false (x > y is false)

7.2. Logical OR (||)

A || B is true if at least one of A or B is true.

console.log(x > y || y < z); // true  (y < z is true)
console.log(x > y || y > z); // false (both conditions false)

7.3. Logical NOT (!)

!A negates the boolean value of A.

let flag = false;
console.log(!flag);  // true

Negating an expression:

let x = 1;
let y = 2;
console.log(!(x < y)); // x < y is true, !true → false

ASCII truth-table snapshot:

text

A B A && B A || B

true true true true

true false false true

false true false true

false false false false

8. Small Integrated Example

Use this section in class to tie everything together.

// 1. Declare and initialize variables
let miles = 130;
const MILES_TO_KM = 1.60934;
// 2. Calculate kilometers using arithmetic and assignment
let km = miles * MILES_TO_KM;
// 3. Build a message using template literals
let message = `The distance of ${km} kms is equal to ${miles} miles`;
// 4. Decide if distance is "long" using comparison and logical operators
let isLongTrip = km > 200 && km < 500;
// 5. Log results
console.log(message);
console.log("Is this a long trip?", isLongTrip);

Line-by-line connections to chapter content:

Uses let and const for variables.

Uses number primitives and arithmetic operators *, >, <, &&.

Builds a string via template literals and interpolation.

Produces a boolean classification with comparison + logical operators.