Topic 2: JavaScript Basics
📖 15 min read · 🎯 beginner · 🧭 Prerequisites: css-properties, insert-select-update-delete-queries
Why this matters
Up until now, you've built pages that just sit there — HTML gives them structure, CSS makes them look good, but nothing moves, nothing responds. Click a button? Nothing happens. Type something? Nothing changes. That's the gap JavaScript fills. It's the part of web development that makes things actually do something. In this lesson, we'll start with the fundamentals — variables, operators, and functions — the three building blocks you'll use in every single JavaScript program you ever write. Get these right, and the rest of the language starts to make sense.
What You'll Learn
- Declare variables with
var,let, andconstand understand JavaScript's core data types - Use arithmetic, assignment, comparison, and logical operators to manipulate values
- Control program flow with
if/else,switch,for,while, anddo...while - Define and invoke functions using declarations, expressions, and arrow syntax
- Work with arrays and objects to store and access collections of data
The Analogy
Think of a JavaScript program as a recipe card. The variables are your labeled ingredient bowls — each one holds a specific thing (flour, sugar, eggs). The operators are the kitchen actions — measure, add, subtract, multiply portions. The control structures are the conditional steps — if the dough is too sticky, add more flour; while the oven isn't hot, wait; for each guest, plate one slice. And the functions are named sub-recipes you can call on demand — "make frosting" is written once and referenced whenever you need it. Put them all together and you have a complete, repeatable program, just like a complete, repeatable dish.
Chapter 1: What Is 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, working alongside HTML (structure) and CSS (presentation) to deliver rich user experiences directly in the browser — no compilation step required.
Every modern browser includes a JavaScript engine that reads and executes your code line by line, which makes it uniquely fast to iterate on: write, save, refresh, observe.
Chapter 2: Variables and Data Types
Variables are named containers that hold data. JavaScript gives you three keywords for declaring them.
Declaring Variables
var name = "Alice"; // function-scoped, hoisted — older style
let age = 25; // block-scoped, reassignable — preferred for mutable values
const city = "Vizag"; // block-scoped, not reassignable — preferred for constants
Data Types
JavaScript supports several built-in data types:
| Type | Description | Example |
|---|---|---|
| String | Text, wrapped in quotes | "Alice" |
| Number | Integer or floating-point | 25, 3.14 |
| Boolean | True or false | true, false |
| Array | Ordered list of values | ["red", "green", "blue"] |
| Object | Keyed collection of data | { name: "Alice", age: 25 } |
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 perform operations on variables and values.
Arithmetic Operators
| Operator | Meaning | Example |
|---|---|---|
+ | Addition | a + b |
- | Subtraction | a - b |
* | Multiplication | a * b |
/ | Division | a / b |
% | Modulus (remainder) | a % b |
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
| Operator | Meaning |
|---|---|
= | 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
| Operator | Meaning |
|---|---|
== | Equal to (loose) |
=== | Strict equal to (value + type) |
!= | Not equal to |
!== | 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
Logical Operators
| Operator | Meaning |
|---|---|
&& | 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 — flips the value
Chapter 4: Control Structures
Control structures determine which code runs and how many times.
Conditional Statements
if— runs a block when a condition istrueelse— runs a block when the condition isfalseelse if— chains an additional conditionswitch— selects one of many labeled blocks to execute
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— loops a set number of timeswhile— loops as long as a condition istruedo...while— likewhile, but always executes at least once
// 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);
flowchart TD
A([Start]) --> B{Condition true?}
B -- Yes --> C[Execute block]
C --> D[Update counter]
D --> B
B -- No --> E([End loop])
Chapter 5: Functions
Functions are named, reusable blocks of code designed to perform a particular task. They run only when called (invoked).
Function Declaration
function greet(name) {
return "Hello, " + name + "!";
}
console.log(greet("Alice")); // Output: Hello, Alice!
Function Expression
A function stored inside a variable. The variable name becomes the callable reference.
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.
const greet = (name) => {
return "Hello, " + name + "!";
};
console.log(greet("Charlie")); // Output: Hello, Charlie!
All three forms above produce the same result — choice is mostly stylistic, with arrow functions being the modern default in most codebases.
Chapter 6: Objects and Arrays
Arrays
Arrays store multiple values in a single ordered variable. Elements are 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 used above:
.push(value)— appends a value to the end.pop()— removes and returns the last value.length— returns the current number of elements
Objects
Objects store keyed collections of data — each key maps to a value, including other functions (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
this inside a method refers to the object that owns the method — here, person.
🧪 Try It Yourself
Task: Build a small grade reporter that takes a numeric score and prints a letter grade.
Starter snippet:
function getGrade(score) {
if (score >= 90) {
return "A";
} else if (score >= 80) {
return "B";
} else if (score >= 70) {
return "C";
} else if (score >= 60) {
return "D";
} else {
return "F";
}
}
// Test it
let scores = [95, 82, 71, 58, 100];
for (let i = 0; i < scores.length; i++) {
console.log("Score: " + scores[i] + " → Grade: " + getGrade(scores[i]));
}
Success criterion: Open your browser console (F12 → Console), paste the snippet, and press Enter. You should see five lines printed, each matching the expected letter grade for that score. Try changing a score value and confirm the grade updates accordingly.
🔍 Checkpoint Quiz
Q1. What is the difference between == and === in JavaScript?
A) There is no difference — they are interchangeable
B) == checks value only; === checks both value and type
C) === checks value only; == checks both value and type
D) === is used only for strings
Q2. What does the following code print to the console?
let x = 10;
x += 5;
x -= 3;
console.log(x);
A) 10
B) 12
C) 15
D) 8
Q3. Given the following object, what does person.greet() output?
let person = {
name: "Bob",
greet: function() {
console.log("Hello, my name is " + this.name);
}
};
person.greet();
A) Hello, my name is undefined
B) Hello, my name is person
C) Hello, my name is Bob
D) A runtime error is thrown
Q4. You need a variable that holds a list of five city names and will be changed by adding new cities later. Which declaration is most appropriate, and which method would you use to add a city?
A1. B — == performs loose equality (coerces types before comparing, so "5" == 5 is true), while === requires both value and type to match ("5" === 5 is false).
A2. B — Starting at 10, += 5 gives 15, then -= 3 gives 12.
A3. C — this.name inside the method refers to person.name, which is "Bob", producing Hello, my name is Bob.
A4. Use let cities = ["Delhi", "Mumbai", "Chennai", "Kolkata", "Bangalore"]; — let because the array will be mutated. Use cities.push("Hyderabad") to add a new city to the end.
🪞 Recap
- JavaScript variables are declared with
var,let, orconst, and can hold strings, numbers, booleans, arrays, or objects. - Arithmetic, assignment, comparison, and logical operators let you compute, update, and evaluate values.
if/else if/elseandswitchcontrol which block of code executes based on conditions.for,while, anddo...whileloops repeat code blocks a controlled number of times.- Functions — declared, expressed, or arrow-style — are reusable named blocks that accept parameters and return values.
- Arrays and objects are JavaScript's primary structures for grouping related data, with arrays using numeric indexes and objects using named keys.
📚 Further Reading
- MDN Web Docs — JavaScript Guide — the definitive reference for every concept covered here
- javascript.info — The Modern JavaScript Tutorial — free, in-depth guide from basics to advanced, excellent for beginners
- Eloquent JavaScript (free online) — a deeper dive into JS fundamentals with exercises
- ⬅️ Previous: Insert, Select, Update, Delete Queries
- ➡️ Next: PHP Variables Introduction