Computer4U logo
Plus Two Computer Science · Chapter 06

Client Side Scripting Using JavaScript

9 sections
Live JavaScript playground
14 review questions
6.1

Getting Started with JavaScript

6.1

The SCRIPT Tag

JavaScript code is embedded in a web page using the <SCRIPT> tag. Its Language attribute names the scripting language being used — here, always JavaScript. A page containing JavaScript is still saved with an .html extension.

<SCRIPT Language= "JavaScript">
document.write("Welcome to JavaScript.");
</SCRIPT>

document.write() is a JavaScript function that inserts text into the body section of the page — document refers to the body section itself. Like C++, every JavaScript statement ends in a semicolon, and script code can appear more than once, anywhere between HTML tags.

6.1.1

Case Sensitivity & the Script Engine

JavaScript is case sensitive — keywords are always lowercase. Identifiers conventionally use camelCase (e.g. firstName, checkData): lowerCamelCase when the first word starts lowercase, UpperCamelCase when it doesn't. Every browser has a JavaScript engine, a virtual machine that interprets script code at runtime; a page with no script renders faster since the browser skips handing anything to the engine. Users can disable JavaScript entirely in their browser settings, in which case the browser simply ignores everything inside <SCRIPT>.

6.2

Creating Functions in JavaScript

6.2

Defining & Calling a Function

A function is a named group of instructions, defined with the keyword function. Unlike C++, a JavaScript function declares no return type. Defining a function does not run it — it must be called by name, followed by parentheses and a semicolon.

function print()
{
  document.write("Welcome to JavaScript.");
}

print(); <!-- must be called to execute -->

A function can be defined inside <HEAD> or <BODY>, but placing it in the head section is usual practice — the head loads before the body, so by the time the body calls the function, its definition is already in memory.

6.3

Data Types in JavaScript

6.3

Number, String & Boolean

Where C++ has int, char, float, double and more, JavaScript reduces this to just three basic data types.

Table 6.0: Basic data types in JavaScript
TypeHoldsExamples
NumberAll positive/negative, integer and fractional values.27, -300, 1.89, -0.0082
StringAny characters enclosed in double quotes."Kerala", "Mark20", "sanil@123"
BooleanExactly two values — not quoted.true, false

If true or false are written inside quotes, they become strings instead. JavaScript is case sensitive, so TRUE and FALSE are not valid booleans.

6.4

Variables in JavaScript

6.4

The var Keyword

Where C++ uses int, float, char and so on, JavaScript declares every variable with the single keyword var. A declaration alone doesn't define a variable's type — that's decided only once a value is assigned. Several variables can share one var statement, separated by commas.

var a, b, c, d, f;
a = 25;    <!-- number -->
b = 18.5;  <!-- number -->
c = "INDIA"; <!-- string -->
d = true;   <!-- boolean -->
document.write(typeof(a)); <!-- "number" -->

The built-in typeof() function reports a variable's type. A variable that's declared but never assigned a value has the special type undefined.

6.5

Operators in JavaScript

6.5.1–6.5.4

Arithmetic, Assignment, Relational & Logical

Almost every operator in JavaScript works exactly as it does in C++.

+ − * / %= += −= *= /= %=== != > < >= <=&& || !
6.5.5

The String Addition Operator (+)

The same + operator that adds numbers also concatenates strings — its behaviour depends on the type of its operands. If either operand is a string, both are treated as strings.

var x = "42";
var y = 5;
var z = x + y;  <!-- z is "425" (string concatenation) -->

var z2 = Number(x) + y;  <!-- z2 is 47 (numeric addition) -->

Number() converts a string containing digits into a true number type — essential when adding values pulled from a text box, since text box content is always treated as a string.

6.6

Control Structures in JavaScript

6.6.1

if & if–else

Every control structure familiar from C++ carries over unchanged.

if (score < 30)
{
  document.write("The student is failed.");
}
else
{
  document.write("The student is passed.");
}
6.6.2

switch

A multi-branching statement — the matching case runs based on the value of the expression.

switch (d)
{
  case 1: document.write("Sunday"); break;
  case 2: document.write("Monday"); break;
  default: document.write("Invalid Day");
}
6.6.3–6.6.4

for & while Loops

for uses a loop variable to control the number of iterations; while repeats for as long as its test expression stays true. do–while exists too, but for and while cover almost every case a beginner needs.

for (i = 1; i < = 10; i++)
{
  document.write("Square of " + i + " is " + (i*i));
  document.write("<BR>");
}
6.7

Built-in Functions

6.7

alert, isNaN, and String Methods

JavaScript's built-in functions (also called methods) handle common tasks without any code of your own.

Table 6.0: Frequently used built-in functions
Function / PropertyPurpose
alert("msg")Pops up a message window — handy for validation feedback.
isNaN(value)Returns true if the value is not a number.
x.toUpperCase()Returns the upper-case form of string x.
x.toLowerCase()Returns the lower-case form of string x.
x.charAt(n)Returns the character at position n (0-indexed).
x.lengthProperty (no parentheses) giving the number of characters in x.

