[Go to site: main page, start]

0% found this document useful (0 votes)
5 views30 pages

Chapter3 JavaScript Theory

Chapter 3 of the Web Technology course covers the fundamentals of JavaScript, including its history, variables, data types, operators, type conversion, conditionals, and loops. It explains key concepts such as the differences between JavaScript and Java, variable declaration methods (var, let, const), and the scope of variables. The chapter also details how JavaScript runs in browsers and various output methods for displaying data.

Uploaded by

chotaliyadev7008
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)
5 views30 pages

Chapter3 JavaScript Theory

Chapter 3 of the Web Technology course covers the fundamentals of JavaScript, including its history, variables, data types, operators, type conversion, conditionals, and loops. It explains key concepts such as the differences between JavaScript and Java, variable declaration methods (var, let, const), and the scope of variables. The chapter also details how JavaScript runs in browsers and various output methods for displaying data.

Uploaded by

chotaliyadev7008
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

WEB TECHNOLOGY

CHAPTER 3
JavaScript — Fundamentals to Loops

Complete Theory Notes with Explanations & Examples

Subject Code 3161012 — Web Technology


Semester VI | B.E. Computer / IT Engineering
University Gujarat Technological University (GTU)
Chapter 3 of 6
Coverage Introduction, Variables, Data Types, Operators, Type Conversion, Conditionals, Loops
TABLE OF CONTENTS
1. Introduction to JavaScript
1.1 What is JavaScript?
1.2 History and Evolution of JavaScript
1.3 How JavaScript Runs in the Browser
1.4 JavaScript vs Java — Key Differences
1.5 Where to Write JavaScript
1.6 JavaScript Output Methods
2. Variables and Constants
2.1 What is a Variable?
2.2 Declaring Variables — var, let, and const
2.3 var vs let vs const — Detailed Comparison
2.4 Variable Naming Rules
2.5 Scope — Global, Function, and Block
2.6 Hoisting
3. Data Types
3.1 What is a Data Type?
3.2 Primitive Data Types
3.3 The typeof Operator
3.4 Special Values — null, undefined, NaN, Infinity
3.5 Non-Primitive — Objects and Arrays (Overview)
4. Operators
4.1 Arithmetic Operators
4.2 Assignment Operators
4.3 Comparison Operators
4.4 Logical Operators
4.5 String Operators
4.6 Bitwise Operators
4.7 Ternary Operator
4.8 Operator Precedence
5. Type Conversion and Coercion
5.1 Implicit Type Coercion
5.2 Explicit Type Conversion
5.3 Truthy and Falsy Values
6. Conditional Statements
6.1 What is a Conditional Statement?
6.2 if Statement
6.3 if-else Statement
6.4 if-else if-else Ladder
6.5 Nested if Statements
6.6 switch Statement
6.7 switch vs if-else — When to Use Which
7. Loops
7.1 What is a Loop and Why Use It?
7.2 for Loop
7.3 while Loop
7.4 do-while Loop
7.5 for...in Loop
7.6 for...of Loop
7.7 break and continue Statements
7.8 Nested Loops
7.9 Comparing All Loop Types
1. Introduction to JavaScript

1.1 What is JavaScript?


JavaScript is a lightweight, interpreted, high-level programming language primarily used to make web
pages interactive and dynamic. It is one of the three core technologies of the World Wide Web, alongside
HTML (structure) and CSS (style).

While HTML tells the browser what to display and CSS tells it how to display it, JavaScript tells the browser
what to do — responding to user clicks, validating forms, fetching data from servers, animating elements,
and much more.

Key characteristics of JavaScript:


■ Interpreted — Code is executed line by line by the browser's JavaScript engine without needing
prior compilation.
■ Dynamically typed — You do not need to declare the type of a variable. The type is determined at
runtime.
■ Object-oriented — Everything in JavaScript is (or can be treated as) an object.
■ Event-driven — JavaScript responds to user actions (clicks, keystrokes, mouse movements) called
events.
■ Single-threaded — JavaScript executes one operation at a time, but uses asynchronous callbacks
and Promises to handle slow operations without freezing the browser.
■ Cross-platform — Runs in every modern browser on every operating system without any
installation.
■ Versatile — Originally browser-only, JavaScript now runs on servers ([Link]), mobile devices
(React Native), and even IoT devices.

■ JavaScript is completely unrelated to the Java programming language. The name "JavaScript" was a
marketing decision by Netscape in 1995 to capitalise on Java's popularity at the time.

1.2 History and Evolution of JavaScript


<b>Year / Version</b> <b>Key Development</b>

1995 — Created Brendan Eich at Netscape Communications creates the language in just 10 days. Initially named Mocha

1996 — Microsoft JScript Microsoft reverse-engineers JavaScript and releases JScript for Internet Explorer — creating browser in

1997 — ECMAScript 1 (ES1) JavaScript is standardised by ECMA International as ECMAScript. This creates a common specification

1999 — ES3 Adds regular expressions, try/catch error handling, and more string methods. Becomes the baseline for

