BRAINBIT INFOTECH · RANCHI
COMPLETE JAVASCRIPT COURSE · PART 1 OF 4

JavaScript Foundations

Make your first programs: variables, data types, strings, numbers, decisions, loops and functions.

6 modules~18 hours30 practice examplesNeeds basic HTML

By the end of this part you can build

  • A shopping bill and GST calculator
  • A grade calculator and a login check
  • A multiplication table and a number guessing game
  • Reusable functions for EMI, discount and age

Every example opens in a live browser preview. Click ✎ Edit on any preview, or press L, to open the Code Lab.

ROADMAP FOR THIS PART

Module 1What Is JavaScript & Your First Program2.5 h
Module 2Variables, Data Types & Operators3 h
Module 3Strings, Numbers & Math3 h
Module 4Decisions: if, else, switch3 h
Module 5Loops3 h
Module 6Functions & Scope3.5 h
JavaScriptBefore we begin

How to Use This Part

Suggested teaching hours per module (Part 1)012342.5 hM13 hM23 hM33 hM43 hM53.5 hM6

Every module has

  1. 1
    A "Where is it used?" diagram of a real web page
  2. 2
    Concept slides with code + live preview + console
  3. 3
    Step-through animations: watch variables change
  4. 4
    A Live Lab: edit code, see the result instantly
  5. 5
    5 practice examples with solutions
  6. 6
    An animated recap + quiz
Controls→ next, ← back, M menu, L Code Lab, F fullscreen. Click ✎ Edit on any preview to change its code.
MODULE 1

What Is JavaScript & Your First Program

⏱ 2.5 hours5 practice examplesLive code lab

You will learn

  • What JavaScript does on a web page
  • Where JavaScript runs: browser, server, mobile
  • Adding JS with the <script> tag
  • console.log, alert and changing page text
  • Reading error messages in the Console

You will build

  • A welcome message on a coaching website
  • A bus ticket printed in the console
  • A "Show today's date" button
JSclickupdate
Module 1Real-world use

Where Is This Used in Real Websites and Apps?

LOGOButtonNavigation menuFormCards / boxes

You will find it here

  • Buttons that do something: Add to cart, Like, Play video
  • Menus that open and close on mobile
  • Forms that check your mobile number before sending
  • Live updates: cricket scores, chat messages, notifications
  • Every app you use (WhatsApp Web, Paytm, YouTube) runs JavaScript in the browser
Remember the houseHTML = walls (structure), CSS = paint (style), JavaScript = electricity (things that move and react).
Module 1Why JavaScript?

HTML Shows, CSS Styles, JavaScript ACTS

H

HTML

Puts the post, text and button on the page.
C

CSS

Makes the button round and red.
JS

JavaScript

When you click, it adds 1, updates the number and colours the button. HTML and CSS alone cannot count!
Click LikeClick the button several times. Watch the count and the Console below the page.
D:/js-practice/like.html
Console output appears here
like.htmlHTML
Module 1The big picture

JavaScript Runs Almost Everywhere

JavaScriptWeb browsersevery websiteServersNode.js back-endsMobile appsReact NativeDesktop appsVS Code, WhatsApp desktop
  • It is the only programming language that runs inside every web browser
  • With Node.js the same language runs on servers
  • Frameworks like React and React Native build web and mobile apps
  • VS Code (the editor you use) is itself built with JavaScript
Not Java!JavaScript and Java are completely different languages. The similar name was a marketing idea in 1995.
What you needOnly a browser (Chrome) and VS Code. No installation of JavaScript is required – it is already inside the browser.
Module 1Adding JavaScript

Where to Write JavaScript: the <script> Tag

index.htmlHTML
D:/js-practice/index.html
Console output appears here
<head><h1>Hello!</h1><p>...</p><script></body> Browser reads top to bottom Script runs here: the h1already exists, so JS canchange it.
RulePut <script> at the end of <body>, or in the head with defer. Then the HTML exists before JS tries to use it.
Module 1First program

Three Ways to Show Output

script.jsJS
D:/js-practice/script.js
Console output appears here
MethodWho sees itUse for
console.log()Developer (Console)Testing, debugging
alert()User, as a popupRare warnings
Change page textUser, on the pageReal apps
Module 1Tools

Meet the Console: Your JavaScript Playground

  1. 1
    Open Chrome, press F12 (or Ctrl+Shift+J)
  2. 2
    Click the Console tab
  3. 3
    Type 2 + 2 and press Enter
  4. 4
    Type alert("Hi") and press Enter
  5. 5
    Red text = an error. Read it: it tells you the problem and the line number
In this deckEvery preview has a Console panel underneath, so you can see console.log output without opening DevTools.
Elements Console Sources Network>2 + 2< 4>"Ranchi".length< 6>"Jharkhand".toUpperCase()< "JHARKHAND">hello< Uncaught ReferenceError: hello is not defined
Module 1Syntax basics

Statements, Comments and Case

consoleobject
.logmethod (action)
(
"Hello"value (a string)
)
;end of statement
RuleExample
A statement is one instructionconsole.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'
script.jsJS
D:/js-practice/script.js
Console output appears here
Module 1How JS runs

Watch JavaScript Run Line by Line

script.jsJS
Press Next step to run the program one line at a time.

Memory (variables)

(empty)

Console output

Module 1Errors

Errors Are Your Friends: Read the Red Message

script.jsJS
D:/js-practice/script.js
Console output appears here
ErrorUsual cause
ReferenceError: x is not definedSpelling mistake, or variable not created
SyntaxError: Unexpected tokenMissing bracket, quote or comma
TypeError: ... is not a functionUsing something the wrong way
ImportantWhen an error happens, JavaScript stops at that line. Everything after it does not run.
Module 1Live Lab

