0% found this document useful (0 votes)
8 views23 pages

Embedding JavaScript in HTML_unit 3_12_08_25

The document explains how to embed JavaScript in HTML, detailing two methods: inline with <script> tags and externally with .js files. It covers identifiers, reserved words, primitive data types, and variable declarations in JavaScript, along with numeric and string operations. Additionally, it discusses type coercion, string methods, and the typeof operator.

Uploaded by

amsini
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views23 pages

Embedding JavaScript in HTML_unit 3_12_08_25

The document explains how to embed JavaScript in HTML, detailing two methods: inline with <script> tags and externally with .js files. It covers identifiers, reserved words, primitive data types, and variable declarations in JavaScript, along with numeric and string operations. Additionally, it discusses type coercion, string methods, and the typeof operator.

Uploaded by

amsini
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 23

Embedding JavaScript in HTML

JavaScript can be included in an HTML document in two main


ways:
a. Directly in HTML with <script> tags
html

<script type="text/javascript">
alert("Hello World");
</script>
 The JavaScript code is written between the <script> and
</script> tags.
 In older HTML versions, the type="text/javascript" attribute
was required.
 In HTML5, this attribute is optional because
"text/javascript" is the default.
b. Indirectly with an external .js file
html

<script type="text/javascript" src="tst_number.js"></script>


 The src attribute points to the JavaScript file.
 Even when the <script> element has no direct content, it
still requires a closing tag (</script>).
Why sometimes inline scripts are used?
 For small amounts of code.
 When multiple small scripts appear in different places in the
HTML, separating them into a file can be inconvenient.
2. Identifiers in JavaScript
Identifiers are names used for variables, functions, and other
entities.
Rules for identifiers:
 Must start with a letter, underscore _, or dollar sign $.
 After the first character, they can also include digits (0–9).
 No limit on length.
 JavaScript is case-sensitive:

myVar ≠ MyVar ≠ MYVAR


 By convention, programmer-defined variable names usually
avoid uppercase entirely or use them only for constants or
class names.
Special note on $:
 Technically valid, but originally not intended for user
scripts.
 In practice, some libraries (like jQuery) use $ heavily.

3. Reserved Words
JavaScript has 25 reserved words that cannot be used as
identifiers (variable names, function names, etc.). These include
keywords like if, for, return, while, etc.
1. Document type declaration
 In modern HTML5, the correct syntax should be:
html
<!DOCTYPE html>
(Notice the space and no dot — your current version is a
small typo.)
 This tells the browser: "Render this as an HTML5 document."

2. HTML comment at the top


html

<!-- hello.html
A trivial hello world example of HTML/JavaScript
-->
 This is a standard HTML comment.
 It’s ignored by the browser and is used for documentation.
3. Opening the HTML document
html

<html lang="en">
 <html> marks the start of your HTML code.
 lang="en" declares the document language (English) — helps
accessibility tools and search engines.

4. <head> section
html

<head>
<title> Hello world </title>
<meta charset="utf-8" />
</head>
 <title> → The text shown in the browser tab or window title.
 <meta charset="utf-8"> → Declares that the page uses UTF-
8 character encoding, so it can display almost all world
characters correctly.
5. <body> section with JavaScript
html
<body>
<script type="text/javascript">
<!-
document.write("Hello, fellow Web programmers!");
// -->
</script>
</body>
Inside the <script> tag:
 type="text/javascript" → Specifies the scripting language. In
HTML5, you can omit this because JavaScript is default.
 document.write("Hello, fellow Web programmers!"); → This
JavaScript command writes text directly into the web page
at the point where the script runs.

6. Closing the HTML


html

</html>
 Marks the end of the HTML document.

When this page runs:


The browser parses the HTML, executes the JavaScript inside
<script>, and displays:

Hello, fellow Web programmers!


It is directly on the webpage.

Primitives, Operations, and Expressions

The primitive data types, operations, and expressions of


