Week 2: Mastering Variables, Data, and Operations in JS

Unlocking the power to store and manipulate information in JavaScript.

Dive into Chapter 2

Chapter 2: Fundamental Data Types and Operations

Variables: Naming, Declaring, Assigning Values.

Variables are fundamental to programming. They act as named containers for storing data values that your program can use and manipulate. Think of them as labels for information.

Declaring Variables (let, const, var)

In modern JavaScript (ES6 and later), you primarily use let and const to declare variables:

  • let: Declares variables whose value can be reassigned later. Variables declared with let are block-scoped (their scope is limited to the block {} they are defined in).
    let message = "Hello";
    message = "World"; // This is allowed
    console.log(message);
  • const: Declares variables whose value cannot be reassigned after initialization (constants). They are also block-scoped. Use const for values you don't intend to change.
    const pi = 3.14159;
    // pi = 3.14; // This would cause a TypeError!
    console.log(pi);

    Note: For objects and arrays declared with const, the variable itself cannot be reassigned, but the contents of the object or array can still be modified.

  • var (Legacy): The older way to declare variables. var variables are function-scoped or globally-scoped, not block-scoped, which can sometimes lead to unexpected behavior. It's generally recommended to use letand const instead in modern JavaScript.
    var count = 10; // Older style, function-scoped
    

Naming Variables

JavaScript variable names (identifiers) must follow these rules:

  • Can contain letters, digits, underscores (_), and dollar signs ($).
  • Must begin with a letter, underscore (_), or dollar sign ($). Cannot start with a digit.
  • Are case-sensitive (myVariable and myvariable are different).
  • Cannot be reserved keywords (like let, const, if, for, function, etc.).
  • The convention is to use camelCase for variable names (e.g., numberOfStudents, firstName).

Assigning Values

You assign a value to a variable using the assignment operator (=).

let age = 30; // Declaring and assigning in one step
const userName = "Alice";
let score;      // Declaration without assignment (value is 'undefined')
score = 100;    // Assignment later

Basic Data Types: The Building Blocks of Information.

JavaScript is dynamically typed, meaning you don't specify the data type when declaring a variable. The type is determined automatically based on the assigned value. JavaScript has several primitive data types:

  • Number: Represents both integers and floating-point numbers. There's no distinct integer type like in some other languages.
    let integerNum = 100;
    let floatNum = 99.99;
    let scientificNum = 2.5e3; // 2500
  • String: Represents textual data. Enclosed in single quotes ('...'), double quotes ("..."), or backticks (`...` - template literals).
    let name = "Bob";
    let greeting = 'Hello!';
    let message = `Welcome, ${name}!`; // Template literal
  • Boolean: Represents logical values true or false. Used extensively in conditional logic.
    let isActive = true;
    let isLoggedIn = false;
  • undefined: A variable that has been declared but not assigned a value has the value undefined. It represents the unintentional absence of a value.
    let city;
    console.log(city); // Output: undefined
  • null: Represents the intentional absence of any object value. It's often assigned explicitly to indicate "no value".
    let selectedUser = null;

    Note: typeof null strangely returns "object", which is a historical quirk.

  • Symbol (ES6+): Represents a unique identifier. Used less commonly in basic programming but important for more advanced scenarios like creating unique object properties.
    const id = Symbol('uniqueId');
  • BigInt (ES2020+): Represents integers of arbitrary precision, larger than the standard Number type can safely handle. Created by appending n to an integer literal.
    const veryLargeNumber = 1234567890123456789012345678901234567890n;