Live Lab: Your First JavaScript

first.html – edit me!
Live preview
TryChange the message text. Add console.log(5 * 8);. Misspell getElementById on purpose and read the red error in the console.
Module 1Practice Example 1 of 5

Welcome Message on a Coaching Website

BeginnerExcel Academy, Hazaribagh wants its homepage to greet visitors with a message written by JavaScript.

Your tasks

  1. Create a page with an empty <p id="welcome">
  2. Add a <script> at the end of body
  3. Put the text "Welcome to Excel Academy, Hazaribagh!" into the paragraph
  4. Print "Welcome message shown" in the console
  5. Style the paragraph with CSS (big, coloured)
Where this is used: Welcome banners, greetings with the user's name after login.
welcome.htmlHTML
Module 1Practice Example 2 of 5

Print a Bus Ticket in the Console

BeginnerA bus booking app first prints the ticket in the console to test it before showing it to users.

Your tasks

  1. Use 6 console.log lines
  2. Print a line of dashes at the top and bottom
  3. Print From: Ranchi, To: Jamshedpur
  4. Print Seat: 14 and Fare: 350
  5. Print the total of 2 tickets using maths: 350 * 2
Where this is used: Testing app features before building the screen.
ticket.jsJS
Module 1Practice Example 3 of 5

Find and Fix the Errors

BeginnerRahul's script does not work. Click Try it in the Lab to load it. Read the console errors and fix the 4 mistakes.

Your tasks

  1. Console should be lowercase
  2. A string is missing its closing quote
  3. getElementByID has a wrong capital letter
  4. The script is placed before the element it changes
  5. Check: the page shows "Fixed by Rahul!" and no red errors
HintFix one error at a time, from the top. Each fix may reveal the next error.
Where this is used: Debugging is half of a developer's job.
fix-me.htmlHTML
Module 1Practice Example 4 of 5

Change Page Text with JavaScript

BeginnerA school result page must show the student name and result filled in by JavaScript (later this will come from a server).

Your tasks

  1. HTML with three empty spans: name, class, result
  2. JavaScript fills: Priya Kumari, Class 10, PASS
  3. Make the result text green with .style.color
  4. Log "Result page ready"
  5. Use textContent, not innerHTML
Where this is used: Profile pages, dashboards and results filled with data.
result.htmlHTML
Module 1Practice Example 5 of 5

A "Show Today's Date" Button

BeginnerThe Ranchi Railway Station kiosk page has a button that shows today's date and time.

Your tasks

  1. A button with onclick="showDate()"
  2. An empty paragraph with id "today"
  3. In the script, write a function showDate (you will learn functions fully in Module 6)
  4. Inside it, put new Date().toLocaleString("en-IN") into the paragraph
  5. Also log the date to the console
HintClick the button in the preview. The date changes every time you click.
Where this is used: Clocks, "last updated" labels, receipts and booking screens.
date.htmlHTML
Module 1Module complete

Recap: What You Completed in Module 1

  • ✓JS makes pages react: click, count, update
  • ✓JS runs in browsers, servers (Node.js), mobile and desktop apps
  • ✓<script> at the end of body (or defer)
  • ✓console.log, alert and changing page text
  • ✓Using the DevTools Console
  • ✓Statements, comments, case-sensitivity
  • ✓JS runs top to bottom and stops at an error
100%Module 1 done

Coming next

Module 2: Variables, Data Types & Operators – store and calculate values.

Quick quiz – click an answer

Q1. Which one shows a message ONLY to the developer?

console.log writes to the Console in DevTools.

Q2. Where is the safest place for a <script> tag?

Then all the HTML above it already exists.

Q3. Is Console.log("Hi") correct?

It must be console with a small c.
MODULE 2

Variables, Data Types & Operators

⏱ 3 hours5 practice examplesLive code lab

You will learn

  • Variables as labelled boxes: let and const (and old var)
  • Naming rules and camelCase
  • Data types: string, number, boolean, undefined, null
  • Maths, assignment and comparison operators
  • Type conversion: why "5" + 2 = "52"

You will build

  • A food-order bill with GST
  • A temperature converter
  • An EMI / interest calculator page
name"Riya"age14isStudenttrue
Module 2Real-world use

Where Is This Used in Real Websites and Apps?

LOGOCards / boxesFormButtonHeader

You will find it here

  • Cart total on Flipkart / Swiggy: price x quantity + delivery
  • Form values you type: name, mobile, age
  • Game scores, likes counts, wallet balance
  • Settings: dark mode on/off (true / false)
  • Every app stores data in variables while it runs
Module 2Variables

Variables: Labelled Boxes for Your Data

city"Ranchi"let city = "Ranchi";price120let price = 120;GST0.18const GST = 0.18;A variable = a labelled box in memory that holds a value
L

let

A box whose value can change: score, cart count, current city.
C

const

A box that cannot be re-assigned: GST rate, app name, PI. Use it by default.
V

var

The old way (before 2015). You will see it in old code. Avoid it in new code.
Module 2Variables

let vs const: Step Through It

script.jsJS
Press Next step to run the program one line at a time.

Memory (variables)

(empty)

Console output

Module 2Naming

Naming Variables: Rules and Good Habits

NameOK?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
letkeyword
totalPricename (camelCase)
=assignment: "store into"
450value
;
camelCaseFirst word small, each next word starts with a capital: mobileNumber, isLoggedIn, cartTotal.
= is not "equals"In JS, = means store the value on the right into the box on the left. To compare, use ===.
Module 2Data types

Data Types: What Kind of Value Is It?

