Pre-Security Course / Module 4
Reading Code & JavaScript Basics
This module does two jobs. First it teaches you enough JavaScript — the language of the web — that words like variable, function, object and JSON stop being mysteries. Then it turns that reading skill on the DOM, on attack payloads, and on SQL. You do not need to become a developer; you need to look at code and know what it is doing. Every example here runs in the browser you already have — try them in the Console as you go.
4.1 · HTML and the DOM
HTML (HyperText Markup Language) is the skeleton of every web page. It is not a programming language — it does not calculate or decide anything; it simply describes structure using tags written in angle brackets. A tag usually comes as a pair — an opening tag and a closing tag with a slash — wrapping some content:
<h1>Welcome, Priya</h1>
<a href="/profile">My Profile</a>
Here <h1> marks a heading and <a> marks a link. The settings inside a tag — like href="/profile" — are attributes. So an element is a tag, its attributes, and its content together.
The DOM — the page as a tree
When the browser loads that HTML, it builds a live, in-memory tree of all the elements, called the DOM (Document Object Model). Every element nests inside its parent, exactly as the tags nest:
Why this matters for security: the browser must decide, for anything it shows, whether a piece of text is content (just display it) or HTML (build it into the tree as real elements). If an attacker can get the browser to treat their input as new HTML, they can inject their own elements — including a <script> — into your DOM. That is the seed of cross-site scripting (XSS), which we return to once you can read the JavaScript involved.
In short — HTML describes a page with tags and attributes; the browser turns it into a live tree, the DOM. Trouble starts when user input is treated as HTML instead of as text.
Quick check
-
In
<a href="/home">Home</a>, what ishref="/home"?Attributes live inside the opening tag and configure the element. Here it sets where the link goes.
-
What is the DOM?
The DOM is the page held in memory as a tree of elements — and JavaScript changes the tree, not the original file.
-
Is HTML a programming language?
HTML marks up structure with tags. It cannot calculate or make decisions — that is JavaScript's job.
4.2 · JavaScript: variables and data types
If HTML is the skeleton, JavaScript (JS) is the muscle — the language that makes pages do things, running right inside your browser. We will learn it in small pieces. Start with the most basic idea of any programming language: storing a value.
Variables — named boxes
A variable is a named box that holds a value. You create one with the word let, give it a name, and put something in it with =:
let age = 25;
let name = "Priya";
Now age holds 25 and name holds the text "Priya". With let you can change the box's contents later (age = 26;). If a value should never change, use const instead of let — a locked box. (You will also see the older keyword var; treat it as an old-fashioned let.)
Data types — the kinds of value
Every value has a type. The four you must know:
| Type | What it is | Example |
|---|---|---|
| String | Text, always in quotes | "hello", "admin" |
| Number | Any number, no quotes | 42, 3.14 |
| Boolean | Only true or false | true, false |
| Null / Undefined | "Empty" / "not set yet" | null, undefined |
The quotes matter: 25 is a number you can do maths with, while "25" is a string — text that happens to look like a number. Mixing the two up is a classic beginner bug, and it also shows up in security, where a value's type can change how the code behaves.
⌨ Try it yourself — make a variable
Open DevTools (F12) → Console, and type these one line at a time, pressing Enter after each:
let x = 5;
x + 3; // 8 — a number
let who = "admin";
who.length; // 5 — the text is 5 characters long
In short — a variable is a named box (let to change, const to lock). Every value has a type: string (text, in quotes), number, boolean (true/false), and the empties null/undefined.
Quick check
-
In
let name = "Priya";, what isname?letcreates a named box;nameis the label on it and"Priya"is what is inside. -
What is the difference between
25and"25"?Quotes make it a string.
25 + 25is 50, but"25" + "25"gives"2525". -
Which keyword makes a value that should never change?
constis a locked box.letallows the value to change later. -
Which of these is a boolean?
A boolean is only
trueorfalse."yes"is a string;42is a number.
4.3 · Operators, decisions and loops
Storing values is only useful if code can compare them, decide what to do, and repeat work. That is what this section adds.
Operators
Operators are the symbols that combine or compare values:
- Maths:
+-*/— add, subtract, multiply, divide. - Compare:
===(equal to),!==(not equal),>,<— these give back a boolean,trueorfalse. - Logic:
&&(and),||(or),!(not) — for combining conditions.
One trap worth flagging now: a single = assigns a value (puts it in the box), while === compares two values. Beginners mix these up constantly.
Making decisions with if
An if statement runs a block of code only when a condition is true; an else gives the alternative:
let age = 20;
if (age >= 18) {
console.log("Adult");
} else {
console.log("Minor");
}
Read it plainly: "if age is 18 or more, print Adult; otherwise print Minor." console.log(...) simply prints a value to the console — your everyday way to see what code is doing.
Repeating with loops
A loop repeats a block of code. The common for loop repeats a set number of times:
for (let i = 0; i < 3; i++) {
console.log(i); // prints 0, then 1, then 2
}
Read the three parts in the brackets as: start i at 0; keep going while i < 3; add 1 to i each time (i++). A while loop is simpler — it just repeats "while" a condition stays true. Loops are how code does the same thing to every item in a list — every user, every row, every file.
⌨ Try it yourself — a decision and a loop
In the Console, paste each block and press Enter:
let score = 72;
if (score >= 60) { "pass" } else { "fail" }
for (let i = 1; i <= 5; i++) { console.log("row " + i); }
In short — operators compare and combine values (mind = vs ===); if/else makes decisions; for and while loops repeat work — the way code touches every item in a list.
Quick check
-
What does a
forloop do?A loop runs the same block again and again — normally a set number of times, or once per item in a list.
-
What is the difference between
=and===?One equals sign puts a value into a variable. Three compare two values and give back true or false.
-
In
if (age >= 18) { ... } else { ... }, when does theelseblock run?elseis the other path: it runs only when theifcondition is not true. -
A comparison like
5 > 3gives back what kind of value?Comparisons always answer true or false — the boolean type that every decision in code rests on.
4.4 · Functions
A function is a named, reusable block of steps. You define it once, then call it whenever you need it — like a recipe you can follow again and again. Functions can take inputs (called parameters) and give back an output (with return):
function add(a, b) {
return a + b;
}
add(2, 3); // 5
Read it: the function add takes two inputs, a and b, and returns their sum. add(2, 3) calls it with 2 and 3, and hands back 5. You will also see a shorter modern style, the arrow function, which does the same thing:
const add = (a, b) => a + b;
Built-in functions you have already met
The browser gives you functions ready-made. You have used several already in this course:
alert("hi")— pop up a message box.console.log(x)— print a value to the Console.atob("YWRtaW4=")— decode base64 (from Module 1).document.getElementById("box")— grab an element from the DOM.
The round brackets are how you call a function; whatever you put inside them are the inputs. Spotting somename( ... ) in code and reading it as "call somename with these inputs" is a huge step in reading any program.
⌨ Try it yourself — write and call a function
function greet(who) {
return "Hello, " + who;
}
greet("Priya"); // "Hello, Priya"
In short — a function is a reusable named block of steps. It takes inputs (parameters) in round brackets and hands back an output with return. Calling one is name(inputs).
Quick check
-
What is a function?
A function packages steps under a name so they can be run again, usually taking inputs and returning a result.
-
In
add(2, 3), what are2and3?Values in the brackets are the arguments — the inputs the function works on.
-
What does
returndo in a function?returnends the function and passes its answer back to whatever called it. -
When you see
alert("hi"), what is happening?alertis a function the browser already provides; the brackets call it, and"hi"is the input.
4.5 · Objects, arrays and JSON
Single values only get you so far. Real programs group values together, and there are two shapes for that.
Arrays — ordered lists
An array is an ordered list, written in square brackets. You reach items by their position, counting from zero:
let users = ["priya", "amit", "sara"];
users[0]; // "priya" (the first item)
users.length; // 3
Objects — labelled values
An object groups values under labels (called keys), written in curly brackets as key: value pairs. Instead of a position, you reach a value by its key with a dot:
let user = {
name: "Priya",
role: "analyst",
active: true
};
user.name; // "Priya"
user.role; // "analyst"
user.role follows the "role" label to "analyst".JSON — objects as text for sending
Now the piece you will see constantly on the job. JSON (JavaScript Object Notation) is a text format for data that looks almost exactly like a JavaScript object — the difference is that keys are in quotes, and it is plain text, so it can travel across the network. It is how a browser and a server hand structured data to each other:
{
"name": "Priya",
"role": "analyst",
"active": true
}
When you watch web traffic in DevTools (Module 3) and a response looks like the block above, that is JSON. Two built-in functions convert between the two worlds: JSON.stringify(obj) turns an object into JSON text to send, and JSON.parse(text) turns received JSON text back into an object your code can use. Recognising JSON — and knowing it is just an object written as text — is one of the most useful things in this whole module, because modern apps and APIs speak JSON everywhere.
⌨ Try it yourself — object and JSON
let user = { name: "Priya", role: "analyst" };
user.role; // "analyst"
JSON.stringify(user); // '{"name":"Priya","role":"analyst"}' ← JSON text
In short — an array is an ordered list (square brackets, counted from 0); an object is a bundle of key→value pairs (curly brackets, reached with a dot). JSON is an object written as plain text — the format apps and APIs use to send data.
Quick check
-
Given
let user = { name: "Priya", role: "analyst" };, how do you get "analyst"?You reach an object's value by its key with a dot:
user.role→ "analyst". -
In the array
let a = ["x", "y", "z"];, what isa[0]?Arrays are indexed from 0, so
a[0]is the first item, "x". -
What is JSON?
JSON is an object written as plain text, which is how browser and server pass data to each other.
-
What is the main difference between an array and an object?
Arrays are ordered and reached by index. Objects hold key-and-value pairs and are reached by name.
4.6 · Putting it together — reading a payload
You now know enough JavaScript to read an attacker's input and say exactly what it does. That is the whole reason a tester learns this. The classic XSS test payload is:
<script>alert(1)</script>
Take it apart with what you have learned. It is an HTML <script> element (Module 4.1) containing JavaScript that calls the built-in function alert (Module 4.4) with the input 1. On its own the pop-up is harmless. The point is what it proves: if text you typed made an alert appear, the site ran your JavaScript. And if it will run a harmless alert, it will just as happily run code that reads the victim's session cookie (Module 3) and sends it away. That is why a humble pop-up is the standard proof of a cross-site scripting flaw — and why cookies marked HttpOnly are harder to steal this way.
Notice what just happened: you did not memorise a fact, you read the code. Element, function call, input, effect. That is exactly the skill this module set out to give you, and it is the skill you will use on every web test.
In short — reading code beats memorising payloads. <script>alert(1)</script> is a script element calling the alert function — proof the site runs your JavaScript, which an attacker escalates to stealing cookies (an XSS flaw).
Quick check
-
A tester enters
<script>alert(1)</script>and a pop-up appears. What has this proved?Input was treated as code rather than text. That is cross-site scripting (XSS).
-
In
alert(1), what role doesalertplay?The brackets are the giveaway:
alert(1)calls the built-in function with1as its argument. -
Why is a harmless
alert(1)treated as serious proof of a bug?The pop-up is harmless, but it proves the site executes your input. Anything else would run just as happily.
4.7 · SQL basics
JavaScript runs in the browser; the data it shows usually lives in a database on the server, arranged as tables — rows and columns, like a spreadsheet. A table called accounts might have columns id, name, balance, and one row per customer. The language used to ask a database for data is SQL (Structured Query Language), and you will read it constantly.
Read it plainly: SELECT which columns you want, FROM which table, WHERE some condition is true. The query above asks for the name and balance from accounts, for the row whose id is 42. That is most of the SQL you need to recognise.
Why testers care
Applications build these queries using input from the user — and that is where danger enters. Imagine a site glues your login straight into a query as text:
SELECT * FROM users WHERE user = 'INPUT' AND pass = 'INPUT';
If the app does not keep your input separate from the query, an attacker can type input that changes the query itself — for instance ending the text early with a quote and adding OR 1=1, a condition always true, to slip past the password check. That is SQL injection, one of the most serious and common web flaws. You do not need to master SQL to spot it; you need to read a query and see where user input lands inside it.
In short — SQL asks a database for data: SELECT columns FROM a table WHERE a condition holds. When user input is glued into a query unsafely, an attacker can rewrite the query — SQL injection.
Quick check
-
In
SELECT email FROM customers WHERE id = 7;, what doesWHEREdo?SELECTpicks the columns;WHEREpicks the rows. -
SQL injection becomes possible when…
When user text is pasted straight into a query, the user can change what that query means.
-
Why does adding
OR 1=1often bypass a login check?The injected condition is always true, so the
WHEREclause succeeds no matter what password was given.
4.8 · Recognising Oracle, MSSQL and MySQL
SQL is a standard, but every database vendor adds its own dialect — small differences in syntax and built-in features. On a real engagement, especially in a bank, you must be able to glance at a query or a config and say which database it belongs to. You do not have to write it; you have to recognise it. This skill turns up in two places at once: understanding SQL-injection payloads, and reviewing database configurations against a standard (the config-review work from Module 2, and Module 5's VACA).
| Database | Give-away signs | Where you meet it |
|---|---|---|
| Oracle | FROM dual, SYSDATE, packages named DBMS_..., string join with || | Large enterprise / core banking. |
| Microsoft SQL Server (MSSQL) | SELECT @@version, GETDATE(), sp_configure, TOP 10, xp_cmdshell | Windows / .NET environments. |
| MySQL / MariaDB | LIMIT 10, backtick quotes `col`, information_schema, version() | Web apps, open-source stacks. |
A worked read: open a database config for review and see EXEC sp_configure 'xp_cmdshell', 1;. Two tells fire at once — sp_configure and xp_cmdshell — so you know instantly this is Microsoft SQL Server, and can check the settings that matter for that engine (that one, xp_cmdshell, lets the database run operating-system commands — exactly the risky feature a config review flags). A fresher who freezes at "is this Oracle or MSSQL?" loses credibility fast; one who names it in a glance does not.
⌨ Try it yourself — spot the dialect
Read each line and name the database:
1) SELECT * FROM emp WHERE rownum <= 5; -- ?
2) SELECT TOP 5 * FROM emp; -- ?
3) SELECT * FROM emp LIMIT 5; -- ?
Answers: (1) Oracle (rownum), (2) MSSQL (TOP), (3) MySQL (LIMIT). Three ways to say "first five rows" — the dialect is the tell.
In short — every database has a dialect. Recognise the tells — Oracle (dual, DBMS_, ||), MSSQL (@@version, sp_configure, xp_cmdshell, TOP), MySQL (LIMIT, backticks) — so you can name the engine in queries and config reviews.
Quick check
-
You see
SELECT @@version; EXEC sp_configure;in a config. Which engine?@@versionandsp_configureare MSSQL fingerprints. -
A query ends with
FROM dualand joins strings with||. Which database?dualand||for string concatenation are classic Oracle. -
You see backtick-quoted column names and
LIMIT 20. Which engine?Backticks around identifiers and
LIMITare MySQL and MariaDB signatures.
Module 4 glossary
- HTML / DOM
- Tags that describe structure / the browser's live tree of those elements.
- JavaScript
- The language that makes pages interactive; runs in the browser.
- Variable
- A named box for a value (
letto change,constto lock). - Data type
- The kind of value: string (text), number, boolean (true/false), null/undefined.
- Operator
- Symbols to combine/compare values:
+ - * /,===,&&,||. - if / else
- Run code only when a condition is true, with an alternative.
- Loop (for / while)
- Repeat a block of code — e.g. over every item in a list.
- Function
- A reusable named block; takes inputs (parameters), gives an output (
return). Call it withname(inputs). - Array
- An ordered list in square brackets, indexed from 0.
- Object
- A bundle of key→value pairs in curly brackets, reached by name with a dot.
- JSON
- An object written as plain text — the format apps and APIs use to send data.
- SQL
- The language to query a database: SELECT … FROM … WHERE …
- SQL injection
- Changing a query's meaning via input the app failed to keep separate.
- Dialect
- A vendor's flavour of SQL — Oracle, MSSQL, MySQL.
Recap — what you can now do
- Read HTML tags and picture the page as a DOM tree.
- Read JavaScript: variables and types, operators,
if/else, loops, and functions. - Explain what an object, an array and JSON are — and read them.
- Take apart an XSS payload by reading the code, not memorising it.
- Read a basic SQL query, spot injection, and recognise Oracle, MSSQL and MySQL.
End-of-module quiz
-
Which line creates a variable holding text?
A string is text in quotes, stored in a variable —
let name = "Priya";. -
{ "name": "Priya", "role": "analyst" }is an example of…Curly braces with
"key": valuepairs is JSON — the format APIs send data in. -
You see
calculateTotal(items)in some code. What is happening?The name followed by brackets means a call, and
itemsis the input being handed in. -
A comment box shows your typed
<script>as running code, not text. What have you likely found?Input that is rendered as HTML or JavaScript instead of plain text is XSS.