Topic 17 of 26 · UI Designer

Topic 2 : JavaScript Basics

Lesson TL;DRTopic 2: JavaScript Basics 📖 6 min read · 🎯 beginner · 🧭 Prerequisites: tagsintroductiontotables, cssproperties Why this matters Here's the thing — HTML gives your page structure, CSS makes it look...
6 min read·beginner·javascript · variables · functions · control-flow

Topic 2: JavaScript Basics

📖 6 min read · 🎯 beginner · 🧭 Prerequisites: tags-introduction-to-tables, css-properties

Why this matters

Here's the thing — HTML gives your page structure, CSS makes it look good, but neither one can do anything. Click a button? Nothing happens. Fill out a form? It just sits there. That's where JavaScript comes in. It's the language that makes your page respond, react, and come alive. In this lesson, we're starting from the very beginning — variables, operators, functions — the building blocks you'll use in every project from here on out.

What You'll Learn

  • Declare variables with var, let, and const and distinguish JavaScript's core data types
  • Apply arithmetic, assignment, comparison, and logical operators to manipulate values
  • Control program flow using conditional statements (if/else/switch) and loops (for, while, do...while)
  • Define reusable logic with function declarations, function expressions, and arrow functions
  • Work with arrays and objects to organize and retrieve collections of data

The Analogy

Think of a JavaScript program as the operations manual for a busy city hall. The variables are labeled filing cabinets — each one holds a piece of information (a name, a number, a list). The operators are the clerks who compare, combine, and calculate values from those cabinets. The control structures are the routing rules: "If the applicant is under 18, send them to window A; otherwise, window B." And the functions are the trained staff members — you describe a job once, give the staff member a name, and call on them whenever that job needs doing. Objects and arrays are the filing rooms themselves: organized collections the whole office can reference.

Chapter 1: Introduction to JavaScript

JavaScript is a high-level, interpreted programming language that is widely used to create interactive and dynamic web pages. It is an essential part of web development, alongside HTML and CSS. Unlike HTML (structure) and CSS (presentation), JavaScript adds behavior — responding to clicks, validating forms, fetching data, and updating the page without a reload.

Key characteristics:

  • Interpreted — runs directly in the browser without a separate compilation step
  • Dynamically typed — variable types are determined at runtime
  • Event-driven — code can react to user actions, timers, and network responses
  • Multi-paradigm — supports procedural, object-oriented, and functional styles

Chapter 2: Variables and Data Types

Variables are named containers for storing data. JavaScript gives you three keywords to declare them.

Declaring Variables

var name = "Alice";   // function-scoped; avoid in modern code
let age = 25;         // block-scoped; use when the value will change
const city = "Vizag"; // block-scoped; use when the value is fixed

Prefer const by default; reach for let when you know the value will be reassigned; avoid var in modern JavaScript.

Data Types

JavaScript supports several built-in data types:

  • String — text, wrapped in single, double, or backtick quotes
  • Number — integers and floating-point values alike
  • Boolean — exactly true or false
  • Array — an ordered list of values stored in a single variable
  • Object — a collection of key-value pairs for representing structured entities
let name = "Alice";                                    // String
let age = 25;                                          // Number
let isStudent = true;                                  // Boolean
let colors = ["red", "green", "blue"];                 // Array
let person = { name: "Alice", age: 25, city: "Vizag" }; // Object

Chapter 3: Operators

Operators are symbols that tell JavaScript to perform a specific operation on one or more values.

Arithmetic Operators

OperatorMeaning
+Addition
-Subtraction
*Multiplication
/Division
%Modulus (remainder)
let a = 10;
let b = 5;
let sum        = a + b;  // 15
let difference = a - b;  // 5
let product    = a * b;  // 50
let quotient   = a / b;  // 2
let remainder  = a % b;  // 0

Assignment Operators

OperatorMeaning
=Assignment
+=Addition assignment
-=Subtraction assignment
*=Multiplication assignment
/=Division assignment
let x = 10;
x += 5;  // x = x + 5  → 15
x -= 3;  // x = x - 3  → 12
x *= 2;  // x = x * 2  → 24
x /= 4;  // x = x / 4  → 6

Comparison Operators

OperatorMeaning
==Equal to (loose)
===Strict equal to
!=Not equal to (loose)
!==Strict not equal to
>Greater than
<Less than
>=Greater than or equal to
<=Less than or equal to
let a = 10;
let b = 5;
console.log(a == b);   // false
console.log(a != b);   // true
console.log(a > b);    // true
console.log(a < b);    // false
console.log(a >= 10);  // true
console.log(a === 10); // true
console.log(a !== 10); // false

Prefer === over == — strict equality avoids surprising type coercions like "5" == 5 evaluating to true.

Logical Operators

OperatorMeaning
&&Logical AND
||Logical OR
!Logical NOT
let isStudent = true;
let isAdult   = false;
console.log(isStudent && isAdult); // false — both must be true
console.log(isStudent || isAdult); // true  — at least one is true
console.log(!isStudent);           // false — inverts the value

Chapter 4: Control Structures

Control structures determine which code runs and how many times, based on conditions and loops.

Conditional Statements

  • if — executes a block when a condition is true
  • else — executes a block when the if condition is false
  • else if — tests an additional condition when earlier ones are false
  • switch — selects one of many code blocks to execute based on a value
let age = 25;
if (age < 18) {
    console.log("You are a minor.");
} else if (age >= 18 && age < 65) {
    console.log("You are an adult.");
} else {
    console.log("You are a senior.");
}

let day = 3;
switch (day) {
    case 1:
        console.log("Monday");
        break;
    case 2:
        console.log("Tuesday");
        break;
    case 3:
        console.log("Wednesday");
        break;
    default:
        console.log("Invalid day");
}