The difference between a function and a property: a function is called with parentheses and often arguments (x.toUpperCase()); a property is accessed directly by name (x.length).

6.8

Accessing Textbox Values Using JavaScript

6.8

document.form.element.value

Any form control needs a Name before JavaScript can reach it. A control is then addressed as document.formName.elementName.value.

function showSquare()
{
  var num = document.frmSquare.txtNum.value;
  document.frmSquare.txtSqr.value = num * num;
}

The function is wired to a control using an event attribute, most commonly onClick on a button:

<INPUT Type= "button" Value= "Show" onClick= "showSquare()">

Table 6.6: Common JavaScript events
EventOccurs when…
onClickthe user clicks on an object.
onMouseEnterthe mouse pointer moves onto an object.
onMouseLeavethe mouse pointer moves off an object.
onKeyDownthe user presses a key on the keyboard.
onKeyUpthe user releases a key on the keyboard.

6.8.1

Drop-down Lists & Validation

A <SELECT> control's selectedIndex property gives the position of the chosen <OPTION>, counting from 0. Combined with isNaN(), string length checks, and return to bail out early, these pieces build real client-side validation.

function checkData()
{
  var T_name = document.frmValid.txtName.value;
  if (T_name == "")
  { alert("Please enter name!"); return; }
  if (T_name.length < 5)
  { alert("Name must contain at least 5 characters!"); return; }
}

JavaScript never raises an error dialog of its own — if the engine can't execute a line, it silently skips the rest of the function. That's why explicit checks with alert() and return matter for guiding the user.

6.9

Ways to Add Scripts to a Web Page

6.9.1–6.9.3

Inside BODY, Inside HEAD, or External File

Scripts can live in three places, each with a trade-off.

Inside <BODY> — runs as the page loads, in placeInside <HEAD> — loads before the body; the usual choiceExternal .js file — reusable across pages, keeps HTML clean

An external file holds JavaScript only — no <SCRIPT> tag inside it — and is linked in with the Src attribute. When Src is present, any code written inside that same <SCRIPT> tag is ignored, so a linked file and inline code need two separate tags.

<SCRIPT Type= "text/JavaScript" Src= "checkdata.js">
</SCRIPT>
Try It Yourself

Live JavaScript Playground

Edit the code on the left and press Run to see the result on the right — try out the functions and events from this chapter directly.

index.html
Self-Assessment

Question & Answer Review

Tap a question to reveal the answer — a quick way to check understanding before moving to Chapter 7.

01Which tag and attribute are used to include JavaScript in an HTML page?
The <SCRIPT> tag, with its Language attribute set to "JavaScript".
02What does document.write() do?
It is a JavaScript function that inserts the given text into the body section of the web page — document refers to the body section itself.
03Why must a function be called even after it is defined?
Defining a function only stores its instructions — it does not run automatically. It executes only when called by its name followed by parentheses.
04Name the three basic data types in JavaScript.
Number, String, and Boolean.
05What keyword declares a variable in JavaScript, and how does that differ from C++?
The keyword var declares every variable, regardless of the type of value it will hold — unlike C++, which uses a different keyword (int, float, char, etc.) for each type.
06What value does a declared-but-unassigned variable hold, and what does typeof() do?
It holds the special value undefined. typeof() is a built-in function that reports the current data type of a variable.
07How does the + operator behave differently with strings versus numbers?
Between two numbers, + adds them arithmetically. If either operand is a string, both are treated as strings and + concatenates them instead.
08Why is the Number() function often needed when processing text box input?
Text box content is always treated as a string by default. Number() converts that string into a true number type so arithmetic operators add rather than concatenate the values.
09List the control structures covered in this chapter.
if and if–else, switch, the for loop, and the while loop — all used exactly as they are in C++.
10What does isNaN() check, and why is it useful for validation?
It returns true if the given value is NOT a number. It's useful for checking whether a user has typed a number into a field that expects one, before further processing.
11How is a web page element accessed from JavaScript, and why must it be named?
Using document.formName.elementName.value. An element with no Name attribute cannot be referenced from JavaScript at all.
12What does onClick= "functionName()" do when written inside an INPUT tag?
It calls that function whenever the user clicks the element — one of several event attributes (along with onMouseEnter, onMouseLeave, onKeyDown, onKeyUp) that can trigger a JavaScript function.
13What does the selectedIndex property of a SELECT element give you?
The position (starting from 0) of the currently chosen OPTION in a drop-down list.
14What are the three places a script can be placed, and what's the advantage of an external .js file?
Inside <BODY>, inside <HEAD>, or as an external file. An external .js file can be reused across multiple pages, keeps HTML and JavaScript easier to read and maintain, and can speed up page loading.