JavaScript are similar to those of other common
programming languages.
1. The Five Primitive Types
Primitive values are simple, fast, and immutable. Wrapper
objects exist mainly to give you useful properties and
methods, and JavaScript will create them for you
automatically when needed.
In JavaScript, a primitive type is the most basic kind of data.
The five primitives are:
1. Number – numeric values (e.g., 42, 3.14, -5)
2. String – text (e.g., "Hello", 'World')
3. Boolean – logical values (true or false)
4. Undefined – means a variable has been declared but not
assigned a value
5. Null – means “no value” or “nothing”
Example:
javascript
let age = 17; // Number
let name = "Alice"; // String
let isStudent = true; // Boolean
let x; // Undefined
let y = null; // Null
2. Wrapper Objects
Even though primitives like "Hello" or 42 are not objects,
JavaScript provides built-in object versions of three primitives:
 Number object for Number primitives
 String object for String primitives
 Boolean object for Boolean primitives

These wrapper objects:


 Store a primitive value inside them
 Provide extra properties and methods that you can use
For example:
javascript
let numPrimitive = 42; // primitive
let numObject = new Number(42); // wrapper object
console.log(numPrimitive.toFixed(2)); // Works! Output: "42.00"

Numeric Literals in JavaScript


 In JavaScript, all numbers (whether integers or decimals)
are stored as the same type: Number.
 This Number type uses double-precision floating-point
format (the same as in most programming languages).
Forms of Numeric Literals
You can write numbers in several ways:
1. Integers → Just digits:
72
2. Floating-point numbers → Have a decimal point:
pgsql

7.2
.72 // leading decimal without 0 is allowed
72. // trailing decimal without digits after is allowed
3. Scientific notation (exponents) → Use e or E:
7E2 // means 7 × 10² = 700
7e2 // same as above
.7e2 // 0.7 × 10² = 70
7.2E-2 // 7.2 × 10⁻² = 0.072
4. Hexadecimal → Start with 0x or 0X:
0xFF // 255 in decimal

2. String Literals in JavaScript


 A string literal is a sequence of characters wrapped in
single quotes ' ' or double quotes " ".
 Both forms are equivalent:
javascript

'Hello'
"Hello"
Escape sequences
Special characters in strings are written with a backslash \:
 \n → new line
 \t → tab
 \' → single quote (inside single-quoted string)
 \" → double quote (inside double-quoted string)
 \\ → backslash
Example:
javascript

'You\'re the most freckly person I\'ve ever seen'


"D:\\bookfiles"

3. Empty (Null) String


 A string with no characters can be written as:
javascript

'' // single quotes


"" // double quotes

Summary Table
Type Examples
Integer 72, 100
Float 7.2, .72, 72.
Scientific 7E2, .7e2, 7.2E-2
Hexadecimal 0x1A, 0XFF
String 'Hello', "World"
Escaped String 'You\'re cool', "D:\\path"
Empty String '', ""
Other Primitive Types in JavaScript
JavaScript has three additional primitive types besides Number
and String:
Possible
Type Notes
Value(s)
Means "no value." A variable is null if it’s
explicitly set to that value. Using a null
Null null
variable without assigning it first causes a
runtime error.
Means "declared, but no value assigned."
This happens when a variable is declared
Undefined undefined
but not initialized. Unlike null, undefined
is automatically assigned by JavaScript.
Used for logical operations. Often the
Boolean true, false result of comparisons or Boolean
expressions.
Key difference:
 null → explicitly means "nothing" (set by you).
 undefined → means "not yet assigned" (set by JavaScript).

Declaring Variables
JavaScript is dynamically typed, meaning:
 Variables do not have fixed types.
 A variable can hold a number, then later hold a string, then
an object.
Ways to declare:
1. Implicit declaration – assigning a value without var (not
recommended):
myVar = 42; // creates variable implicitly
2. Explicit declaration – using var (or let / const in modern
JS):

var counter, index, pi = 3.14159, quarterback = "Elway",


stop_flag = true;
If declared but not assigned, it becomes undefined.

Numeric Operators
JavaScript supports:
 Binary operators: + (add), - (subtract), * (multiply), /
