JavaScript is a lightweight, interpreted programming language that is used to add interactivity and dynamic behaviour to web pages. While HTML provides the structure and CSS provides the styling, JavaScript gives life to a web page by enabling actions such as validating a form, responding to a button click, changing the content of a page, showing alert messages, and creating animations. JavaScript runs in the browser of the client computer, which is why it is also called a client-side scripting language.
JavaScript was created by Brendan Eich at Netscape in 1995 and was originally called LiveScript. It is not related to the Java programming language despite the similar name. JavaScript is one of the three core technologies of the World Wide Web, and today it is also used on the server side through environments like Node.js. Because JavaScript is interpreted, the browser reads and executes the code line by line without the need for compilation.
In this chapter we will learn how to embed JavaScript in HTML pages, write basic programs using variables and data types, use operators, and control the flow of a program with conditional statements and loops. We will also study functions, events, and built-in objects. This foundation will enable students to create interactive web pages and prepare them for more advanced topics in computer science.
JavaScript code can be placed inside an HTML page using the <SCRIPT> tag. The <SCRIPT> tag can appear in the head section or the body section of the page. When a script is placed in the body, it runs when the page loads; when placed in the head, it is loaded before the page is displayed. A <SCRIPT> tag can be written in two ways:
<SCRIPT> and </SCRIPT> tags in the HTML page..js file and linked using <SCRIPT SRC="script.js"></SCRIPT>.<SCRIPT>
document.write("Welcome to JavaScript");
</SCRIPT>
The document.write() method writes text directly to the web page. This simple example shows how JavaScript interacts with the document object of the browser.
Variables are named storage locations in memory that hold data. In JavaScript, variables are declared using the var keyword, or in modern versions with let and const. The value stored in a variable can be changed during the execution of the program.
var name = "Riya";
var age = 15;
var marks = 92.5;
JavaScript supports the following basic data types:
15 or 92.5."Riya".true and false, used for logical decisions.JavaScript is a dynamically typed language, which means a variable can hold any type of value and its type can change at runtime. The typeof operator is used to find the data type of a value.
Operators are symbols that perform operations on operands. The main categories of operators in JavaScript are given below.
+ (addition), - (subtraction), * (multiplication), / (division), % (modulus or remainder), ++ (increment), and -- (decrement).=, +=, -=, *=, and /=. For example, x += 5 is the same as x = x + 5.== (equal to), === (strictly equal), != (not equal), > (greater than), < (less than), >= (greater than or equal to), and <= (less than or equal to). These operators return a boolean value.&& (AND), || (OR), and ! (NOT). They are used to combine multiple conditions.+ operator can join (concatenate) two strings, for example "Hello" + " World" gives "Hello World".When a string and a number are added, JavaScript performs string concatenation. For example, "5" + 3 results in the string "53". Understanding operator behaviour is essential for writing correct programs.
Conditional statements allow a program to take decisions based on conditions. JavaScript supports if, if...else, if...else if...else, and switch statements.
var age = 18;
if (age >= 18) {
alert("You are eligible to vote");
} else {
alert("You are not eligible to vote");
}
The if statement executes a block of code if the condition is true, otherwise the else block executes. The else if ladder checks multiple conditions in sequence, and the switch statement is used when a variable is compared against several constant values. The condition inside the parentheses must evaluate to a boolean value.
Loops are used to execute a block of code repeatedly. JavaScript provides three main types of loops.
var sum = 0;
for (var i = 1; i <= 10; i++) {
sum = sum + i;
}
document.write("Sum = " + sum);
This program computes the sum of the first ten natural numbers, which is 55. Loops together with conditional statements form the basis of all programming logic.
A function is a reusable block of code that performs a specific task. Functions help to organise the program and avoid repeating the same code. A function is defined using the function keyword and is called by its name whenever it is needed.
function greet(name) {
return "Hello " + name;
}
document.write(greet("Arjun"));
In this example, greet is the function name and name is a parameter. The return statement sends a value back to the caller. Functions can have any number of parameters, and a function can be called from anywhere in the page, including from within event handlers. In JavaScript, a function is also called a subprogram or method, and it is treated as a first-class object.
An event is an action that occurs on a web page, such as clicking a button, moving the mouse, pressing a key, or submitting a form. JavaScript can respond to these events using event handlers. An event handler is an attribute or listener that executes a piece of code when the event occurs. Common events include:
onclick: occurs when a user clicks an element.onmouseover: occurs when the mouse pointer moves over an element.onmouseout: occurs when the mouse pointer leaves an element.onkeydown: occurs when a key is pressed.onchange: occurs when the value of a control changes.onsubmit: occurs when a form is submitted.<BUTTON onclick="alert('Button clicked!')">Click Me</BUTTON>
When the user clicks the button, the alert dialog box displays the message. Event handling is the key to making web pages interactive, and it is extensively used in form validation and dynamic page updates.
JavaScript provides many built-in objects with useful methods. The most important ones for beginners are listed below.
document.write(): writes text to the document.alert(message): displays a message in a dialog box.prompt(message): displays a dialog box asking for input and returns the entered value.confirm(message): displays a dialog box with OK and Cancel buttons and returns true or false.String methods: length (number of characters), toUpperCase(), toLowerCase(), and charAt().Math object: Math.sqrt(), Math.pow(), Math.round(), and Math.random().These built-in objects save time and make programs more powerful. In practical exams, alert, prompt, and document.write are the most commonly tested methods.
| Data Type | Description | Example |
|---|---|---|
| Number | Integer or floating point | 15, 92.5 |
| String | Sequence of characters | "Riya" |
| Boolean | true or false | true |
| Null | No value | null |
| Undefined | Variable without value | var x; |
| Event | When It Occurs |
|---|---|
| onclick | User clicks an element |
| onmouseover | Mouse pointer moves over an element |
| onmouseout | Mouse pointer leaves an element |
| onkeydown | A key is pressed |
| onchange | Value of a control changes |
| onsubmit | A form is submitted |
The most important idea in this chapter is that JavaScript treats values flexibly, and beginners must learn to predict how values behave when combined. When the plus operator is used with two numbers, it adds them, but when it is used with a string and a number, it joins them together into a new string. This is why "5" + 3 gives "53" while 5 + 3 gives 8. The same idea extends to comparisons: the loose equality operator == compares two values after converting them to a common type, so 5 == "5" is true, whereas the strict equality operator === compares both the value and the type, so 5 === "5" is false. Practising expressions of this kind builds the careful mindset that prevents many silent errors in larger programs.
Variables are the containers of a program, and JavaScript gives us three ways to declare them. The keyword var was used in older code and has a broad scope, while let and const, introduced in modern JavaScript, give finer control. A variable declared with let can be reassigned, but a variable declared with const cannot be changed after its first value is stored. Choosing the right keyword makes the program's intent clear and prevents accidental overwriting of values that must stay fixed. The typeof operator, which reports the data type of a value, is the quickest way to check what a variable actually holds at any moment in the execution of the script.
Functions and events together turn a static page into an interactive one. A function is defined once with the function keyword, but it is not executed until it is called; the call provides the arguments, the function works with them, and the return statement sends the result back. Events such as onclick connect these functions to the user's actions, so that a click on a button can call a function that validates a form or changes the text of the page. Understanding this link between events and functions is the bridge from writing simple scripts to building genuinely interactive web pages, because it explains how a page responds to the person using it. Loops and conditional statements fit into the same mental model: a condition chooses which block runs, a loop repeats a block a chosen number of times, and a function packages any block so that it can be reused from anywhere in the page.
"5" + 3 gives "53" because the plus operator concatenates a string and a number.= (assignment) instead of == (comparison) inside an if condition.</SCRIPT> tag, which makes the browser display the code as text.var keyword in older code, which creates an accidental global variable.while when the number of iterations is known; a for loop is more appropriate in such cases.alert and Alert are different.<SCRIPT> ... </SCRIPT> with document.write or alert.== and ===. == compares values after type conversion, while === compares value and type.JavaScript is the scripting language that makes web pages interactive and dynamic. In this chapter we learned to embed JavaScript in HTML, declare variables with different data types, use arithmetic, comparison, and logical operators, and control program flow with conditional statements and loops. We also studied functions, which make code reusable, and events, which connect user actions to program responses. Built-in methods such as alert, prompt, and document.write are the practical tools of daily JavaScript programming. With this foundation, students can move on to understanding how scripts interact with databases and web services in later chapters.