script.jsJS
D:/js-practice/script.js
Console output appears here
TypeExampleReal use
string"Ranchi"names, messages
number42, 3.14prices, marks
booleantruelogged in? paid?
undefined / null–no value yet / empty
Module 2Operators

Maths Operators: Your App Is a Calculator

OperatorMeaningExampleResult
+add120 + 30150
-subtract500 - 120380
*multiply80 * 3240
/divide100 / 425
%remainder17 % 52
**power2 ** 38
BODMAS works10 + 5 * 2 is 20 (multiply first). Use brackets to be clear: (10 + 5) * 2 is 30.
% in real appsEven or odd: n % 2 === 0. Every 3rd item: i % 3 === 0.
D:/js-practice/bill.js
Console output appears here
bill.jsJS
Module 2Operators

Shortcuts: +=, -=, ++ and -- (Wallet Example)

script.jsJS
Press Next step to run the program one line at a time.

Memory (variables)

(empty)

Console output

Also*=, /=, -- work the same way.
Module 2Comparison

Comparing Values: == vs ===

script.jsJS
D:/js-practice/script.js
Console output appears here
OperatorMeans
> < >= <=greater / less (or equal)
===strictly equal (use this)
!==strictly not equal
==, !=loose: avoid, causes surprises
Result is a booleanEvery comparison gives true or false. In Module 4 you will use them to make decisions.
Module 2Type conversion

The "5" + 2 = "52" Trap (and How to Fix It)

"5" + 2 = "52" + with a string JOINS text instead of adding! Number("5") + 2 =7
script.jsJS
D:/js-practice/script.js
Console output appears here
Very common bugAnything you read from an <input> is a string, even "500". Convert with Number() before doing maths.
Module 2Live Lab

Live Lab: A Quick Bill Calculator

bill.html – edit me!
Live preview
TryRemove Number(...) around one input and click Calculate – what goes wrong? Add a 5% GST line. Add a "Thekua (Rs. 10)" input.
Module 2Practice Example 1 of 5

Food Order Bill with GST

BeginnerA Ranchi restaurant app must calculate the bill: 2 thalis at Rs. 180, 1 lassi at Rs. 60, 5% GST and Rs. 30 delivery.

Your tasks

  1. Use const for prices and rates
  2. Calculate subtotal, gst and total in let variables
  3. Print each line with console.log
  4. Round the total with Math.round()
  5. Also show the total on the page
Where this is used: Every food delivery and e-commerce checkout page.
bill.htmlHTML
Module 2Practice Example 2 of 5

Student Profile in Variables

BeginnerBefore building the school app screen, store one student's details in variables and check their types.

Your tasks

  1. Variables for name (string), rollNo (number), marks (number), isHosteller (boolean)
  2. A variable busRoute with no value
  3. Print each value with its typeof
  4. Use const where values never change
  5. Change marks once with += (grace marks)
Where this is used: Every app models users and records as variables before saving them.
profile.jsJS
Module 2Practice Example 3 of 5

Temperature Converter

BeginnerThe Jharkhand weather page shows Celsius, but tourists from abroad want Fahrenheit.

Your tasks

  1. Store celsius = 32 (a hot Ranchi afternoon)
  2. Formula: F = C * 9 / 5 + 32
  3. Store and print the result
  4. Also convert Netarhat's 12°C
  5. Show "32°C = 89.6°F" on the page
Where this is used: Weather apps, unit converters, recipe apps (grams/cups).
temp.htmlHTML
Module 2Practice Example 4 of 5

Mobile Recharge Wallet

IntermediateA Paytm-style wallet starts with Rs. 1000. Track every transaction with shortcut operators.

Your tasks

  1. Start: let balance = 1000
  2. Recharge Rs. 299: use -=
  3. Cashback 10% of 299: use +=
  4. Count transactions with ++
  5. Print balance after each step; check if balance >= 500
Where this is used: Wallets, game coins, stock counts in shops.
wallet.jsJS
Module 2Practice Example 5 of 5

Simple Interest Calculator Page

IntermediateA bank branch in Bokaro wants a web calculator: enter principal, rate and years, click Calculate.

Your tasks

  1. Three number inputs and a button
  2. Read values and convert with Number()
  3. SI = P x R x T / 100; Amount = P + SI
  4. Show both on the page
  5. Log what happens if you forget Number() (use string + number)
HintClick Calculate in the preview and compare the two console lines.
Where this is used: Bank, loan, EMI and SIP calculators on finance sites.
interest.htmlHTML
Module 2Module complete

Recap: What You Completed in Module 2

  • ✓Variables are labelled boxes in memory
  • ✓const by default, let when it changes, avoid var
  • ✓camelCase names; = means "store"
  • ✓Types: string, number, boolean, undefined, null + typeof
  • ✓Maths: + - * / % ** and BODMAS
  • ✓Shortcuts +=, -=, ++; comparisons === and !==
  • ✓Input values are strings: convert with Number()
100%Module 2 done

Coming next

Module 3: Strings, Numbers & Math – format text, round prices and make random numbers.

Quick quiz – click an answer

Q1. Which value can be changed later?

let allows re-assignment.

Q2. What is "10" + 5?

A string + number joins them as text.

Q3. What is 17 % 5?

% gives the remainder: 17 = 3 x 5 + 2.
MODULE 3

Strings, Numbers & Math

⏱ 3 hours5 practice examplesLive code lab

You will learn

  • Strings: quotes, length, index positions
  • Template literals with ${...}
  • String methods: upper/lower, trim, includes, slice, replace, split
  • Numbers: toFixed, rounding, Indian number format
  • The Math object: round, floor, ceil, max, min, random