(divide), % (modulus).
 Unary operators:
o + (positive sign)
o - (negation)
o ++ (increment)
o -- (decrement)
Prefix vs. Postfix
If a = 7:
 (++a) * 3 → Increment first (a=8), then multiply → 24
 (a++) * 3 → Multiply first (a=7), then increment → 21
In both cases, a ends up as 8.
Precedence & Associativity
 Precedence = which operator is applied first.
 Associativity = if same precedence, which direction is
applied.
Table:
Operators Associativity Higher precedence first
++, --, unary -, unary + Right Highest precedence
*, /, % Left
Binary +, binary - Left Lowest here
Example:
javascript

var a = 2, b = 4, c, d;

c = 3 + a * b; // * first → 3 + (2*4) = 11
d = b / a / 2; // / left → (4/2) / 2 = 1
Parentheses override precedence:
javascript

(a + b) * c // forces addition first


Automatic Conversion (Type Coercion)
JavaScript is helpful (sometimes confusingly so):
If you use a method on a primitive, JavaScript automatically
wraps it in an object temporarily so you can use object
methods.
Example:
javascript

let name = "Alice";


console.log(name.toUpperCase()); // "ALICE"

// Internally, JavaScript does:


console.log(new String("Alice").toUpperCase());
After the method runs, the wrapper object disappears, and you
still have a primitive.

The Key Difference Between Primitive and Object


 Primitive: Stored directly as a value in memory.
 Object: Stored as a reference (a pointer to where the value
and properties are stored).
Example:
javascript

let prim = 17; // primitive


let obj = new Number(17); // object

console.log(typeof prim); // "number"


console.log(typeof obj); // "object"
Even though both prim and obj “contain” the number 17, they
behave differently because one is a primitive and the other is an
object.

The Math Object


 Purpose: Gives you mathematical constants and functions.
 How you use it: You don’t create a Math object; you just
use its methods or properties directly, like Math.sin(x).
 Examples of Math methods:
o Math.sin(x) → sine of x (radians)
o Math.cos(x) → cosine of x
o Math.floor(x) → rounds down
o Math.round(x) → rounds to nearest integer
o Math.max(a, b) → returns larger of two numbers
 Example:
javascript

let angle = Math.PI / 2;


console.log(Math.sin(angle)); // 1

The Number Object


 Purpose: Stores numeric constants and provides methods
for numbers.
 Important properties:
o Number.MAX_VALUE → largest number JS can
represent.
o Number.MIN_VALUE → smallest positive number JS
can represent.
o Number.NaN → “Not a Number” special value.
o Number.POSITIVE_INFINITY → Infinity.
o Number.NEGATIVE_INFINITY → -Infinity.
o Number.PI → value of π (actually from Math, not
Number in modern JS).
 Special cases:
o Division by zero → Infinity or -Infinity.
o Invalid math operations → NaN.
o NaN is not equal to itself → you must use isNaN(x) to
check.
 Example:
javascript

let a = 0 / 0;
console.log(isNaN(a)); // true

String Catenation (+)


 If either operand of + is a string → JavaScript joins them
as strings.
javascript

"Hello " + 2025; // "Hello 2025"


 If both operands are numbers → + means addition.
Implicit Type Conversions (Coercion)
JavaScript tries to convert values automatically depending on
context:
 + with a string → number is converted to string.
javascript

"Age: " + 25 // "Age: 25"


 Numeric operators (*, /, %) force string to be converted to a
number.
javascript

"7" * 3 // 21
"abc" * 3 // NaN
 Special cases:
o null → becomes 0 in numeric context.
o undefined → becomes NaN in numeric context.

Explicit Type Conversions


You can force conversions:
 Number → String:
javascript

String(42) // "42"
(42).toString() // "42"
(42).toString(2) // "101010" (binary)
42 + "" // "42"
 String → Number:
javascript
Number("42") // 42
"42" - 0 // 42
parseInt("42px") // 42
parseFloat("3.14 meters") // 3.14

