Make your first programs: variables, data types, strings, numbers, decisions, loops and functions.
Every example opens in a live browser preview. Click ✎ Edit on any preview, or press L, to open the Code Lab.
<script> at the end of <body>, or in the head with defer. Then the HTML exists before JS tries to use it.| Method | Who sees it | Use for |
|---|---|---|
console.log() | Developer (Console) | Testing, debugging |
alert() | User, as a popup | Rare warnings |
| Change page text | User, on the page | Real apps |
2 + 2 and press Enteralert("Hi") and press Enterconsole.log output without opening DevTools.| Rule | Example |
|---|---|
| A statement is one instruction | console.log("Hi"); |
| Semicolon ends it (optional but recommended) | let x = 5; |
| Single-line comment | // this is ignored |
| Multi-line comment | /* ... */ |
| Case-sensitive! | console works, Console fails |
| Text goes in quotes | "Ranchi" or 'Ranchi' |
| Error | Usual cause |
|---|---|
ReferenceError: x is not defined | Spelling mistake, or variable not created |
SyntaxError: Unexpected token | Missing bracket, quote or comma |
TypeError: ... is not a function | Using something the wrong way |
console.log(5 * 8);. Misspell getElementById on purpose and read the red error in the console.<p id="welcome"><script> at the end of bodyconsole.log lines350 * 2Console should be lowercasegetElementByID has a wrong capital letter.style.colortextContent, not innerHTMLonclick="showDate()"showDate (you will learn functions fully in Module 6)new Date().toLocaleString("en-IN") into the paragraphModule 2: Variables, Data Types & Operators – store and calculate values.
Q1. Which one shows a message ONLY to the developer?
Q2. Where is the safest place for a <script> tag?
Q3. Is Console.log("Hi") correct?
letconstvar| Name | OK? | Why |
|---|---|---|
studentName | ✔ | camelCase: best style |
total_marks | ✔ | allowed, less common in JS |
$price, _id | ✔ | $ and _ are allowed |
2ndPlace | ✘ | cannot start with a number |
my name | ✘ | no spaces |
let, class | ✘ | reserved keywords |
x, a1 | ⚠ | allowed but meaningless |
mobileNumber, isLoggedIn, cartTotal.= means store the value on the right into the box on the left. To compare, use ===.| Type | Example | Real use |
|---|---|---|
| string | "Ranchi" | names, messages |
| number | 42, 3.14 | prices, marks |
| boolean | true | logged in? paid? |
| undefined / null | – | no value yet / empty |
| Operator | Meaning | Example | Result |
|---|---|---|---|
+ | add | 120 + 30 | 150 |
- | subtract | 500 - 120 | 380 |
* | multiply | 80 * 3 | 240 |
/ | divide | 100 / 4 | 25 |
% | remainder | 17 % 5 | 2 |
** | power | 2 ** 3 | 8 |
10 + 5 * 2 is 20 (multiply first). Use brackets to be clear: (10 + 5) * 2 is 30.n % 2 === 0. Every 3rd item: i % 3 === 0.*=, /=, -- work the same way.| Operator | Means |
|---|---|
> < >= <= | greater / less (or equal) |
=== | strictly equal (use this) |
!== | strictly not equal |
==, != | loose: avoid, causes surprises |
true or false. In Module 4 you will use them to make decisions.<input> is a string, even "500". Convert with Number() before doing maths.Number(...) around one input and click Calculate – what goes wrong? Add a 5% GST line. Add a "Thekua (Rs. 10)" input.const for prices and rateslet variablesMath.round()busRoute with no valuetypeofconst where values never change+= (grace marks)celsius = 32 (a hot Ranchi afternoon)F = C * 9 / 5 + 32let balance = 1000-=+=++>= 500Number()Module 3: Strings, Numbers & Math – format text, round prices and make random numbers.
Q1. Which value can be changed later?
Q2. What is "10" + 5?
Q3. What is 17 % 5?
"...", '...' or backticks. Escape a quote with a backslash: "Say \"hi\"". Methods like toUpperCase() give a new string; the original never changes.| Method | Real use |
|---|---|
trim() | clean search / login input |
toLowerCase() | case-insensitive search |
includes() | search: does it contain? |
slice() | first 6 letters, last 4 digits |
split() | break into words/parts |
padStart() | roll no. 007, time 09:05 |
trim() removes accidental spacestoLowerCase() on both sides so "FALLS" matches "Falls"includes() checks if the text appears anywherefalls, NET, park. (The loop and functions used here are taught in Modules 5 and 6.)toFixed(2) to display money.| Method | Example | Result |
|---|---|---|
Math.round() | Math.round(4.5) | 5 |
Math.floor() | Math.floor(4.9) | 4 (down) |
Math.ceil() | Math.ceil(4.1) | 5 (up) |
Math.max() | Math.max(45, 92, 78) | 92 |
Math.min() | Math.min(45, 92, 78) | 45 |
Math.abs() | Math.abs(-7) | 7 |
Math.sqrt() | Math.sqrt(144) | 12 |
Math.PI | 3.14159... |
Math.ceil(47 / 10) = 5 pages.slice(0, 3). Add @example.com to make an email. Capitalise the first letter for a display name.toFixed(2)replaceAll(" ", "")slice(-4) and padStarttoLocaleString("en-IN", {style: "currency", currency: "INR"})slice to split into two halvesMath.max and Math.mintoFixed(1)Module 4: Decisions – if, else, switch and logical operators.
Q1. What is "Ranchi"[0]?
Q2. Which makes 1 to 6?
Q3. Show 249 as "249.00":
( ), code in { }. The else part is optional.marks >= 33 first, everyone with 72 or 95 gets "C"!| Operator | Meaning | True when |
|---|---|---|
&& | AND | BOTH sides are true |
|| | OR | AT LEAST ONE side is true |
! | NOT | flips true ↔ false |
if (username) instead of if (username !== ""). An empty input box is falsy.case using ===breakdefault runs when nothing matchestrim() and a coloured message&&light = "red"switch decides the next lightnew Date().getHours()const hour = 21;.Module 5: Loops – repeat tasks automatically: tables, lists, games.
Q1. Which value is FALSY?
Q2. true && false is:
Q3. What happens if you forget break in a switch case?
let i = 1 runs once, before the first lap.i <= 5 is tested before every lap. false = stop.{ } runs once per lap.i++ runs after every lap, then back to Check.i <= word.length goes one step too far (index 2 does not exist). For positions use i < length.| Loop | Use when |
|---|---|
for | You know how many times (10 rows, each item) |
while | You do NOT know how many times (until target, until correct guess) |
do...while | It must run at least once (show menu, then ask again) |
for...of | Go through each item of a list/string (next slides) |
| Loop | Gives you |
|---|---|
for (let i = 0; ...) | the index number |
for (const x of list) | each value directly |
%). Add a second loop to print tables 2 to 5 at once.<ul> with innerHTMLsplit(",")line to build each rowincludes to mark booked seatsModule 6: Functions – reusable blocks of code (the most important idea in JS).
Q1. How many times does for (let i = 0; i < 3; i++) run?
Q2. Which keyword skips to the next lap?
Q3. Best loop when you do NOT know how many times?
sendOTP() is easier to read than 20 lines.| Word | Meaning |
|---|---|
| Parameter | The variable in the definition: name |
| Argument | The real value you pass: "Riya" |
| Call | Writing the name with () runs it |
greet without () | Just refers to the function, does not run it |
<button onclick="greet('Riya')"> calls the function when clicked. You have done this since Module 1!undefined, or the default if one is givenisSomething or hasSomething| Style | When you see it |
|---|---|
function name() {} | Normal named functions |
const f = function () {} | Older code, callbacks |
const f = () => {} | Modern code, React, array methods (Module 7) |
return optional. No parameters: () => ...addGST(amount) and use it in show(). Give percent a default of 10. Rewrite applyDiscount as an arrow function.applyDiscount(price, percent) returns the reduced priceaddGST(price, rate = 18) returns price with GSTformatINR(amount) returns "Rs. 1,180.00"calcEMI(principal, yearlyRate, months)**)getAge(birthYear) using the current year from DatecanVote(age) returns true/falsemessage(name, birthYear) returns a full sentencecalcBMI(kg, cm) returns kg / (m x m), 1 decimalbmiCategory(bmi) returns Underweight (<18.5) / Normal (<25) / Overweight (<30) / Obesereturn inside an if ends the function early. That is why no else is needed in bmiCategory.isEmpty(text)isValidMobile(num): 10 digits, starts 6-9 (use a loop or regex later)isValidEmail(email): contains "@" and "." after itisStrongPassword(p): 8+ chars, has a numbervalidateUser(user) returns a list of error messagesPart 2: Arrays, Objects and the DOM – control real web pages!
Q1. What does a function return if there is no return statement?
Q2. const sq = n => n * n; then sq(4) is:
Q3. A variable declared with let inside a function can be used:
You have finished Part 1 of the Complete JavaScript Course.
Keep all your practice files in D:\js-practice. You will reuse them in the capstone apps.