ЁЯТ╗
тМия╕П
ЁЯЦ▒я╕П
ЁЯЦея╕П
ЁЯТ╛
тЖР Back to Dashboard
Font Size:

1. Introduction

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.

2. Embedding JavaScript in HTML

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:

Example of internal JavaScript

<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.

3. Variables and Data Types

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:

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.

4. Operators in JavaScript

Operators are symbols that perform operations on operands. The main categories of operators in JavaScript are given below.

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.

5. Conditional Statements

Conditional statements allow a program to take decisions based on conditions. JavaScript supports if, if...else, if...else if...else, and switch statements.

The if...else statement

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.

6. Loops in JavaScript

Loops are used to execute a block of code repeatedly. JavaScript provides three main types of loops.

Example of a for loop

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.

7. Functions in JavaScript

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.

8. Events and Event Handling

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:

Example using the onclick event

<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.

9. Built-in Objects and Methods

JavaScript provides many built-in objects with useful methods. The most important ones for beginners are listed below.

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.

Quick Revision Tables

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

Mind Map

graph TD A["JavaScript Basics"] --> B["Embedding in HTML"] A --> C["Variables & Data Types"] A --> D["Operators"] A --> E["Control Flow"] A --> F["Functions"] A --> G["Events"] B --> B1["Internal - SCRIPT tag"] B --> B2["External - .js file"] D --> D1["Arithmetic, Assignment"] D --> D2["Comparison, Logical"] E --> E1["if, if...else, switch"] E --> E2["for, while, do...while"] G --> G1["onclick, onmouseover"] G --> G2["onkeydown, onsubmit"]

Important Diagrams (SVG)

Diagram 1: JavaScript in a Web Page

HTML (Structure) Defines the content of the page CSS (Presentation) Styles colours, fonts, and layout JavaScript (Behaviour) Adds interactivity and responds to events Golden Rule: HTML, CSS, and JavaScript together build an interactive web page.

Diagram 2: if...else Flowchart

Start age >= 18 ? True False alert("Eligible to vote") if block alert("Not eligible") else block End Golden Rule: Only one of the if or else blocks executes for a given condition.

10. Detailed Concept Explanation

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.

Common Mistakes

  1. Confusing JavaScript with Java. They are two completely different languages with no relationship.
  2. Forgetting that "5" + 3 gives "53" because the plus operator concatenates a string and a number.
  3. Using = (assignment) instead of == (comparison) inside an if condition.
  4. Forgetting the closing </SCRIPT> tag, which makes the browser display the code as text.
  5. Declaring variables without the var keyword in older code, which creates an accidental global variable.
  6. Using while when the number of iterations is known; a for loop is more appropriate in such cases.
  7. Forgetting that JavaScript is case-sensitive, so alert and Alert are different.

Exam Tips

  1. Learn to write the skeleton of a script: <SCRIPT> ... </SCRIPT> with document.write or alert.
  2. Memorise the difference between == and ===. == compares values after type conversion, while === compares value and type.
  3. Practise writing an if...else program to check even or odd numbers, a very common exam question.
  4. Remember the three parts of a for loop: initialisation, condition, and increment.
  5. Be able to describe at least three events with examples: onclick, onmouseover, and onsubmit.
  6. Know the data types and be able to identify the type of a given value using the typeof operator.

Conclusion

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.