JavaScript also has the Object type, which is a non-primitive type used for more complex data structures (we'll cover objects and arrays later).

You can use the typeof operator to check the data type of a variable:

console.log(typeof 42);          // "number"
console.log(typeof "hello");     // "string"
console.log(typeof true);        // "boolean"
console.log(typeof undefined);   // "undefined"
console.log(typeof null);        // "object" (the quirk!)
console.log(typeof Symbol('id')); // "symbol"
console.log(typeof 100n);        // "bigint"
console.log(typeof {});          // "object"
console.log(typeof []);          // "object" (arrays are objects)

Arithmetic Operators: Performing Calculations.

These operators perform mathematical calculations on numbers.

Operator Name Example Result Description
+Addition5 + 38Adds operands.
-Subtraction5 - 32Subtracts right operand from left.
*Multiplication5 * 315Multiplies operands.
/Division5 / 31.666...Divides left operand by right.
%Modulo (Remainder)5 % 32Returns the remainder of a division.
**Exponentiation (ES7+)5 ** 3125Raises left operand to the power of the right.
++Incrementlet x=5; x++;x is 6Increases operand by 1 (postfix/prefix).
--Decrementlet y=5; y--;y is 4Decreases operand by 1 (postfix/prefix).

Examples:

let a = 10;
let b = 4;
console.log("a + b =", a + b);   // 14
console.log("a / b =", a / b);   // 2.5
console.log("a % b =", a % b);   // 2
console.log("a ** b =", a ** b); // 10000

let counter = 5;
counter++; // counter is now 6
console.log("Counter:", counter);

The + operator can also be used for string concatenation:

let firstName = "Jane";
let lastName = "Doe";
let fullName = firstName + " " + lastName; // "Jane Doe"
console.log(fullName);

Comparison Operators: Making Comparisons.

Comparison operators compare two values and return a boolean (true or false) result.

OperatorNameExample (x=5, y='5', z=3)ResultDescription
==Equal (Loose)x == ytrueCompares values after type coercion. (Avoid if possible)
===Strictly Equalx === yfalseCompares values AND types without coercion. (Recommended)
!=Not Equal (Loose)x != ztrueCompares values after type coercion.
!==Strictly Not Equalx !== ytrueCompares values AND types without coercion. (Recommended)
>Greater thanx > ztrueChecks if left operand is greater than right.
<Less thanx < zfalseChecks if left operand is less than right.
>=Greater than or equal tox >= ytrueChecks if left is greater than or equal to right.
<=Less than or equal tox <= zfalseChecks if left is less than or equal to right.

Important: Always prefer strict equality (===) and strict inequality (!==) over loose equality (==, !=) to avoid unexpected results due to automatic type coercion.

let p = 10;
let q = '10';
let r = 5;

console.log("p == q:", p == q);     // true (loose equality, string '10' coerced to number 10)
console.log("p === q:", p === q);   // false (strict equality, types are different)
console.log("p !== q:", p !== q);   // true (strict inequality)
console.log("p > r:", p > r);       // true

Logical Operators: Combining Boolean Expressions.

Logical operators combine or invert boolean values.

  • && (Logical AND): Returns true if both operands are true (or truthy). Otherwise returns false (or the first falsy value encountered).
    let isAdult = true;
    let hasTicket = false;
    console.log(isAdult && hasTicket); // false
  • || (Logical OR): Returns true if at least one operand is true (or truthy). Returns false (or the last falsy value) only if both are false (or falsy).
    let isWeekend = true;
    let isHoliday = false;
    console.log(isWeekend || isHoliday); // true
  • ! (Logical NOT): Inverts the boolean value of its operand. !true becomes false, and !false becomes true.
    let isRaining = false;
    console.log(!isRaining); // true

JavaScript also uses the concept of "truthy" and "falsy" values in logical operations. Falsy values include false, 0, "" (empty string), null, undefined, and NaN. All other values are considered truthy.

Operator Precedence

JavaScript operators have a specific order of precedence (similar to mathematical rules). For example, multiplication (*) happens before addition (+), and logical AND (&&) happens before logical OR (||). Use parentheses () to control the order of evaluation explicitly when needed.

let result = 10 + 5 * 2; // 20 (multiplication first)
let result2 = (10 + 5) * 2; // 30 (parentheses first)

let check = true || false && false; // true (&& has higher precedence than ||)
let check2 = (true || false) && false; // false (parentheses first)
Syllabus