You will build

  • A username generator
  • A price formatter (Rs. 1,25,000.00)
  • An OTP generator and a dice game
R0A1N2C3H4I53.14159Math.random()
Module 3Real-world use

Where Is This Used in Real Websites and Apps?

LOGOFormCards / boxesHeadingsButton

You will find it here

  • Search boxes: trim spaces, ignore upper/lower case
  • Prices: Rs. 1,499.00 with 2 decimals and commas
  • Messages: "Hi Riya, your order #4521 is on the way"
  • OTP codes, coupon codes and random quiz questions
  • Usernames and emails: check for @, cut parts of text
Module 3Strings

Strings Are a Row of Characters

J0H1A2R3K4H5A6N7D8Positions (index) start at 0. "JHARKHAND".length is 9, last index is 8.
script.jsJS
D:/js-practice/script.js
Console output appears here
Quotes and immutabilityUse "...", '...' or backticks. Escape a quote with a backslash: "Say \"hi\"". Methods like toUpperCase() give a new string; the original never changes.
Module 3Template literals

Template Literals: Build Messages Easily

`backtick (key left of 1)
Hi normal text
${name}insert a variable
, order #
${id}
is ready`
messages.jsJS
D:/js-practice/messages.js
Console output appears here
D:/js-practice/notification.html
Where usedEvery notification, receipt and chat message in an app is built like this from variables.
Module 3String methods

String Methods You Will Use Every Day

script.jsJS
D:/js-practice/script.js
Console output appears here
MethodReal 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
Module 3Strings in apps

Real Use: A Case-Insensitive Search Check

D:/js-practice/search.html
Console output appears here
  1. 1
    Read what the user typed
  2. 2
    trim() removes accidental spaces
  3. 3
    toLowerCase() on both sides so "FALLS" matches "Falls"
  4. 4
    includes() checks if the text appears anywhere
  5. 5
    Highlight the matching items
Type in the search boxTry falls, NET, park. (The loop and functions used here are taught in Modules 5 and 6.)
Module 3Numbers

Formatting Numbers: Decimals and Indian Commas

script.jsJS
D:/js-practice/script.js
Console output appears here
0.1 + 0.2Computers store decimals in binary, so tiny errors appear. Always use toFixed(2) to display money.
en-INIndian format groups by lakhs and crores: 1,25,000 and 1,00,00,000.
Module 3Math object

The Math Object: Rounding, Max, Min, Random

MethodExampleResult
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.PI3.14159...
Real use: pagesMath.ceil: 47 products, 10 per page → Math.ceil(47 / 10) = 5 pages.
D:/js-practice/random.html
Console output appears here
random.jsJS
Module 3Math object

How a Random Number Between 1 and 6 Is Made

random()0.73➜* 64.38➜floor()4➜+ 15random() never reaches 1, so * 6 gives 0 to 5.99. floor makes 0-5, +1 makes 1-6.Math.floor(Math.random() * (max - min + 1)) + min
🎲

Games

Dice, Ludo, card shuffles, random enemy positions.
🔒

Security

OTPs and captcha codes (real banks use stronger crypto random).
🌟

Content

Random quote of the day, quiz question order, banner ads.
Module 3Live Lab

Live Lab: A Username Maker

username.html – edit me!
Live preview
TryUse only the first 3 letters of the last name with slice(0, 3). Add @example.com to make an email. Capitalise the first letter for a display name.
Module 3Practice Example 1 of 5

Personalised Order Message

BeginnerAfter payment, a cafe app shows: "Thank you Aman! Your order #A-1042 of 3 items (Rs. 249.00) will be ready at 5:30 PM."

Your tasks

  1. Variables: customer, orderNo, items, amount, time
  2. Build the message with a template literal
  3. Show the amount with toFixed(2)
  4. Show it on the page and in the console
  5. Print the message length too
Where this is used: Order confirmations, SMS templates, email receipts.
order-msg.htmlHTML
Module 3Practice Example 2 of 5

Clean Up a Messy Name and Mobile

BeginnerUsers type data carelessly in a sign-up form: " rAhUl kumar " and "98765 43210". Clean it before saving.

Your tasks

  1. Trim spaces from the name
  2. Make it Title Case: "Rahul Kumar" (split, then fix each word)
  3. Remove spaces from the mobile number with replaceAll(" ", "")
  4. Check the mobile has 10 characters
  5. Show masked mobile: "******3210" using slice(-4) and padStart
HintArrays and loops (Modules 5 and 7) will make this work for names with any number of words.
Where this is used: Sign-up forms, CRM data cleaning, masking phone numbers for privacy.
clean.jsJS
Module 3Practice Example 3 of 5

Price Formatter for a Shop

IntermediateJharkhand Handicrafts shows prices in Indian format with the rupee symbol and a discount.

Your tasks

  1. Original price 125000 (a silk wall hanging)
  2. 15% discount; final price
  3. Format both with toLocaleString("en-IN", {style: "currency", currency: "INR"})
  4. Show the saving rounded with Math.round
  5. Display all on the page
Where this is used: Every Indian e-commerce product page.
price.htmlHTML
Module 3Practice Example 4 of 5

OTP Generator

IntermediateA login page sends a 6-digit OTP. Generate one and show when it expires.

Your tasks

  1. Make a random 6-digit number (100000 to 999999)
  2. Convert it to a string and show it with spaces: "482 913"
  3. Use slice to split into two halves
  4. Show "Valid for 5 minutes" using a template literal
  5. Generate a new OTP on button click
Where this is used: Login, payments, Aadhaar-style verifications.
otp.htmlHTML
Module 3Practice Example 5 of 5

Marks Statistics Card