2009 — ES5 Major update. Adds strict mode, JSON support, Array methods (forEach, map, filter), and [Link](

2015 — ES6 / ES2015 The biggest update in JavaScript history. Adds let/const, arrow functions, classes, template literals, dest

2016–2019 — ES7–ES10 Yearly releases adding async/await, [Link](), optional chaining, nullish coalescing, and other im

2009 — [Link] Ryan Dahl creates [Link], bringing JavaScript to the server side. JavaScript can now build full-stack w

Present JavaScript is the most widely used programming language in the world (Stack Overflow survey). Runs e

1.3 How JavaScript Runs in the Browser


Every modern web browser contains a built-in JavaScript Engine — a program that reads, compiles
(Just-In-Time), and executes JavaScript code at very high speed.
<b>Term / Concept</b> <b>Explanation</b>

V8 Engine Used by Google Chrome and [Link]. The fastest JS engine, developed by Google.

SpiderMonkey Used by Mozilla Firefox. The very first JavaScript engine, created by Brendan Eich.

JavaScriptCore Used by Apple Safari. Also called Nitro.

Chakra Used by older Microsoft Edge (before it switched to Chromium/V8).

JavaScript execution in the browser — step by step:


■ The browser downloads the HTML page and encounters a <script> tag.
■ The HTML parser pauses and hands the JavaScript source code to the JavaScript engine.
■ The engine parses the code into an Abstract Syntax Tree (AST) — a structured representation of
the code.
■ The engine compiles the AST to bytecode and then uses Just-In-Time (JIT) compilation to convert
hot code paths to native machine code for speed.
■ The machine code is executed. JavaScript can now read and modify the DOM, respond to events,
make network requests, and more.
■ After the script finishes, the HTML parser resumes.

■ Scripts placed at the bottom of the <body> tag, or using the defer or async attributes, allow the HTML
to load before JavaScript executes — improving page load speed.

1.4 JavaScript vs Java — Key Differences


<b>Feature</b> <b>JavaScript</b> <b>Java</b>

Type Scripting / interpreted language. Compiled, strongly typed OOP language.

Typing Dynamically typed. Statically typed.

Compilation Interpreted at runtime (JIT). Compiled to bytecode, run on JVM.

Run location Browser (and [Link] on server). JVM — desktop, server, Android.

Syntax Loosely C-like, flexible. Strict C-like, verbose.

Objects Prototype-based inheritance. Class-based inheritance.

Threading Single-threaded with event loop. Multi-threaded.

Use case Web pages, web apps, mobile (React Native). Enterprise apps, Android, backend.

1.5 Where to Write JavaScript


JavaScript can be included in a web page in three ways:

1. Inline JavaScript — written directly inside an HTML element's event attribute. Suitable only for very
short, simple actions. Not recommended for complex logic.
<button World!')">Click Me</button>

2. Internal JavaScript — written inside a <script> tag within the HTML file. Good for page-specific
scripts.
<html>
<head>
<title>My Page</title>
</head>
<body>
<h1>Hello</h1>
<script>
// JavaScript goes here
[Link]("Welcome to JavaScript!");
</script>
</body>
</html>

3. External JavaScript — written in a separate .js file and linked using the src attribute of the <script>
tag. This is the recommended approach for real projects because it separates concerns, enables
browser caching, and keeps HTML clean.
<!-- In HTML file -->
<script src="[Link]"></script>

/* In [Link] file */
[Link]("External JS loaded!");
[Link]("title").textContent = "Updated by JS";

1.6 JavaScript Output Methods


JavaScript provides several ways to display or output data. Each method has a specific purpose:

<b>Term / Concept</b> <b>Explanation</b>

<font name="Courier" size="9" color="#1a237e">[Link]()</font>


Prints output to the browser's developer console. The most commonly used method during develo

<font name="Courier" size="9" color="#1a237e">alert()</font>


Displays a pop-up dialog box with a message and an OK button. Blocks execution until the user cl

<font name="Courier" size="9" color="#1a237e">[Link]()</font>


Writes HTML directly into the page during the initial page load. If called after the page has loaded,

<font name="Courier" size="9" color="#1a237e">innerHTML</font>


Sets or gets the HTML content inside an element. The most common and practical way to update

<font name="Courier" size="9" color="#1a237e">textContent</font>


Sets or gets the plain text inside an element, without HTML parsing. Safer than innerHTML when d

<font name="Courier" size="9" color="#1a237e">confirm()</font>


Displays a dialog with OK and Cancel buttons. Returns true if OK is clicked, false if Cancel. Used

<font name="Courier" size="9" color="#1a237e">prompt()</font>


Displays a dialog with a text input field. Returns the text the user typed, or null if they cancelled.

// 1. Console output (developer tools)


[Link]("Hello from console!");

// 2. Alert dialog
alert("Welcome to my website!");

// 3. Update page content using innerHTML


[Link]("output").innerHTML = "<b>Updated!</b>";

// 4. Get user input


var name = prompt("What is your name?");
[Link]("greeting").textContent = "Hello, " + name;
2. Variables and Constants

2.1 What is a Variable?


A variable is a named container in the computer's memory that holds a value. You give the container a
name, and you can store a value in it, retrieve it, and change it throughout the program.

Think of a variable as a labelled box. You write a label on the box (the variable name) and you can put
something inside it (the value). Later, you can look inside to read the value, or replace it with something
new.
var age = 21; // box labelled "age" holds the value 21
var name = "Alice"; // box labelled "name" holds the string "Alice"
age = 22; // update the value in the "age" box
[Link](age); // Output: 22

2.2 Declaring Variables — var, let, and const


JavaScript provides three keywords to declare variables. Each has different behaviour regarding scope,
reassignment, and hoisting:

var — the original declaration keyword (pre-ES6, 1995–2015):


var city = "Ahmedabad";
var city = "Surat"; // OK — var allows re-declaration
city = "Vadodara"; // OK — var allows reassignment
[Link](city); // Output: Vadodara

let — introduced in ES6 (2015). Preferred for variables that will change:
let score = 10;
// let score = 20; // ERROR — let does NOT allow re-declaration
score = 20; // OK — let allows reassignment
[Link](score); // Output: 20

const — introduced in ES6 (2015). For values that never change:


const PI = 3.14159;
// PI = 3.14; // ERROR — const cannot be reassigned
// const PI = 3; // ERROR — const cannot be re-declared
[Link](PI); // Output: 3.14159

■ const does not mean the value is completely immutable. For objects and arrays declared with const, the
reference is fixed but the contents can still be changed. e.g. const arr = [1,2]; [Link](3); is valid.

2.3 var vs let vs const — Detailed Comparison


<b>Feature</b> <b>var</b> <b>let / const</b>

Introduced ES1 (1997) ES6 (2015)

Scope Function-scoped. Block-scoped (inside { }).

Re-declaration Allowed in the same scope. Not allowed in the same scope.

Reassignment Allowed. let: allowed. const: NOT allowed.

Hoisting Hoisted and initialised to undefined. Hoisted but NOT initialised (Temporal Dead Zone).

Global object Adds property to window object. Does NOT add to window object.

Recommended? Avoid in modern code. Yes — use let and const exclusively.
2.4 Variable Naming Rules
JavaScript variable names must follow specific rules:
■ Can contain letters (a–z, A–Z), digits (0–9), underscores (_), and dollar signs ($).
■ Must begin with a letter, underscore _, or dollar sign $. Cannot start with a digit.
■ Names are case-sensitive: myVar and myvar are two different variables.
■ Cannot use JavaScript reserved keywords as names (e.g. let, var, if, for, function, return).

Naming conventions:

<b>Term / Concept</b> <b>Explanation</b>

camelCase Standard for variables and functions in JavaScript. First word lowercase, subsequent words capita

PascalCase Used for class and constructor names. Every word capitalised. e.g. <font name="Courier" size="9"

UPPER_SNAKE_CASE Used for constants. All uppercase with underscores. e.g. <font name="Courier" size="9" color="#1

_prefix A leading underscore conventionally signals a private variable. e.g. <font name="Courier" size="9"

2.5 Scope — Global, Function, and Block


Scope defines where in the code a variable is accessible. JavaScript has three levels of scope:

Global Scope — Variables declared outside any function or block are globally scoped. They can be
accessed from anywhere in the entire JavaScript file.
var globalVar = "I am global";

function greet() {
[Link](globalVar); // accessible here
}
greet(); // Output: I am global
[Link](globalVar); // also accessible here

Function Scope — Variables declared with var inside a function are only accessible within that function.
They cease to exist once the function finishes.
function calcTotal() {
var total = 100; // function-scoped
[Link](total); // Output: 100
}
calcTotal();
// [Link](total); // ERROR: total is not defined here

Block Scope — Variables declared with let or const inside a block (any code between { and }) are only
accessible within that block.
if (true) {
let blockVar = "only inside this block";
const MAX = 100;
[Link](blockVar); // Output: only inside this block
}
// [Link](blockVar); // ERROR: blockVar is not defined

2.6 Hoisting
Hoisting is JavaScript's default behaviour of moving all variable and function declarations to the top of
their scope during the compilation phase — before any code is executed. Only the declaration is hoisted,
not the initialisation (value).
var hoisting: The declaration is hoisted and initialised to undefined:
[Link](x); // Output: undefined (NOT an error)
var x = 5;
[Link](x); // Output: 5

// The above code behaves as if written:


var x; // declaration hoisted to top
[Link](x); // undefined
x = 5; // initialisation stays in place
[Link](x); // 5

let and const hoisting (Temporal Dead Zone): They are hoisted but NOT initialised. Accessing them
before the declaration throws a ReferenceError.
// [Link](y); // ReferenceError: Cannot access y before init
let y = 10;
[Link](y); // Output: 10

Function hoisting: Function declarations are fully hoisted — both the name and the body. You can call a
function before it is defined in the code.
greet(); // Output: Hello! (works before declaration)

function greet() {
[Link]("Hello!");
}

■ Function expressions (var greet = function() {}) are NOT fully hoisted — only the var declaration is
hoisted (as undefined). Arrow functions behave the same way.
3. Data Types

3.1 What is a Data Type?


A data type defines what kind of value a variable can hold and what operations can be performed on it. In
JavaScript, you do not declare a type when creating a variable — the type is determined automatically
based on the value assigned. This is called dynamic typing.

JavaScript data types fall into two main categories:


■ Primitive types — simple, immutable values stored directly in the variable. There are 7 primitive
types in JavaScript.
■ Non-primitive (Reference) types — complex values stored by reference (a memory address). The
main ones are objects, arrays, and functions.

3.2 Primitive Data Types


<b>Term / Concept</b> <b>Explanation</b>

<b>Number</b> Represents all numeric values — integers and floating-point decimals. JavaScript has only one nu
Examples: <font name="Courier" size="9" color="#1a237e">42</font>, <font name="Courier" size=

<b>String</b> A sequence of characters (text). Enclosed in single quotes, double quotes, or backtick template lite
Examples: <font name="Courier" size="9" color="#1a237e">"Hello"</font>, <font name="Courier"

<b>Boolean</b> Has only two possible values: <font name="Courier" size="9" color="#1a237e">true</font> or <fon
Examples: <font name="Courier" size="9" color="#1a237e">true</font>, <font name="Courier" siz

<b>undefined</b> A variable that has been declared but not yet assigned a value automatically holds the value <font
Example: <font name="Courier" size="9" color="#1a237e">let x; // x is undefined</font>

<b>null</b> Represents the intentional absence of any value. Unlike <font name="Courier" size="9" color="#1a
Example: <font name="Courier" size="9" color="#1a237e">let user = null; // no user logged in</fon

<b>BigInt</b> For integers larger than Number can safely represent (above 2<super>53</super>-1). Created by
Example: <font name="Courier" size="9" color="#1a237e">const big = 9007199254740993n</font

<b>Symbol</b> A unique and immutable primitive value. Used as object property keys to avoid name collisions. Ra
Example: <font name="Courier" size="9" color="#1a237e">const id = Symbol("id")</font>

let age = 25; // Number


let name = "Alice"; // String
let active = true; // Boolean
let score; // undefined (not yet assigned)
let user = null; // null (intentionally empty)
let bigNum = 123456789012345678901234567890n; // BigInt
let sym = Symbol("key"); // Symbol

[Link](typeof age); // "number"


[Link](typeof name); // "string"
[Link](typeof active); // "boolean"
[Link](typeof score); // "undefined"
[Link](typeof user); // "object" <-- famous JS quirk!

3.3 The typeof Operator


The typeof operator returns a string describing the data type of a value. It is the primary way to check
types in JavaScript.

<b>Expression</b> <b>Result (string)</b>


<font name="Courier" size="9" color="#1a237e">typeof
<font name="Courier"
42</font> size="9" color="#1a237e">"number"</font>

<font name="Courier" size="9" color="#1a237e">typeof


<font name="Courier"
3.14</font> size="9" color="#1a237e">"number"</font>

<font name="Courier" size="9" color="#1a237e">typeof


<font name="Courier"
"hello"</font> size="9" color="#1a237e">"string"</font>

<font name="Courier" size="9" color="#1a237e">typeof


<font name="Courier"
true</font> size="9" color="#1a237e">"boolean"</font>

<font name="Courier" size="9" color="#1a237e">typeof


<font name="Courier"
undefined</font>size="9" color="#1a237e">"undefined"</font>

<font name="Courier" size="9" color="#1a237e">typeof


<font name="Courier"
null</font> size="9" color="#1a237e">"object"</font> ← known bug in JS

<font name="Courier" size="9" color="#1a237e">typeof


<font name="Courier"
{}</font> size="9" color="#1a237e">"object"</font>

<font name="Courier" size="9" color="#1a237e">typeof


<font name="Courier"
[]</font> size="9" color="#1a237e">"object"</font> ← arrays are objec

<font name="Courier" size="9" color="#1a237e">typeof


<font name="Courier"
function(){}</font>
size="9" color="#1a237e">"function"</font>

<font name="Courier" size="9" color="#1a237e">typeof


<font name="Courier"
Symbol()</font> size="9" color="#1a237e">"symbol"</font>

<font name="Courier" size="9" color="#1a237e">typeof


<font name="Courier"
100n</font> size="9" color="#1a237e">"bigint"</font>

3.4 Special Values — null, undefined, NaN, Infinity


<b>Term / Concept</b> <b>Explanation</b>

<font name="Courier" size="9" color="#1a237e">undefined</font>


Default value of a declared but uninitialised variable. Also returned by functions that do not explicit

<font name="Courier" size="9" color="#1a237e">null</font>


An intentional empty value. Commonly used to reset a variable or indicate "no object". Note: typeo

<font name="Courier" size="9" color="#1a237e">NaN</font>


"Not a Number". Result of an invalid mathematical operation. e.g. "hello" * 5 = NaN. Crucially: NaN

<font name="Courier" size="9" color="#1a237e">Infinity</font>


Result of dividing a positive number by zero, or a value exceeding the maximum number limit. -Inf

[Link](10 / 0); // Infinity


[Link](-5 / 0); // -Infinity
[Link]("abc" * 2); // NaN
[Link](NaN === NaN); // false (NaN is never equal to itself)
[Link](isNaN("hello")); // true
[Link](isNaN(42)); // false

let x;
[Link](x); // undefined
x = null;
[Link](x); // null

3.5 Non-Primitive — Objects and Arrays (Overview)


Objects store collections of related data as key-value pairs. They represent real-world entities.
let student = {
name: "Alice",
age: 21,
course: "Web Technology"
};
[Link]([Link]); // Output: Alice
[Link](student["age"]); // Output: 21

Arrays store ordered lists of values, indexed starting from 0.


let marks = [85, 92, 78, 96];
[Link](marks[0]); // Output: 85 (first element)
[Link]([Link]); // Output: 4
[Link](88); // Add 88 to the end
[Link](marks); // [85, 92, 78, 96, 88]
■ Objects and arrays are passed by reference. Two variables can point to the same object in memory, so
changing one affects the other.
4. Operators
An operator is a symbol or keyword that performs an operation on one or more values (called operands)
and produces a result. JavaScript has a rich set of operators grouped by their purpose.

4.1 Arithmetic Operators


Arithmetic operators perform mathematical calculations on numbers:

<b>Operator</b><b>Name</b> <b>Example and Result</b>

+ Addition 5+3 → 8

- Subtraction 10 - 4 → 6

* Multiplication 6 * 7 → 42

/ Division 15 / 4 → 3.75

% Modulus (remainder) 17 % 5 → 2

** Exponentiation 2 ** 8 → 256

++ Increment (add 1) let x=5; x++ → x becomes 6

-- Decrement (minus 1) let x=5; x-- → x becomes 4

Prefix vs Postfix increment/decrement:


let a = 5;
[Link](a++); // Output: 5 (returns THEN increments)
[Link](a); // Output: 6

let b = 5;
[Link](++b); // Output: 6 (increments THEN returns)
[Link](b); // Output: 6

Important — the + operator with strings (concatenation):


[Link]("Hello" + " " + "World"); // "Hello World"
[Link]("Age: " + 25); // "Age: 25"
[Link](10 + 20 + " items"); // "30 items"
[Link]("items: " + 10 + 20); // "items: 1020" <- order matters

4.2 Assignment Operators


Assignment operators store a value into a variable. The basic assignment operator is =. Compound
assignment operators combine assignment with an arithmetic operation as a shorthand:

<b>Operator</b><b>Equivalent To</b> <b>Example (x = 10)</b>

= x = value x = 10

+= x=x+n x += 5 → x = 15

-= x=x-n x -= 3 → x = 7

*= x=x*n x *= 2 → x = 20

/= x=x/n x /= 4 → x = 2.5

%= x=x%n x %= 3 → x = 1

**= x = x ** n x **= 2 → x = 100


4.3 Comparison Operators
Comparison operators compare two values and return a boolean result (true or false). They are used in
conditions (if statements, loops).

<b>Operator</b><b>Meaning</b> <b>Example and Result</b>

== Equal (loose — type coercion) 5 == "5" → true

=== Strictly equal (no type coercion) 5 === "5" → false

!= Not equal (loose) 5 != "5" → false

!== Strictly not equal 5 !== "5" → true

> Greater than 8>5 → true

< Less than 3<7 → true

>= Greater than or equal 5 >= 5 → true

<= Less than or equal 4 <= 3 → false

== vs === is extremely important in JavaScript:


// == (loose equality) converts types before comparing
[Link](0 == false); // true (false becomes 0)
[Link]("" == false); // true (both become 0)
[Link](null == undefined); // true

// === (strict equality) does NOT convert types


[Link](0 === false); // false (different types)
[Link](5 === 5); // true
[Link]("5" === 5); // false (string vs number)

■ Always use === (strict equality) in your code. Using == can lead to subtle bugs due to unexpected type
coercion.

4.4 Logical Operators


Logical operators combine or invert boolean expressions. They are essential for writing complex
conditions.

<b>Term / Concept</b> <b>Explanation</b>

<font name="Courier" size="9" color="#1a237e">&&</font>


Returns true only if <b>both</b>
(AND) operands are true. If the first operand is false, JavaScript short-ci
Example: <font name="Courier" size="9" color="#1a237e">(5 > 3) && (10 > 7)</font> → true

<font name="Courier" size="9" color="#1a237e">||</font>


Returns true if <b>at least
(OR)one</b> operand is true. If the first operand is true, the second is not ev
Example: <font name="Courier" size="9" color="#1a237e">(5 > 10) || (3 > 1)</font> → true

<font name="Courier" size="9" color="#1a237e">!</font>


Inverts a boolean value.
(NOT)
true becomes false, false becomes true.
Example: <font name="Courier" size="9" color="#1a237e">!(5 > 3)</font> → false

<font name="Courier" size="9" color="#1a237e">??</font>


Returns the right-hand value
(Nullish
only
Coalescing)
if the left side is <font name="Courier" size="9" color="#1a237e"
Example: <font name="Courier" size="9" color="#1a237e">let name = userInput ?? "Guest"</font>

let age = 20;


let hasID = true;

// AND: both must be true


if (age >= 18 && hasID) {
[Link]("Entry allowed"); // Output: Entry allowed
}
// OR: at least one must be true
let isAdmin = false;
let isModerator = true;
if (isAdmin || isModerator) {
[Link]("Access granted"); // Output: Access granted
}

// NOT: invert
let isLoggedOut = !true;
[Link](isLoggedOut); // false

4.5 String Operators


The + operator when used with strings performs concatenation — joining two strings together. The +=
shorthand also works for strings.
let firstName = "Alice";
let lastName = "Smith";
let fullName = firstName + " " + lastName;
[Link](fullName); // Output: Alice Smith

let msg = "Hello";


msg += " World";
[Link](msg); // Output: Hello World

// Modern approach: template literals (backticks)


let city = "Ahmedabad";
let greeting = `Welcome to ${city}!`;
[Link](greeting); // Output: Welcome to Ahmedabad!

4.6 Bitwise Operators


Bitwise operators work on the binary (bit-level) representation of integers. Each number is converted to a
32-bit binary integer, the operation is applied bit-by-bit, and the result is converted back to a regular
integer. Rarely used in web development but appear in exam questions.

<b>Operator</b><b>Name</b> <b>Example</b>

& Bitwise AND 5 & 3 → 1 (0101 & 0011 = 0001)

| Bitwise OR 5 | 3 → 7 (0101 | 0011 = 0111)

^ Bitwise XOR 5 ^ 3 → 6 (0101 ^ 0011 = 0110)

~ Bitwise NOT ~5 → -6

<< Left Shift 5 << 1 → 10 (shift bits left by 1)

>> Right Shift 5 >> 1 → 2 (shift bits right by 1)

4.7 Ternary Operator


The ternary operator (also called the conditional operator) is a compact, single-line shorthand for a
simple if-else statement. It takes three operands, hence the name "ternary".

Syntax:
condition ? valueIfTrue : valueIfFalse
// Example 1 — basic
let age = 20;
let status = (age >= 18) ? "Adult" : "Minor";
[Link](status); // Output: Adult

// Example 2 — inside output


let score = 75;
[Link]("Result: " + (score >= 50 ? "Pass" : "Fail"));
// Output: Result: Pass

// Equivalent if-else (for comparison)


if (score >= 50) {
[Link]("Pass");
} else {
[Link]("Fail");
}

■ Use the ternary operator for simple, single-value conditions. For complex logic with multiple lines, use a
regular if-else statement for readability.

4.8 Operator Precedence


Operator precedence determines the order in which operators are evaluated in an expression with
multiple operators. Higher precedence operators are evaluated first.

<b>Precedence (High → Low)</b> <b>Operators</b>

Grouping ()

Member access / Call . [] ()

Unary ! ~ ++ -- typeof void

Exponentiation **

Multiplication / Division */%

Addition / Subtraction +-

Bitwise shift << >>

Comparison < <= > >=

Equality == != === !==

Bitwise AND &

Bitwise XOR ^

Bitwise OR |

Logical AND &&

Logical OR ||

Nullish Coalescing ??

Ternary ?:

Assignment = += -= *= /= %= **=

// Without knowing precedence, this can be confusing:


[Link](2 + 3 * 4); // Output: 14 (* before +)
[Link]((2 + 3) * 4); // Output: 20 (parentheses first)
[Link](true || false && false); // true (&& before ||)
■ When in doubt, use parentheses ( ) to make the order of evaluation explicit and your code more
readable.
5. Type Conversion and Coercion
Because JavaScript is dynamically typed, values sometimes need to change from one type to another.
This happens in two ways: implicitly (automatically by JavaScript) and explicitly (deliberately by the
programmer).

5.1 Implicit Type Coercion


Type coercion happens automatically when JavaScript encounters mismatched types in an operation. It
converts one or both values behind the scenes to make the operation work. While convenient, it can
produce surprising results if not understood.

// String + Number → string concatenation


[Link]("5" + 3); // "53" (3 becomes "3")
[Link]("5" + true); // "5true"

// Number operations with strings → NaN or number


[Link]("10" - 3); // 7 ("10" becomes 10)
[Link]("10" * 2); // 20
[Link]("hello" - 1); // NaN

// Boolean in arithmetic
[Link](true + 1); // 2 (true becomes 1)
[Link](false + 5); // 5 (false becomes 0)

// Loose equality coercion (reason to use ===)


[Link](0 == false); // true
[Link]("" == false); // true
[Link](null == undefined); // true

■ The + operator triggers string coercion (if one operand is a string). The -, *, /, % operators trigger numeric
coercion. This is why "5" + 3 = "53" but "5" - 3 = 2.

5.2 Explicit Type Conversion


Explicit conversion (also called type casting) means the programmer deliberately converts a value from
one type to another using built-in functions.

Converting to Number:
[Link](Number("42")); // 42
[Link](Number("3.14")); // 3.14
[Link](Number("")); // 0
[Link](Number("hello")); // NaN
[Link](Number(true)); // 1
[Link](Number(false)); // 0
[Link](Number(null)); // 0
[Link](Number(undefined)); // NaN

// parseInt and parseFloat for strings


[Link](parseInt("42px")); // 42 (stops at non-numeric char)
[Link](parseFloat("3.14em")); // 3.14

Converting to String:
[Link](String(42)); // "42"
[Link](String(true)); // "true"
[Link](String(null)); // "null"
[Link]((42).toString()); // "42"
[Link]((255).toString(16)); // "ff" (hexadecimal)
[Link]((8).toString(2)); // "1000" (binary)

Converting to Boolean:
[Link](Boolean(1)); // true
[Link](Boolean(0)); // false
[Link](Boolean("hello")); // true
[Link](Boolean("")); // false
[Link](Boolean(null)); // false
[Link](Boolean(undefined)); // false
[Link](Boolean(NaN)); // false
[Link](Boolean([])); // true (empty array is truthy!)
[Link](Boolean({})); // true (empty object is truthy!)

5.3 Truthy and Falsy Values


In JavaScript, every value can be evaluated as either truthy (behaves like true) or falsy (behaves like
false) in a boolean context (e.g. inside an if condition). There are only six falsy values in JavaScript —
everything else is truthy.

<b>Falsy Values (only 6)</b> <b>Examples of Truthy Values</b>

<font name="Courier" size="9" color="#1a237e">false</font>


<font name="Courier" size="9" color="#1a237e">"hello"</font> (any non-empty

<font name="Courier" size="9" color="#1a237e">0</font>


<fontand
name="Courier"
<font name="Courier"
size="9" color="#1a237e">42</font>
size="9" color="#1a237e">-0</font>
(any non-zero numb

<font name="Courier" size="9" color="#1a237e">0n</font>


<font name="Courier"
(BigInt zero) size="9" color="#1a237e">"0"</font> (string with zero is t

<font name="Courier" size="9" color="#1a237e">""</font>


<font(empty
name="Courier"
string) size="9" color="#1a237e">[]</font> (empty array is truthy

<font name="Courier" size="9" color="#1a237e">null</font>


<font name="Courier" size="9" color="#1a237e">{}</font> (empty object is truth

<font name="Courier" size="9" color="#1a237e">undefined</font>


<font name="Courier" size="9" color="#1a237e">function(){}</font> (any functio

<font name="Courier" size="9" color="#1a237e">NaN</font>

// Truthy/falsy in if conditions
let username = "";
if (username) {
[Link]("Welcome, " + username);
} else {
[Link]("Please enter a username."); // This runs (empty string is falsy)
}

let items = [1, 2, 3];


if (items) {
[Link]("Array exists"); // This runs (array is truthy even if empty)
}
6. Conditional Statements

6.1 What is a Conditional Statement?


A conditional statement allows a program to make decisions — to execute different blocks of code
depending on whether a condition is true or false. Without conditionals, a program would always do the
same thing regardless of input or state.

Think of a conditional as a fork in the road. The program checks a condition, and based on the result, it
takes one path or the other.

6.2 if Statement
The if statement is the most basic conditional. It executes a block of code only if the specified condition
evaluates to true. If the condition is false, the block is skipped entirely.

Syntax:
if (condition) {
// code to run if condition is true
}

let temperature = 38;

if (temperature > 37) {


[Link]("You have a fever. Please rest.");
}
// Output: You have a fever. Please rest.

let marks = 45;


if (marks >= 50) {
[Link]("You passed!");
}
// Nothing is printed because 45 >= 50 is false

6.3 if-else Statement


The if-else statement adds an alternative block of code that runs when the condition is false. One of the
two blocks will always execute.

Syntax:
if (condition) {
// runs if condition is true
} else {
// runs if condition is false
}

let age = 16;

if (age >= 18) {


[Link]("You are eligible to vote.");
} else {
[Link]("You are not eligible to vote yet.");
}
// Output: You are not eligible to vote yet.
// Another example — grade checker
let score = 72;
if (score >= 50) {
[Link]("Result: PASS");
} else {
[Link]("Result: FAIL");
}
// Output: Result: PASS

6.4 if-else if-else Ladder


When there are more than two possible outcomes, we chain multiple conditions using else if.
JavaScript checks each condition from top to bottom and executes the first block whose condition is true. If
none match, the final else block runs.

Syntax:
if (condition1) {
// runs if condition1 is true
} else if (condition2) {
// runs if condition1 is false AND condition2 is true
} else if (condition3) {
// runs if conditions 1 and 2 are false AND condition3 is true
} else {
// runs if ALL conditions above are false
}

let marks = 78;

if (marks >= 90) {


[Link]("Grade: A+");
} else if (marks >= 80) {
[Link]("Grade: A");
} else if (marks >= 70) {
[Link]("Grade: B");
} else if (marks >= 60) {
[Link]("Grade: C");
} else if (marks >= 50) {
[Link]("Grade: D");
} else {
[Link]("Grade: F (Fail)");
}
// Output: Grade: B (78 >= 70 is the first true condition)

6.5 Nested if Statements


A nested if is an if statement placed inside another if or else block. This allows checking multiple
conditions in a hierarchy — an inner condition is only checked if the outer condition is already true.
let age = 20;
let hasLicense = true;

if (age >= 18) {


// This block runs because age >= 18
if (hasLicense) {
// Inner check only runs if outer check passed
[Link]("You can drive a car.");
} else {
[Link]("You are old enough but need a license.");
}
} else {
[Link]("You must be 18 or older to drive.");
}
// Output: You can drive a car.

■ Avoid deep nesting (more than 2–3 levels). Deeply nested conditions become hard to read and maintain.
Consider using logical operators (&&, ||) or early returns to flatten the structure.

6.6 switch Statement


The switch statement is used when a single variable or expression needs to be compared against
multiple specific values. It is cleaner and more readable than a long if-else if chain when comparing one
variable to many possible values.

Syntax:
switch (expression) {
case value1:
// code if expression === value1
break;
case value2:
// code if expression === value2
break;
default:
// code if no case matched
}

let day = 3;

switch (day) {
case 1:
[Link]("Monday");
break;
case 2:
[Link]("Tuesday");
break;
case 3:
[Link]("Wednesday");
break;
case 4:
[Link]("Thursday");
break;
case 5:
[Link]("Friday");
break;
default:
[Link]("Weekend");
}
// Output: Wednesday

Fall-through behaviour: If a break statement is omitted, execution "falls through" to the next case. This
can be used intentionally to group multiple cases that share the same code:
let month = 4; // April

switch (month) {
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
[Link]("31 days");
break;
case 4:
case 6:
case 9:
case 11:
[Link]("30 days");
break;
case 2:
[Link]("28 or 29 days");
break;
}
// Output: 30 days

■ switch uses strict equality (===) for comparison, just like ===. Always include break statements unless
fall-through is intentional.

6.7 switch vs if-else — When to Use Which


<b>Aspect</b> <b>switch</b> <b>if-else</b>

Best for Comparing one variable to many fixed values. Ranges, multiple variables, or complex expressions.

Comparison Uses === (strict equality). Any comparison operator (<, >, >=, <=, ===, etc.).

Readability Cleaner for 5+ fixed value checks. Cleaner for 2–3 conditions.

Ranges Cannot handle ranges directly (e.g. marks >= 90).


Handles ranges naturally.

Fall-through Supported (intentional or accidental). No fall-through — each block is independent.

Default Uses default keyword for unmatched values. Uses final else for unmatched conditions.
7. Loops

7.1 What is a Loop and Why Use It?


A loop is a control structure that repeats a block of code multiple times. Instead of writing the same code
100 times, you write it once inside a loop and tell the loop how many times to repeat it.

Without a loop — printing 1 to 5:


[Link](1);
[Link](2);
[Link](3);
[Link](4);
[Link](5);

With a loop — the same result in 3 lines:


for (let i = 1; i <= 5; i++) {
[Link](i);
}

Loops are essential for: processing lists of data, reading all rows from a database, repeating an action until
a condition changes, traversing arrays, and building tables in HTML.

7.2 for Loop


The for loop is used when you know exactly how many times the loop should run. It is the most
commonly used loop in JavaScript.

Syntax:
for (initialisation; condition; update) {
// body — runs each time condition is true
}

<b>Term / Concept</b> <b>Explanation</b>

<b>Initialisation</b> Executes once before the loop starts. Typically declares and sets a counter variable. e.g. <font na

<b>Condition</b> Checked before every iteration. If true, the body executes. If false, the loop ends. e.g. <font name=

<b>Update</b> Executes after each iteration. Typically increments or decrements the counter. e.g. <font name="C

// Example 1: Print 1 to 10
for (let i = 1; i <= 10; i++) {
[Link](i);
}
// Output: 1 2 3 4 5 6 7 8 9 10

// Example 2: Sum of 1 to 100


let sum = 0;
for (let i = 1; i <= 100; i++) {
sum += i;
}
[Link]("Sum:", sum); // Output: Sum: 5050

// Example 3: Loop over an array


let fruits = ["Apple", "Banana", "Cherry"];
for (let i = 0; i < [Link]; i++) {
[Link](i + ": " + fruits[i]);
}
// Output:
// 0: Apple
// 1: Banana
// 2: Cherry

// Example 4: Count backwards (decrement)


for (let i = 5; i >= 1; i--) {
[Link](i);
}
// Output: 5 4 3 2 1

7.3 while Loop


The while loop repeats as long as a condition remains true. Use it when you do not know in advance
how many times the loop should run — the number of iterations depends on a condition that changes
during execution.

Syntax:
while (condition) {
// body — runs while condition is true
// IMPORTANT: the condition must eventually become false
// to avoid an infinite loop
}

// Example 1: Basic while loop


let i = 1;
while (i <= 5) {
[Link]("Count: " + i);
i++; // update — moves toward ending the loop
}
// Output: Count: 1, Count: 2, Count: 3, Count: 4, Count: 5

// Example 2: Sum until total exceeds 100


let total = 0;
let num = 1;
while (total <= 100) {
total += num;
num++;
}
[Link]("Total exceeded 100 at num:", num - 1);

// Example 3: User input simulation


// (In a real browser this would use prompt())
let password = "wrong";
let attempts = 0;
while (password !== "secret123" && attempts < 3) {
password = "wrong"; // simulating wrong input
attempts++;
}
[Link]("Attempts used:", attempts);

■ Always ensure the loop body contains an update that moves the condition toward false. Forgetting this
creates an infinite loop that crashes the browser tab.
7.4 do-while Loop
The do-while loop is similar to the while loop, with one critical difference: the body executes at least
once, even if the condition is false from the beginning. The condition is checked after the first execution.

Syntax:
do {
// body — runs at least once
} while (condition); // semicolon is required

// Example 1: Basic do-while


let i = 1;
do {
[Link]("i = " + i);
i++;
} while (i <= 5);
// Output: i = 1, i = 2, i = 3, i = 4, i = 5

// Example 2: Condition is false from the start


let x = 10;
do {
[Link]("This runs once, x = " + x);
x++;
} while (x < 5);
// Output: This runs once, x = 10
// (the body executed once even though 10 < 5 is false)

// Example 3: Menu-driven simulation


let choice;
do {
choice = 0; // Simulating user entering 0 to exit
[Link]("Menu shown to user. Choice: " + choice);
} while (choice !== 0);
// Output: Menu shown to user. Choice: 0 (shown once)

When to use do-while: Ideal for menu-driven programs where the menu must be displayed at least once,
input validation loops where the user must enter data at least once, and any situation where the first
execution must happen unconditionally.

7.5 for...in Loop


The for...in loop iterates over the enumerable properties (keys) of an object. Each iteration gives the
next property key as a string. It is designed specifically for objects.

Syntax:
for (let key in object) {
// key = property name (string)
// object[key] = property value
}

// Example 1: Iterating over object properties


let student = {
name: "Alice",
age: 21,
course: "Web Technology",
marks: 88
};

for (let key in student) {


[Link](key + " : " + student[key]);
}
// Output:
// name : Alice
// age : 21
// course : Web Technology
// marks : 88

// Example 2: Using for...in on an array (possible but not recommended)


let arr = ["a", "b", "c"];
for (let index in arr) {
[Link](index + " -> " + arr[index]);
}
// Output: 0 -> a, 1 -> b, 2 -> c

■ Avoid using for...in to iterate arrays. It iterates over property keys (as strings "0","1","2") and may also
include inherited properties. Use for...of or a regular for loop for arrays.

7.6 for...of Loop


The for...of loop (introduced in ES6) iterates over the values of any iterable object — arrays, strings,
Maps, Sets, and more. It is the cleanest way to loop through an array.

Syntax:
for (let value of iterable) {
// value = next item in the iterable
}

// Example 1: Looping over an array


let fruits = ["Apple", "Banana", "Cherry", "Date"];
for (let fruit of fruits) {
[Link](fruit);
}
// Output: Apple Banana Cherry Date

// Example 2: Looping over a string (character by character)


let word = "HELLO";
for (let char of word) {
[Link](char);
}
// Output: H E L L O

// Example 3: Sum of array values


let prices = [120, 350, 80, 210];
let total = 0;
for (let price of prices) {
total += price;
}
[Link]("Total: " + total); // Output: Total: 760

7.7 break and continue Statements


Two special statements can alter the normal flow of any loop:

break — immediately terminates the loop and jumps to the first statement after the loop. Use it when you
find what you were looking for and no longer need to continue.
// Find the first even number in an array
let nums = [3, 7, 9, 4, 11, 6];
for (let n of nums) {
if (n % 2 === 0) {
[Link]("First even number: " + n);
break; // stop the loop immediately
}
}
// Output: First even number: 4

continue — skips the rest of the current iteration and moves to the next one. The loop does NOT stop — it
just skips one cycle.
// Print only odd numbers from 1 to 10
for (let i = 1; i <= 10; i++) {
if (i % 2 === 0) {
continue; // skip even numbers
}
[Link](i);
}
// Output: 1 3 5 7 9

// Skip a specific value


let items = ["apple", "banana", "poison", "cherry"];
for (let item of items) {
if (item === "poison") {
continue; // skip this one
}
[Link]("Eating: " + item);
}
// Output: Eating: apple Eating: banana Eating: cherry

7.8 Nested Loops


A nested loop is a loop placed inside another loop. The inner loop runs completely for every single
iteration of the outer loop. Nested loops are commonly used to work with 2-dimensional data (tables,
matrices, multiplication tables).
// Example 1: Multiplication table (1 to 3)
for (let i = 1; i <= 3; i++) {
for (let j = 1; j <= 3; j++) {
[Link](i + " x " + j + " = " + (i * j));
}
}
// Output:
// 1 x 1 = 1, 1 x 2 = 2, 1 x 3 = 3
// 2 x 1 = 2, 2 x 2 = 4, 2 x 3 = 6
// 3 x 1 = 3, 3 x 2 = 6, 3 x 3 = 9

// Example 2: Star pattern


for (let row = 1; row <= 4; row++) {
let line = "";
for (let col = 1; col <= row; col++) {
line += "* ";
}
[Link](line);
}
// Output:
// *
// * *
// * * *
// * * * *

■ Be careful with nested loops — the total number of iterations is the outer count multiplied by the inner
count. Three nested loops over 100 items each = 1,000,000 iterations. This can slow the browser
significantly.

7.9 Comparing All Loop Types


<b>Loop Type</b><b>When to Use</b> <b>Key Characteristic</b>

for Known number of iterations. Iterating arrays by index.


Counter is initialised, checked, and updated in one line.

while Unknown number of iterations. Loop until a condition


Condition
changes.
checked BEFORE each iteration. May never run.

do-while Must execute at least once. Menu-driven programs.


Condition checked AFTER each iteration. Always runs once.

for...in Iterate over object property keys. Gives keys (as strings). Avoid for arrays.

for...of Iterate over array values, strings, or other iterables.


Gives values directly. Cleaner than index-based for loop.
— End of Chapter 3 (Part 1: Introduction to Loops) —
Subject: Web Technology (3161012) | Chapter 3: JavaScript
Semester VI — B.E. Computer / IT Engineering — GTU
Reference: MDN Web Docs | ECMAScript Specification | JavaScript: The Good Parts — Douglas
Crockford

You might also like