Looping Statements

  • for — repeats a block a set number of times
  • while — repeats a block while a condition remains true
  • do...while — like while, but always runs at least once before checking the condition
// for loop
for (let i = 0; i < 5; i++) {
    console.log("Number: " + i);
}

// while loop
let i = 0;
while (i < 5) {
    console.log("Number: " + i);
    i++;
}

// do...while loop
let j = 0;
do {
    console.log("Number: " + j);
    j++;
} while (j < 5);

All three loops above print Number: 0 through Number: 4. The do...while distinction matters when you need the body to execute before the condition is ever evaluated.

flowchart TD
    A([Start]) --> B{Condition true?}
    B -- Yes --> C[Execute block]
    C --> B
    B -- No --> D([End])

Chapter 5: Functions

Functions are named, reusable blocks of code that perform a specific task and are executed when called (invoked).

Function Declaration

Hoisted to the top of their scope — callable before the line where they are written.

function greet(name) {
    return "Hello, " + name + "!";
}
console.log(greet("Alice")); // Output: Hello, Alice!

Function Expression

Assigned to a variable; not hoisted — must be defined before use.

const greet = function(name) {
    return "Hello, " + name + "!";
};
console.log(greet("Bob")); // Output: Hello, Bob!

Arrow Functions

Arrow functions provide a shorter syntax for writing function expressions. They are especially common in modern JavaScript and React.

const greet = (name) => {
    return "Hello, " + name + "!";
};
console.log(greet("Charlie")); // Output: Hello, Charlie!

For single-expression bodies, the braces and return keyword can be omitted entirely:

const greet = (name) => "Hello, " + name + "!";
console.log(greet("Charlie")); // Output: Hello, Charlie!

Chapter 6: Objects and Arrays

Objects and arrays are the primary ways to organize collections of related data in JavaScript.

Arrays

Arrays store ordered lists of values, accessed by zero-based index.

let colors = ["red", "green", "blue"];
console.log(colors[0]);    // Output: red

colors.push("yellow");     // Add an element to the end
console.log(colors.length); // Output: 4

colors.pop();              // Remove the last element
console.log(colors.length); // Output: 3

Key array methods:

  • push(value) — adds to the end
  • pop() — removes from the end
  • .length — returns the number of elements
  • Index access via array[index] — zero-based

Objects

Objects store keyed collections of data. Each key-value pair is called a property; functions stored as properties are called methods.

let person = {
    name: "Alice",
    age: 25,
    city: "Vizag",
    greet: function() {
        console.log("Hello, my name is " + this.name);
    }
};

console.log(person.name); // Output: Alice
person.age = 26;
console.log(person.age);  // Output: 26
person.greet();            // Output: Hello, my name is Alice

Access object properties with dot notation (person.name) or bracket notation (person["name"]). Use bracket notation when the key is stored in a variable or contains special characters.

🧪 Try It Yourself

Task: Build a small age-classifier function that takes a person's name and age, and prints a personalized message using an if/else if/else chain.

Success criterion: Running the code should print three different messages for three different test ages — one for a minor, one for an adult, and one for a senior.

function classifyAge(name, age) {
    if (age < 18) {
        console.log(name + " is a minor.");
    } else if (age >= 18 && age < 65) {
        console.log(name + " is an adult.");
    } else {
        console.log(name + " is a senior.");
    }
}

classifyAge("Alice", 12);  // Alice is a minor.
classifyAge("Bob", 34);    // Bob is an adult.
classifyAge("Carol", 70);  // Carol is a senior.

Extend it: add the person's city to the message by passing a third argument and storing all three people in an array of objects.

🔍 Checkpoint Quiz

Q1. What is the key difference between == and === in JavaScript?

A) == works only with numbers; === works with all types
B) === checks value AND type; == checks value only and coerces types
C) They are identical — === is just an older alias
D) === is used inside switch statements; == is used in if statements


Q2. What does the following code print to the console?

let x = 10;
x += 5;
x *= 2;
console.log(x);

A) 20
B) 25
C) 30
D) 15


Q3. Given this snippet, what is printed on the third iteration of the loop?

for (let i = 0; i < 5; i++) {
    console.log("Number: " + i);
}

A) Number: 2
B) Number: 3
C) Number: 4
D) Number: 5


Q4. You are building a shopping cart. How would you store a list of product names and then add a new product to the end of the list?

A) Use an object and add a new key with object.push("product")
B) Use an array and call .push("product") on it
C) Use a const string and concatenate with +
D) Use a switch statement to select the product

A1. B — === checks both value and type without coercion, so "5" === 5 is false. == coerces types first, making "5" == 5 evaluate to true, which leads to subtle bugs.

A2. C — x starts at 10, then x += 5 makes it 15, then x *= 2 makes it 30.

A3. A — The loop variable i starts at 0. The third iteration runs when i is 2 (0, 1, then 2), printing Number: 2.

A4. B — Arrays are the right data structure for ordered lists. The push() method appends a new element to the end of an existing array.

🪞 Recap

  • JavaScript variables are declared with const (fixed), let (reassignable), or var (legacy); the language supports strings, numbers, booleans, arrays, and objects as core data types.
  • Arithmetic, assignment, comparison, and logical operators let you compute values, update variables, and evaluate conditions.
  • if/else if/else and switch choose which code to run; for, while, and do...while repeat code based on a condition.
  • Functions — declared, expressed, or arrow-style — encapsulate reusable logic and are invoked by name.
  • Arrays hold ordered lists accessed by index; objects hold named properties accessed by dot or bracket notation.

📚 Further Reading

Like this topic? It’s one of 26 in UI Designer.

Block your seat for ₹2,500 and join the next cohort.