IntermediateShow a class test summary: highest, lowest, average (rounded to 1 decimal) and percentage of the topper out of 50.

Your tasks

  1. Five marks: 42, 37, 48, 29, 45
  2. Use Math.max and Math.min
  3. Average = sum / 5, shown with toFixed(1)
  4. Topper percentage = max / 50 * 100
  5. Show everything in a styled card
HintIn Module 7 you will store marks in an array, so this works for 50 students, not just 5.
Where this is used: Report cards, dashboards, analytics summaries.
stats.htmlHTML
Module 3Module complete

Recap: What You Completed in Module 3

  • ✓Strings, length and index (starts at 0)
  • ✓Template literals with backticks and ${ }
  • ✓trim, toUpperCase, toLowerCase, includes, slice, replace, split, padStart
  • ✓Case-insensitive search technique
  • ✓toFixed and toLocaleString("en-IN")
  • ✓Math.round / floor / ceil / max / min
  • ✓Random numbers in a range (dice, OTP)
100%Module 3 done

Coming next

Module 4: Decisions – if, else, switch and logical operators.

Quick quiz – click an answer

Q1. What is "Ranchi"[0]?

Index starts at 0.

Q2. Which makes 1 to 6?

floor gives 0-5, +1 gives 1-6.

Q3. Show 249 as "249.00":

toFixed on a number variable (or (249).toFixed(2)).
MODULE 4

Decisions: if, else, switch

⏱ 3 hours5 practice examplesLive code lab

You will learn

  • if, else if, else: choosing a path
  • Logical operators &&, ||, !
  • Truthy and falsy values
  • The ternary operator ? :
  • switch for many fixed choices

You will build

  • A pass / fail and grade calculator
  • A login check and free-delivery rule
  • A traffic light and day-of-week app
marks >= 33?PASSFAILyesno
Module 4Real-world use

Where Is This Used in Real Websites and Apps?

LOGOFormButtonNavigation menuCards / boxes

You will find it here

  • Login: if the password is correct, open the dashboard, else show an error
  • Free delivery if the cart total is above Rs. 499
  • Show / hide buttons: show "Logout" only if logged in
  • Discounts: students get 10%, senior citizens get 15%
  • Games: if lives === 0, game over
Module 4if / else

if ... else: Two Roads

Start cartTotal>= 499 ? true false delivery = 0FREE delivery! delivery = 40Add Rs. more... continue with the rest of the program
delivery.jsJS
SyntaxCondition in ( ), code in { }. The else part is optional.
Module 4else if

else if Chains: Step Through a Grade Calculator

script.jsJS
Press Next step to run the program one line at a time.

Memory (variables)

(empty)

Console output

Order mattersCheck the biggest value first. If you check marks >= 33 first, everyone with 72 or 95 gets "C"!
Module 4Logic

Logical Operators: AND, OR, NOT

OperatorMeaningTrue when
&&ANDBOTH sides are true
||ORAT LEAST ONE side is true
!NOTflips true ↔ false
A && BA || BT TtrueT TtrueT FfalseT FtrueF TfalseF TtrueF FfalseF Ffalse
script.jsJS
D:/js-practice/script.js
Console output appears here
Module 4Truthy & falsy

Truthy and Falsy: What Counts as "Yes"?

F

The 6 falsy values

false0"" (empty)nullundefinedNaN
T

Everything else is truthy

true1, -5"0""hello"[] array{} object
Why it mattersYou can write if (username) instead of if (username !== ""). An empty input box is falsy.
script.jsJS
D:/js-practice/script.js
Console output appears here
Module 4Ternary

The Ternary Operator: if-else in One Line

conditiontest
?if true
"Pass"this value
:else
"Fail"that value
script.jsJS
D:/js-practice/script.js
Console output appears here
D:/js-practice/status.html
Console output appears here
Use it forShort choices: singular/plural, colours, labels. For long logic use normal if-else – it is easier to read.
Module 4switch

switch: Many Fixed Choices

script.jsJS
D:/js-practice/script.js
Console output appears here
  1. 1
    switch compares the value with each case using ===
  2. 2
    The matching case runs until break
  3. 3
    Cases without break "fall through" (1-5 share one message)
  4. 4
    default runs when nothing matches
Forgot break?Without break, JS keeps running the next cases too. A classic bug!
Module 4Live Lab

Live Lab: A Result Checker

result.html – edit me!
Live preview
TryAdd grades A+/A/B/C. Show "Distinction" for 75+. Use a ternary to show "Well done!" or "Try again".
Module 4Practice Example 1 of 5

Grade Calculator

BeginnerThe JAC practice-test app shows a grade and a message for each student.

Your tasks

  1. Input for marks and a Check button
  2. else-if chain: A+ (90+), A (75+), B (60+), C (33+), else Fail
  3. Show the grade in a coloured badge
  4. Invalid marks (<0 or >100): show an error
  5. Log the marks and grade
Where this is used: Result portals, quiz apps, performance ratings.
grade.htmlHTML
Module 4Practice Example 2 of 5

Simple Login Check

BeginnerA school portal login (practice only – real apps check passwords on the server).

Your tasks

  1. Username and password inputs, Login button
  2. If either is empty: "Please fill both fields"
  3. If username is "admin" AND password is "rps@2026": "Welcome, Admin!"
  4. Otherwise: "Wrong username or password"
  5. Use trim() and a coloured message
HintNever keep real passwords in front-end JavaScript: anyone can read it with View Source. This is only to practise conditions.
Where this is used: Login forms (logic), PIN checks, admin-only buttons.
login.htmlHTML
Module 4Practice Example 3 of 5

Delivery Charge and Discount Rules