String Properties & Methods


 Strings have:
o Property: length
o Methods: .charAt(), .toUpperCase(), .substring(), etc.
 Even though strings are primitives, JS temporarily wraps
them in a String object so you can use properties/methods.
javascript

let name = "George";


console.log(name.length); // 6

We have:
javascript
var str = "George";
Now we apply different String methods in JavaScript:
1. str.charAt(2) → 'o'
o charAt() returns the character at a given index.
o Indexing starts at 0:
nginx

G e o r g e
0 1 2 3 4 5
o Index 2 → 'o'.

2. str.indexOf('r') → 3
o indexOf() returns the first position where the specified
character (or substring) occurs.
o 'r' first appears at position 3.

3. str.substring(2, 4) → 'or'
o substring(start, end) extracts characters starting from
start index up to but not including the end index.
o From index 2 to index 4 → characters at positions 2
and 3 → "or".
(Your original text said 'org' — that would actually be
str.substring(2, 5).)

4. str.toLowerCase() → 'george'
o Converts all characters in the string to lowercase.
1. typeof Operator
 Purpose: Returns a string describing the type of its
operand.
 Possible returns for primitive types:
o "number" → if operand is a number.
o "string" → if operand is a string.
o "boolean" → if operand is a boolean.
 Special cases:
o typeof null → "object" (this is a well-known quirk in
JavaScript).
o typeof undefined → "undefined".
o For variables not yet assigned a value → "undefined".
 Objects: Always return "object" regardless of what the
object contains.
 Syntax:
javascript

typeof x // no parentheses needed


typeof(x) // also works, just looks like a function

2. Assignment Statements
 Simple assignment:
javascript

a = 5;
 Compound assignment operators:
o a += 7; → a = a + 7;
o a -= 2; → a = a - 2;
o a *= 3; → a = a * 3;
o a /= 4; → a = a / 4;
 Important difference:
o Primitive values → assignment copies the actual
value.
o Objects → assignment copies only the reference
(memory address).

3. Date Object
 Create current date/time:
javascript
var today = new Date();
 Returns local time by default.
 Useful methods (local time):
Method Returns
toLocaleString() Full date/time as a readable string
getDate() Day of month (1–31)
getMonth() Month (0–11, so January = 0)
getDay() Day of week (0–6, Sunday = 0)
getFullYear() Full year (e.g., 2025)
getTime() Milliseconds since Jan 1, 1970 (Unix time)
getHours() Hour (0–23)
getMinutes() Minutes (0–59)
getSeconds() Seconds (0–59)
getMilliseconds() Milliseconds (0–999)
4. Screen Output (document.write)
 document.write() outputs directly into the HTML
document.
 Accepts HTML markup as part of its parameters.
 Can take multiple parameters, which are concatenated.
 Example:
javascript

var result = 42;


document.write("The result is: ", result, "<br />");
 writeln() adds \n, but browsers ignore newlines in HTML
display.

Dialog Boxes via Window object


 The browser's Window object contains:
o alert(message) → shows message in a dialog box with
OK.
javascript

alert("The sum is: " + sum + "\n");


o confirm(message) → shows message with OK and
Cancel, returns true or false.
o prompt(message, default) → asks for user input,
returns the entered string or null.
confirm() method in JavaScript
 Purpose: To ask the user a yes/no type of question in a
pop-up dialog box.
 Syntax:
javascript

confirm("Your message here");


 What happens:
o Shows a dialog window with:
 Your message
 Two buttons: OK and Cancel
o Returns:
 true → if the user clicks OK
 false → if the user clicks Cancel

Example from your text:


javascript

var question = confirm("Do you want to continue this


download?");
 The pop-up will appear with the text:
"Do you want to continue this download?"
 If the user clicks OK → question will be true.
 If the user clicks Cancel → question will be false.

How you might use it:


javascript

if (question) {
alert("Download will continue.");
} else {
alert("Download canceled.");
}
This way, you can let the script behave differently depending on
the user’s choice.

You might also like