IntermediateRanchi Mart rules: free delivery above Rs. 499; students get 10% off; on Sunday everyone gets an extra Rs. 50 off orders above Rs. 1000.

Your tasks

  1. Variables: cartTotal, isStudent, day
  2. delivery = cartTotal >= 499 ? 0 : 40
  3. Apply student discount with if
  4. Sunday rule with &&
  5. Print a bill summary
Where this is used: Checkout rules in every shopping app.
rules.jsJS
Module 4Practice Example 4 of 5

Traffic Light Controller

IntermediateBuild a traffic light for a road-safety class: a button cycles red → green → yellow → red, and a message tells drivers what to do.

Your tasks

  1. Three circles for red, yellow, green
  2. Variable light = "red"
  3. On click, a switch decides the next light
  4. Only the active light is bright (opacity)
  5. Message: Stop / Go / Slow down
Where this is used: State machines in apps: order status, player states, step-by-step forms.
traffic.htmlHTML
Module 4Practice Example 5 of 5

Greeting by Time of Day + Shop Status

IntermediateA cafe website greets visitors based on the current time and shows whether the shop is open (8 AM to 10 PM).

Your tasks

  1. Get the hour with new Date().getHours()
  2. Good morning (5-11), afternoon (12-16), evening (17-20), night (else)
  3. isOpen = hour >= 8 && hour < 22
  4. Show a green OPEN or red CLOSED badge
  5. Log the hour for testing
HintTo test other times, temporarily replace the first line with const hour = 21;.
Where this is used: Greetings, "open now" labels on Google Maps-style listings, night-mode switches.
greeting.htmlHTML
Module 4Module complete

Recap: What You Completed in Module 4

  • ✓if / else: two paths
  • ✓else if chains (check biggest first)
  • ✓&& (and), || (or), ! (not)
  • ✓Falsy: false, 0, "", null, undefined, NaN
  • ✓Ternary: condition ? a : b
  • ✓switch with case, break and default
  • ✓Real rules: delivery, discounts, login, opening hours
100%Module 4 done

Coming next

Module 5: Loops – repeat tasks automatically: tables, lists, games.

Quick quiz – click an answer

Q1. Which value is FALSY?

Only the number 0 is falsy; "0" and "false" are non-empty strings.

Q2. true && false is:

AND needs both to be true.

Q3. What happens if you forget break in a switch case?

Execution continues into the next case.
MODULE 5

Loops

⏱ 3 hours5 practice examplesLive code lab

You will learn

  • Why loops: repeat work automatically
  • The for loop: start, condition, step
  • while and do...while loops
  • break and continue; nested loops
  • Looping over strings and lists with for...of

You will build

  • A multiplication table on a web page
  • A number guessing game
  • A star pattern and a bill total from many items
fori = 1 ... 10repeat without copy-paste
Module 5Real-world use

Where Is This Used in Real Websites and Apps?

LOGOCards / boxesListTableNavigation menu

You will find it here

  • Product grids: one card is created for each product in a loop
  • Tables: rows for each student, each transaction
  • Menus and lists built from data
  • Totals: add up every item in the cart
  • Games: the game loop runs many times every second
Module 5Why loops?

Why Loops? Do Not Copy-Paste 100 Times!

attendance.jsJS
D:/js-practice/attendance.js
Console output appears here
Lines of code needed01835527055 students6060 students3Any number(loop)
Module 5for loop

The for Loop: Start, Check, Run, Step

for( let i = 1; i <= 5; i++) { ... } 1. START (once)2. CHECK before each lap4. STEP after each lap check i <= 53. run the { body }i++ then check again; stop when the check is false
1

1. Start

let i = 1 runs once, before the first lap.
2

2. Check

i <= 5 is tested before every lap. false = stop.
3

3. Body

The code inside { } runs once per lap.
4

4. Step

i++ runs after every lap, then back to Check.
Module 5for loop

Step Through a for Loop

script.jsJS
Press Next step to run the program one line at a time.

Memory (variables)

(empty)

Console output

Module 5for loop

for Loop Patterns: Count Up, Down, by Steps

script.jsJS
D:/js-practice/script.js
Console output appears here
Common mistakei <= word.length goes one step too far (index 2 does not exist). For positions use i < length.
Module 5while

while and do...while: Repeat Until Something Happens

script.jsJS
D:/js-practice/script.js
Console output appears here
LoopUse when
forYou know how many times (10 rows, each item)
whileYou do NOT know how many times (until target, until correct guess)
do...whileIt must run at least once (show menu, then ask again)
for...ofGo through each item of a list/string (next slides)
Infinite loop!If the condition never becomes false, the loop runs forever and the tab freezes. Always change the variable inside the loop.
Module 5break / continue

break and continue: Exit Early or Skip One

script.jsJS
Press Next step to run the program one line at a time.

Memory (variables)

(empty)

Console output

Module 5Nested loops

Nested Loops: A Loop Inside a Loop

script.jsJS
D:/js-practice/script.js
Console output appears here
A1A2A3A4B1B2B3B4C1C2C3C4row Arow Brow Couter loop = rows, inner loop = seats in each row
Used forGrids: seats, calendars, game boards, multiplication tables, tables with rows and columns.
Module 5for...of

for...of: The Easy Way Through a List

script.jsJS
D:/js-practice/script.js
Console output appears here
LoopGives you
for (let i = 0; ...)the index number
for (const x of list)each value directly
Most commonIn real apps, for...of (and array methods in Module 7) are used far more than counting loops.
Module 5Live Lab

Live Lab: Multiplication Table Generator

table.html – edit me!
Live preview
TryMake it go up to 20. Highlight even results with a different colour (use %). Add a second loop to print tables 2 to 5 at once.
Module 5Practice Example 1 of 5

Multiplication Table on a Page

BeginnerA Class 3 maths website shows the table of any number in a neat list.

Your tasks

  1. Input for the number, button "Show table"
  2. for loop from 1 to 10
  3. Build list items with a template literal
  4. Put them into a <ul> with innerHTML
  5. Log each line in the console too
Where this is used: Generating repeated content: lists, rows, cards.
tables.htmlHTML
Module 5Practice Example 2 of 5

Sum and Average of Marks

BeginnerA teacher enters marks separated by commas. Calculate the total, average, and how many passed (33+).

Your tasks

  1. Marks string: "45, 78, 32, 90, 66, 28"
  2. Split it into a list with split(",")
  3. Loop with for...of: convert each to a Number, add to total
  4. Count passes with an if inside the loop
  5. Print total, average (1 decimal) and pass count
Where this is used: Report generation, analytics, totals in spreadsheets-like apps.
marks.jsJS
Module 5Practice Example 3 of 5

Number Guessing Game

IntermediateMake a game: the computer picks a number 1-20; the player guesses until correct, with "too high / too low" hints and a count of tries.

Your tasks

  1. Random secret number with Math.random
  2. Input + Guess button
  3. Compare: too high / too low / correct
  4. Count attempts; on correct show "Got it in N tries"
  5. Disable the button when won; a "Play again" button resets
HintThe page itself is the loop here: each click is one "lap". A while loop would freeze the page while waiting.
Where this is used: Games, quizzes, retry logic (OTP: 3 attempts max).
guess.htmlHTML
Module 5Practice Example 4 of 5

Star and Number Patterns

IntermediateClassic logic practice used in coding interviews: print a pyramid and a number triangle.

Your tasks

  1. Right triangle of stars, 5 rows (nested loop or repeat)
  2. Centred pyramid: spaces then stars
  3. Number triangle: 1 / 1 2 / 1 2 3 ...
  4. Use a variable line to build each row
  5. Change the size with one variable
Where this is used: Interview tests; the same nested-loop thinking builds grids and calendars.
patterns.jsJS
Module 5Practice Example 5 of 5

Bus Seat Layout Generator

AdvancedA Ranchi-Patna bus booking page draws 8 rows x 4 seats, with an aisle after seat 2, and marks some seats as booked.

Your tasks

  1. Nested loops: rows 1-8, seats A-D
  2. Booked seats list: "1A, 3C, 5B, 5C"
  3. Skip/break not needed: use includes to mark booked seats
  4. Add an aisle gap after seat B
  5. Count and show available seats
Where this is used: Bus, train, cinema and flight seat selection screens.
bus.htmlHTML
Module 5Module complete

Recap: What You Completed in Module 5

  • ✓Loops repeat code automatically
  • ✓for: start; check; step
  • ✓Counting up, down and in steps
  • ✓while / do...while when the count is unknown
  • ✓break (exit) and continue (skip)
  • ✓Nested loops for grids and patterns
  • ✓for...of for each item in a list or string
100%Module 5 done

Coming next

Module 6: Functions – reusable blocks of code (the most important idea in JS).

Quick quiz – click an answer

Q1. How many times does for (let i = 0; i < 3; i++) run?

i = 0, 1, 2.

Q2. Which keyword skips to the next lap?

continue skips; break exits.

Q3. Best loop when you do NOT know how many times?

while repeats until a condition changes.
MODULE 6

Functions & Scope

⏱ 3.5 hours5 practice examplesLive code lab

You will learn

  • Why functions: write once, use many times
  • Declaring and calling functions
  • Parameters, arguments and default values
  • return values
  • Arrow functions, scope and the call stack

You will build

  • A GST / discount calculator library
  • An EMI calculator
  • An age and BMI checker with buttons
500addGST( price )590inputoutput
Module 6Real-world use

Where Is This Used in Real Websites and Apps?

LOGOButtonFormCards / boxesNavigation menu

You will find it here

  • Every button runs a function when clicked: addToCart(), login(), search()
  • Calculations reused on many pages: calculateGST(), formatPrice()
  • Validation: isValidEmail(), isValidMobile()
  • Libraries like React are made of thousands of functions
  • Functions keep big apps organised
Module 6Why functions?

A Function Is a Machine: Input → Work → Output

500590120014168094.4 addGST(price)return price * 1.18 One machine, many inputs: the same code gives the right answer every time.
♻

Reuse

Write the GST logic once, use it on the cart, invoice and receipt pages.
📁

Organise

Give a name to a task: sendOTP() is easier to read than 20 lines.
🔧

Fix once

A bug in the formula? Fix it in one place, every page is fixed.
Module 6Declare & call

Declaring and Calling a Function

functionkeyword
greetname
(name)parameter (input slot)
{
... body: the work
}
script.jsJS
D:/js-practice/script.js
Console output appears here
WordMeaning
ParameterThe variable in the definition: name
ArgumentThe real value you pass: "Riya"
CallWriting the name with () runs it
greet without ()Just refers to the function, does not run it
Buttons call functions<button onclick="greet('Riya')"> calls the function when clicked. You have done this since Module 1!
Module 6return

return: Giving a Result Back

script.jsJS
Press Next step to run the program one line at a time.

Memory (variables)

(empty)

Console output

console.log vs returnconsole.log only SHOWS a value. return GIVES it back so the rest of the program can use it.
Module 6Parameters

Many Parameters and Default Values

script.jsJS
D:/js-practice/script.js
Console output appears here
  • Arguments are matched to parameters by position
  • Missing arguments become undefined, or the default if one is given
  • Functions that return true/false are often named isSomething or hasSomething
Module 6Arrow functions

Function Expressions and Arrow Functions

functions.jsJS
D:/js-practice/functions.js
Console output appears here
StyleWhen you see it
function name() {}Normal named functions
const f = function () {}Older code, callbacks
const f = () => {}Modern code, React, array methods (Module 7)
Arrow rulesOne parameter: brackets optional. One expression: braces and return optional. No parameters: () => ...
Module 6Scope

Scope: Where Can a Variable Be Seen?

GLOBAL scope: const shop = "Ranchi Mart" FUNCTION scope: checkout() { let total = 500 } BLOCK scope: if (...) { const coupon = "SAVE10" } Inside the block: coupon, total AND shop are visible From outside you CANNOT see inside a box. Like rooms: from a bedroom you see the hall, not the reverse.
script.jsJS
D:/js-practice/script.js
Console output appears here
Good habitKeep variables inside the function that needs them. Too many global variables cause bugs when two parts of the app use the same name.
Module 6Call stack

The Call Stack: Functions Calling Functions

CALL STACK (like a pile of plates) main program placeOrder() calcTotal() addGST() top runs first,returns, is removed bottom = started first
script.jsJS
D:/js-practice/script.js
Console output appears here
In DevToolsSources tab > set a breakpoint > the "Call Stack" panel shows exactly this pile (Module 19).
Module 6Live Lab

Live Lab: Small Functions Working Together

discount.html – edit me!
Live preview
TryAdd a function addGST(amount) and use it in show(). Give percent a default of 10. Rewrite applyDiscount as an arrow function.
Module 6Practice Example 1 of 5

GST and Discount Helper Functions

BeginnerBuild a tiny "pricing library" for a shop website: three functions that other pages can reuse.

Your tasks

  1. applyDiscount(price, percent) returns the reduced price
  2. addGST(price, rate = 18) returns price with GST
  3. formatINR(amount) returns "Rs. 1,180.00"
  4. Combine them: formatINR(addGST(applyDiscount(1000, 10)))
  5. Test with 3 different products
Where this is used: Shared utility files (utils.js) in every real project.
pricing.jsJS
Module 6Practice Example 2 of 5

EMI Calculator

IntermediateA Bokaro bike showroom wants an EMI calculator on its website.

Your tasks

  1. Function calcEMI(principal, yearlyRate, months)
  2. Monthly rate r = yearlyRate / 12 / 100
  3. EMI = P x r x (1+r)^n / ((1+r)^n - 1) (use **)
  4. Return the EMI rounded to 2 decimals
  5. Inputs + button show EMI, total paid and total interest
Where this is used: Bank, vehicle and home-loan websites; finance apps.
emi.htmlHTML
Module 6Practice Example 3 of 5

Age Calculator and Voting Eligibility

BeginnerA government-services kiosk checks if a citizen can vote (18+) from their birth year.

Your tasks

  1. Function getAge(birthYear) using the current year from Date
  2. Function canVote(age) returns true/false
  3. Function message(name, birthYear) returns a full sentence
  4. Use the functions together for 3 people
  5. Show results on the page as a list
Where this is used: Eligibility checks: scholarships, exams, schemes.
voter.htmlHTML
Module 6Practice Example 4 of 5

BMI Checker with a Button

IntermediateA gym website shows BMI and the category when you enter weight and height.

Your tasks

  1. calcBMI(kg, cm) returns kg / (m x m), 1 decimal
  2. bmiCategory(bmi) returns Underweight (<18.5) / Normal (<25) / Overweight (<30) / Obese
  3. Arrow function for the button handler
  4. Colour the result by category
  5. Validate: show an error if inputs are empty or 0
Hintreturn inside an if ends the function early. That is why no else is needed in bmiCategory.
Where this is used: Health and fitness apps; any "calculator" feature.
bmi.htmlHTML
Module 6Practice Example 5 of 5

Reusable Validation Functions

AdvancedCreate the validation helpers used by the sign-up form you will build in Module 11.

Your tasks

  1. isEmpty(text)
  2. isValidMobile(num): 10 digits, starts 6-9 (use a loop or regex later)
  3. isValidEmail(email): contains "@" and "." after it
  4. isStrongPassword(p): 8+ chars, has a number
  5. validateUser(user) returns a list of error messages
Where this is used: Form validation, API input checks, data cleaning.
validators.jsJS
Module 6Module complete

Recap: What You Completed in Module 6

  • ✓Functions: write once, call many times
  • ✓Declare with function name(params) { }
  • ✓Parameters vs arguments; default values
  • ✓return gives a value back (and ends the function)
  • ✓Function expressions and arrow functions =>
  • ✓Scope: global, function, block
  • ✓The call stack: functions calling functions
100%Module 6 done

Coming next

Part 2: Arrays, Objects and the DOM – control real web pages!

Quick quiz – click an answer

Q1. What does a function return if there is no return statement?

Functions return undefined by default.

Q2. const sq = n => n * n; then sq(4) is:

One-line arrows return automatically.

Q3. A variable declared with let inside a function can be used:

That is function scope.
PART 1 COMPLETE

Well done!

You have finished Part 1 of the Complete JavaScript Course.

Modules completed

  • Module 1: What Is JavaScript & Your First Program
  • Module 2: Variables, Data Types & Operators
  • Module 3: Strings, Numbers & Math
  • Module 4: Decisions: if, else, switch
  • Module 5: Loops
  • Module 6: Functions & Scope

Keep all your practice files in D:\js-practice. You will reuse them in the capstone apps.

</> Code Lab
Edit the code – the preview updates as you type
Live preview