0% found this document useful (0 votes)
2 views34 pages

JS Study Notes

This document provides comprehensive study notes on JavaScript, covering its origin, components, execution environment, and capabilities. It includes details on embedding JavaScript in HTML, syntax basics, data types, operators, type conversion, and built-in objects. The notes are designed for beginners and include code examples to illustrate key concepts.

Uploaded by

vimif59418
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)
2 views34 pages

JS Study Notes

This document provides comprehensive study notes on JavaScript, covering its origin, components, execution environment, and capabilities. It includes details on embedding JavaScript in HTML, syntax basics, data types, operators, type conversion, and built-in objects. The notes are designed for beginners and include code examples to illustrate key concepts.

Uploaded by

vimif59418
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

JavaScript

Complete Study Notes


Based on Chapter 4 — Programming the World Wide Web
With full code examples for beginners
1. What is JavaScript?
1.1 Origin & Background
JavaScript was originally developed by Netscape as LiveScript. In 1995, it was jointly developed
with Sun Microsystems and renamed JavaScript. It is standardised by ECMA as ECMA-262
(also called ECMAScript), and is supported by all major browsers.

1.2 Three Components of JavaScript


• Core — the heart of the language (syntax, operators, objects, functions)
• Client-side — library of objects for browser control and user interaction (this is what you
will mostly use)
• Server-side — library of objects for use in web servers (e.g., [Link])

1.3 Where JavaScript Runs


When you open a web page, the browser downloads the HTML file. Any JavaScript in that file is
executed by the browser's JavaScript engine. This means JavaScript runs on the user's
computer (client-side), not on the web server.
📝 Note: Modern browsers all use ECMAScript Edition 5 or later. Chrome uses V8, Firefox uses
SpiderMonkey, and Safari uses Nitro.

1.4 What Can JavaScript Do?


• Validate form data before sending it to the server
• Modify HTML content and CSS styles dynamically
• Respond to user events (clicks, keypresses, mouse movements)
• Create richer interfaces than plain HTML/CSS
• Make requests to a server without reloading the page (AJAX)

1.5 Difference Between Java and JavaScript


Java JavaScript
Strongly typed (variables have fixed types) Dynamically typed (variables can change type)
Has true classes and inheritance Prototype-based, no true classes (pre-ES6)
Compiled to bytecode Interpreted by browser
Objects are static Objects are dynamic (properties added at
runtime)
2. Embedding JavaScript in HTML
2.1 The <script> Tag
JavaScript is placed inside a <script> tag in an HTML document. You can place it in two
locations:
• Inside <head> — runs when called, or responds to events
• Inside <body> — runs once as the page loads

2.2 Method 1: Direct Embedding


<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
// Your JavaScript code goes here
alert("Hello, World!");
</script>
</head>
<body>
<p>This is my web page.</p>
</body>
</html>

2.3 Method 2: External File (Preferred)


Create a separate .js file and link it with the src attribute. This keeps your HTML clean and lets
you reuse the same JS across multiple pages.
<!-- In your HTML file -->
<script type="text/javascript" src="[Link]"></script>

<!-- [Link] contains your JavaScript code -->

2.4 Output Methods


[Link]() — writes directly into the HTML page as it loads.
alert() — pops up a dialog box with a message.

// Writing to the page


[Link]("<h2>Hello from JavaScript!</h2>");
[Link]("<br />"); // Use <br /> for line breaks in HTML output

// Alert dialog box


alert("Welcome to my page!");
alert("Sum is: " + 42 + "\n"); // \n = new line inside alert
3. Syntax Basics
3.1 Identifiers (Variable Names)

• Can contain letters, digits, $, and _
• Are case-sensitive: myVar and myvar are different
• Cannot be a reserved word (like: break, case, catch, if, else, for, while, return, etc.)

Valid examples:
var myName;
var _privateVar;
var $price;
var firstName;
var count1;

Invalid examples:
var 1count; // Cannot start with a digit
var my-name; // Hyphens not allowed
var if; // Reserved word

3.2 Comments
// This is a single-line comment

/*
This is a
multi-line comment
*/

3.3 Semicolons
Statements can end with a semicolon (;). JavaScript will insert one automatically if you leave it
out — but this can sometimes cause unexpected bugs. Always use semicolons for clarity.
⚠ Warning: Be careful when splitting statements across lines. JavaScript may insert a semicolon
where you don't want one. For example, a return statement followed by a value on the next line will
return undefined.

// Correct — return value on SAME line


function getX() {
return 42;
}

// WRONG — JavaScript inserts semicolon after return!


function getX() {
return // <- semicolon inserted here, returns undefined
42;
}
4. Data Types and Variables
4.1 The Five Primitive Types
Type Example Values Notes
Number 42, 3.14, -7, 1E2 Stored as 64-bit floating point
String "hello", 'world' Single or double quotes, no difference
Boolean true, false Lowercase only
Undefined undefined Variable declared but not assigned
Null null Deliberate empty value; causes error if used

4.2 Declaring Variables


JavaScript is dynamically typed — a variable can hold any type of value, and can change type
at runtime. Declare variables using the var keyword.
var counter; // Declared, value is undefined
var index = 0; // Declared and assigned a number
var pi = 3.14159;
var name = "Surya"; // String
var isActive = true; // Boolean

// Multiple variables in one statement


var a, b, c;
var x = 1, y = 2, z = 3;

4.3 Number Literals


Numbers can be written as integers, decimals, or in scientific notation (exponent form). They
can also be written in hexadecimal (base 16) by starting with 0x.
var a = 12; // Integer
var b = 1.2; // Decimal
var c = .12; // Also decimal (0.12)
var d = 1E2; // Scientific: 1 × 10² = 100
var e = 1.5e-3; // 0.0015
var f = 0xFF; // Hexadecimal: 255 in decimal

4.4 String Literals


Strings are sequences of characters. You can use single or double quotes — they behave the
same. Use escape sequences for special characters.
var greeting = "Hello, World!";
var name = 'Surya';
// Escape sequences
var msg1 = "She said \"hello\""; // She said "hello"
var msg2 = 'It\'s a test'; // It's a test
var msg3 = "Line 1\nLine 2"; // \n = new line
var msg4 = "Tab\there"; // \t = tab
var empty = ""; // Empty string

4.5 Primitive vs. Object Storage


Primitive values are stored directly in memory (nonheap). Objects are stored in heap memory
and accessed via a reference. This distinction matters when passing values to functions.
var prim = 17; // Value 17 stored directly
var obj = new Number(17); // Reference pointing to 17 in heap
5. Operators
5.1 Arithmetic Operators
var a = 10, b = 3;

[Link](a + b); // 13 (addition)


[Link](a - b); // 7 (subtraction)
[Link](a * b); // 30 (multiplication)
[Link](a / b); // 3.333... (division)
[Link](a % b); // 1 (modulus — remainder)

// Increment and Decrement


var x = 5;
x++; // x is now 6 (post-increment)
++x; // x is now 7 (pre-increment)
x--; // x is now 6 (post-decrement)

// Difference between pre and post


var a = 3;
var result1 = (++a) * 3; // a becomes 4 first, then 4*3 = 12
var a = 3;
var result2 = (a++) * 3; // 3*3 = 9, then a becomes 4

5.2 Operator Precedence (Highest to Lowest)


Operators Associativity
++, --, unary minus (-x) Right to left
*, /, % Left to right
+, - Left to right
>, <, >=, <= Left to right
==, != Left to right
===, !== Left to right
&& Left to right
|| Left to right
=, +=, -=, *=, /=, %= Right to left

Example demonstrating precedence:


var a = 2, b = 4;
var c = 3 + a * b; // * first: 3 + 8 = 11 (not 20)
var d = b / a / 2; // Left-to-right: (4/2)/2 = 1 (not 4)
5.3 Assignment Operators
var x = 10;
x += 5; // x = x + 5 → 15
x -= 3; // x = x - 3 → 12
x *= 2; // x = x * 2 → 24
x /= 4; // x = x / 4 → 6
x %= 4; // x = x % 4 → 2

5.4 Comparison Operators


// == checks value only (with type conversion)
3 == '3' // true — string '3' is converted to number

// === checks value AND type (no conversion)


3 === '3' // false — different types
3 === 3 // true

// != and !== work the same way


3 != '3' // false (values are equal after conversion)
3 !== '3' // true (types differ)

// Other comparisons
5 > 3 // true
5 < 3 // false
5 >= 5 // true
5 <= 4 // false

📝 Note: Always prefer === and !== to avoid unexpected type-conversion bugs.

5.5 Logical Operators


var a = true, b = false;

a && b // AND: true only if BOTH are true → false


a || b // OR: true if AT LEAST one is true → true
!a // NOT: flips the value → false

// Short-circuit evaluation
false && someFunction() // someFunction never called!
true || someFunction() // someFunction never called!

5.6 The typeof Operator


Returns a string describing the type of a value.
typeof 42 // "number"
typeof "hello" // "string"
typeof true // "boolean"
typeof undefined // "undefined"
typeof null // "object" ← this is a known quirk!
typeof {} // "object"
typeof function(){} // "function"

// Two syntax forms — both are valid


typeof x
typeof(x)
6. Type Conversion
6.1 Implicit (Automatic) Conversion
JavaScript automatically converts types in many situations. Understanding this is critical to
avoid bugs.
// String + Number → String concatenation
"August " + 1977 // "August 1977"
"Age: " + 25 // "Age: 25"

// Number * String → Multiplication


7 * "3" // 21 (string converted to number)

// Booleans in numeric context


null + 1 // 1 (null converts to 0)
undefined + 1 // NaN (undefined becomes NaN)

// Boolean context
// These are FALSY (treated as false):
// 0, "", null, undefined, NaN, false

// These are TRUTHY (treated as true):


// Any non-zero number, any non-empty string, objects
// NOTE: the STRING "0" is truthy!
if ("0") { /* this RUNS */ }

6.2 Explicit Conversion


// Convert to String
var n = 42;
var s1 = String(n); // "42"
var s2 = n + ""; // "42" (concatenate with empty string)

// Convert to Number
var str = "3.14";
var num1 = Number(str); // 3.14
var num2 = str - 0; // 3.14 (subtract 0 trick)

// parseInt and parseFloat


parseInt("42px") // 42 (stops at non-numeric char)
parseFloat("3.14abc") // 3.14
parseInt("abc") // NaN

// Convert to Boolean
Boolean(0) // false
Boolean("") // false
Boolean("hello") // true
Boolean(42) // true
7. Built-in Objects
7.1 The Math Object
The Math object provides mathematical constants and functions. Always prefix with Math.
[Link] // 3.14159265...
Math.E // 2.71828...

[Link](-5) // 5 (absolute value)


[Link](16) // 4 (square root)
[Link](2, 8) // 256 (2 to the power 8)
[Link](3.9) // 3 (round down)
[Link](3.1) // 4 (round up)
[Link](3.5) // 4 (round to nearest)
[Link](5, 2, 8, 1) // 8 (largest value)
[Link](5, 2, 8, 1) // 1 (smallest value)
[Link]() // Random number between 0.0 and 1.0

// Random integer between 1 and 10:


var rand = [Link]([Link]() * 10) + 1;

// Trigonometry
[Link]([Link] / 2) // 1
[Link](0) // 1

7.2 The Number Object


Number.MAX_VALUE // Largest number JS can hold
Number.MIN_VALUE // Smallest positive number
[Link] // Not a Number
Number.POSITIVE_INFINITY // Infinity
Number.NEGATIVE_INFINITY // -Infinity

// Check for NaN (never use ==, always use isNaN())


isNaN(NaN) // true
isNaN(42) // false
isNaN('hello') // true

// Convert number to string


var n = 3.14159;
[Link]() // "3.14159"
[Link](2) // "3.14" (2 decimal places)

7.3 The String Object


Strings have many useful methods. Remember: positions start at index 0.
var str = "Hello, World!";
// Property
[Link] // 13

// Methods
[Link](0) // "H"
[Link](7) // "W"
[Link]("World") // 7 (position of first match)
[Link]("xyz") // -1 (not found)

[Link](7, 12) // "World" (from pos 7 up to but not including 12)


[Link]() // "hello, world!"
[Link]() // "HELLO, WORLD!"

// String concatenation
var first = "Hello";
var second = " World";
var combined = first + second; // "Hello World"

7.4 The Date Object


The Date object represents a specific point in time.
// Create a Date for right now
var now = new Date();

// Create a specific date


var d = new Date(2024, 0, 15); // Jan 15, 2024 (months are 0-indexed!)

// Extract parts
[Link]() // e.g., 2024
[Link]() // 0–11 (0 = January, 11 = December!)
[Link]() // 1–31 (day of month)
[Link]() // 0–6 (0 = Sunday, 6 = Saturday)
[Link]() // 0–23
[Link]() // 0–59
[Link]() // 0–59
[Link]() // Milliseconds since Jan 1, 1970

// Display as readable string


[Link]() // "4/13/2024, 2:30:00 PM"

// Timing code execution


var start = new Date();
// ... some code ...
var end = new Date();
var ms = [Link]() - [Link]();
[Link]("Took: " + ms + " milliseconds");

📝 Note: Months in JavaScript are zero-indexed: January = 0, February = 1, ..., December = 11.
This is a common source of bugs!
8. User Input and Output
8.1 Output: [Link]()
[Link]("Hello from JavaScript!");
[Link]("<br />"); // HTML line break
[Link]("<b>Bold text</b>");
[Link]("Sum = " + (3 + 4)); // Sum = 7

8.2 Output: alert()


Opens a pop-up dialog. Since it is not HTML, use \n instead of <br />.
alert("Hello!");
alert("Name: " + name + "\nAge: " + age);

8.3 Input: prompt()


Opens a dialog with a text field. The user types something and clicks OK. The method returns
the text as a string.
var name = prompt("What is your name?", "");
// First argument: message to show
// Second argument: default text in the input box

alert("Hello, " + name + "!");

8.4 Input: confirm()


Shows a message with OK and Cancel buttons. Returns true if OK is clicked, false if Cancel.
var answer = confirm("Do you want to continue?");
if (answer === true) {
[Link]("User clicked OK");
} else {
[Link]("User clicked Cancel");
}

8.5 Complete Example: Simple Calculator


<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function calculate() {
var num1 = Number(prompt("Enter first number:", ""));
var num2 = Number(prompt("Enter second number:", ""));
var sum = num1 + num2;
alert("The sum of " + num1 + " and " + num2 + " is: " + sum);
}
</script>
</head>
<body>
<button onclick="calculate()">Click to Add Numbers</button>
</body>
</html>
9. Control Statements
9.1 if / else if / else
var score = 85;

if (score >= 90) {


[Link]("Grade: A");
} else if (score >= 80) {
[Link]("Grade: B");
} else if (score >= 70) {
[Link]("Grade: C");
} else {
[Link]("Grade: F");
}

9.2 switch Statement


Use switch when comparing one value against many possible values.
var day = 3;

switch (day) {
case 1:
[Link]("Monday");
break;
case 2:
[Link]("Tuesday");
break;
case 3:
[Link]("Wednesday");
break;
default:
[Link]("Other day");
break;
}
// Output: Wednesday

⚠ Warning: Always include break; at the end of each case. Without it, execution 'falls through' to the
next case automatically.

9.3 while Loop


Repeats as long as the condition is true. The condition is checked BEFORE each iteration.
var count = 1;

while (count <= 5) {


[Link]("Count: " + count + "<br />");
count++;
}
// Output: Count: 1, Count: 2, ..., Count: 5

9.4 for Loop


The most common loop. Has init, condition, and increment all in one line.
for (var i = 0; i < 5; i++) {
[Link]("i = " + i + "<br />");
}
// Output: i = 0, i = 1, i = 2, i = 3, i = 4

// Counting down
for (var i = 10; i >= 0; i--) {
[Link](i + " ");
}
// Output: 10 9 8 7 6 5 4 3 2 1 0

// Sum of 1 to 100
var sum = 0;
for (var i = 1; i <= 100; i++) {
sum += i;
}
[Link]("Sum = " + sum); // Sum = 5050

9.5 do...while Loop


The body runs at LEAST once, because the condition is checked AFTER each iteration.
var num;
do {
num = Number(prompt("Enter a positive number:", ""));
} while (num <= 0);

[Link]("You entered: " + num);

9.6 Loops vs. Each Other — Quick Reference


Loop When to Use Condition Checked
while Unknown number of iterations Before each iteration
for Known number of iterations Before each iteration
do...while Must run at least once After each iteration
10. Objects
10.1 What is an Object?
An object is a collection of related data (properties) and functions (methods). Think of it as a
named container for related values.

10.2 Creating Objects


// Method 1: Using new Object()
var student = new Object();
[Link] = "Surya";
[Link] = 42;
[Link] = "A";

// Method 2: Object literal (shorter and preferred)


var student = {
name: "Surya",
roll: 42,
grade: "A"
};

// Accessing properties
[Link]([Link]); // Dot notation
[Link](student["name"]); // Bracket notation

10.3 Nested Objects


var car = {
make: "Ford",
model: "Mustang",
engine: {
config: "V8",
hp: 450
}
};

[Link]([Link]); // 450

10.4 Dynamic Properties


JavaScript objects are dynamic. You can add or remove properties after the object is created.
var car = { make: "Ford" };

// Add new properties any time


[Link] = "Mustang";
[Link] = 2024;
// Delete a property
delete [Link];

// Access undefined property → returns undefined


[Link]([Link]); // undefined

10.5 The for-in Loop (Iterating Object Properties)


var student = { name: "Surya", roll: 42, grade: "A" };

for (var prop in student) {


[Link](prop + " = " + student[prop] + "<br />");
}
// Output:
// name = Surya
// roll = 42
// grade = A
11. Arrays
11.1 What is an Array?
An array is an ordered list of values. Unlike some languages, JavaScript arrays can hold values
of mixed types, and can grow or shrink dynamically. Array indices start at 0.

11.2 Creating Arrays


// Method 1: Array literal (preferred)
var fruits = ["apple", "banana", "cherry"];

// Method 2: new Array()


var nums = new Array(10, 20, 30);

// Method 3: Empty array then fill


var list = [];
list[0] = "first";
list[1] = "second";

// Mixed types in one array (allowed in JS)


var mixed = [42, "hello", true, null];

11.3 Accessing & Modifying Elements


var colors = ["red", "green", "blue"];

[Link](colors[0]); // "red"
[Link](colors[1]); // "green"
[Link](colors[2]); // "blue"
[Link](colors[3]); // undefined

// Length property
[Link]([Link]); // 3

// Modify an element
colors[1] = "yellow"; // ["red", "yellow", "blue"]

// Extending the array


colors[5] = "purple"; // length becomes 6, indices 3 and 4 are empty

11.4 Looping Through an Array


var fruits = ["apple", "banana", "cherry"];

// Standard for loop


for (var i = 0; i < [Link]; i++) {
[Link](fruits[i] + "<br />");
}

// for-in loop (gives the index, not value)


for (var index in fruits) {
[Link](index + ": " + fruits[index] + "<br />");
}

11.5 Array Methods


Method What it Does Example
join() Joins elements into a string [1,2,3].join("-") → "1-2-3"
reverse() Reverses the array in place [1,2,3].reverse() → [3,2,1]
sort() Sorts alphabetically by default ["b","a","c"].sort() → ["a","b","c"]
concat() Joins two arrays [1,2].concat([3,4]) → [1,2,3,4]
slice() Returns a sub-array [1,2,3,4].slice(1,3) → [2,3]
push() Adds to end [1,2].push(3) → [1,2,3]
pop() Removes from end [1,2,3].pop() → removes 3
shift() Removes from beginning [1,2,3].shift() → removes 1
unshift() Adds to beginning [2,3].unshift(1) → [1,2,3]

var list = ["first", "second", "third"];

// push / pop (work at the END)


[Link]("fourth"); // ["first", "second", "third", "fourth"]
var last = [Link](); // removes "fourth", last = "fourth"

// shift / unshift (work at the BEGINNING)


var head = [Link](); // removes "first"
[Link]("zero", "first"); // adds at beginning

// Sorting numbers (must supply comparator!)


var nums = [10, 5, 3, 8, 1];
[Link](function(a, b) { return a - b; }); // [1, 3, 5, 8, 10]

11.6 Two-Dimensional Arrays


// An array of arrays
var matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
[Link](matrix[0][0]); // 1
[Link](matrix[1][2]); // 6
[Link](matrix[2][1]); // 8

// Iterate over a 2D array


for (var r = 0; r < [Link]; r++) {
for (var c = 0; c < matrix[r].length; c++) {
[Link](matrix[r][c] + " ");
}
[Link]("<br />");
}
12. Functions
12.1 Defining and Calling Functions
// Define a function
function greet(name) {
[Link]("Hello, " + name + "!<br />");
}

// Call the function


greet("Surya"); // Hello, Surya!
greet("World"); // Hello, World!

12.2 Return Values


function add(a, b) {
return a + b;
}

var result = add(10, 5); // 15


[Link](result);
[Link](add(3, 4)); // 7

// Without return, function returns undefined


function sayHi() {
[Link]("Hi!");
// no return statement
}
var x = sayHi(); // x is undefined

12.3 Variable Scope


The scope of a variable is the region of code where it is visible.
var globalVar = "I am global"; // Visible everywhere

function myFunc() {
var localVar = "I am local"; // Only visible inside myFunc
[Link](globalVar); // Works fine
[Link](localVar); // Works fine
}

myFunc();
[Link](globalVar); // Works fine
[Link](localVar); // ERROR: localVar is not defined

// If you forget var, it becomes global (bad practice!)


function bad() {
accidentalGlobal = "oops"; // No var — global scope!
}

12.4 Parameters and Arguments


Parameters in the function header are called formal parameters. The values passed in the call
are actual parameters (arguments). JavaScript does not check the number or type of
arguments.
function greet(name, greeting) {
[Link](greeting + ", " + name + "!<br />");
}

greet("Surya", "Hello"); // Hello, Surya!


greet("Surya"); // undefined, Surya! (greeting is undefined)
greet("A", "B", "C"); // "C" is ignored — extra args are OK

// Arguments object — access all passed arguments


function showAll() {
for (var i = 0; i < [Link]; i++) {
[Link](arguments[i] + "<br />");
}
}
showAll(1, 2, 3, "four"); // Prints each argument

12.5 Pass by Value vs. Objects


// Primitives — passed by VALUE (copy)
function increment(n) {
n += 1; // Only modifies local copy
}
var x = 5;
increment(x);
[Link](x); // Still 5 — original unchanged

// Objects/Arrays — the REFERENCE is passed


function addItem(arr) {
[Link]("new"); // Modifies the ORIGINAL array
}
var myList = ["a", "b"];
addItem(myList);
[Link](myList); // ["a", "b", "new"]

// But reassigning doesn't affect the original


function replace(arr) {
arr = ["x", "y"]; // Only changes local reference
}
replace(myList);
[Link](myList); // Still ["a", "b", "new"]
12.6 Constructor Functions (Creating Custom Objects)
A constructor is a function used with the new keyword to create and initialize objects.
// Define a constructor
function Student(name, roll, grade) {
[Link] = name;
[Link] = roll;
[Link] = grade;
[Link] = function() {
[Link]("Name: " + [Link] + ", Roll: " + [Link] + "<br />");
};
}

// Create objects using new


var s1 = new Student("Surya", 42, "A");
var s2 = new Student("Priya", 17, "B");

[Link](); // Name: Surya, Roll: 42


[Link](); // Name: Priya, Roll: 17

[Link]([Link]); // Surya
13. Regular Expressions
13.1 What are Regular Expressions?
A regular expression (regex) is a pattern used to search for, match, or replace text in strings. In
JavaScript, patterns are written between forward slashes /pattern/.

13.2 Basic Pattern Syntax


Pattern Meaning Example Match
/hello/ Exact text match "say hello there"
. Any character except newline /f.r/ matches "for", "far", "fir"
[abc] Any one of: a, b, or c /[aeiou]/ matches any vowel
[a-z] Any lowercase letter [A-Z] = uppercase, [0-9] = digit
[^abc] NOT a, b, or c /[^0-9]/ = not a digit
\d Any digit [0-9] /\d/ matches "5" in "abc5"
\D Non-digit /\D/ matches "a" in "a5"
\w Word char [A-Za-z0-9_] /\w+/ matches words
\s Whitespace (space, tab, newline) /\s/ matches any space
\b Word boundary /\bis\b/ matches 'is' not 'this'
^ Start of string /^Hello/ must start with Hello
$ End of string /world$/ must end with world

13.3 Quantifiers (Repetition)


Symbol Meaning Example
* Zero or more /bo*/ matches "b", "bo", "boo"
+ One or more /bo+/ matches "bo", "boo" (not "b")
? Zero or one /colou?r/ matches "color" or "colour"
{n} Exactly n times /\d{4}/ matches exactly 4 digits
{n,m} Between n and m times /\d{2,4}/ matches 2, 3, or 4 digits

13.4 Pattern Modifiers (Flags)


// i — case-insensitive
/apple/[Link]("I love Apple pie") // true
// g — global (find ALL matches, not just first)
"aabaa".match(/a/g) // ["a", "a", "a", "a"]

13.5 Using Regex with String Methods


var str = "Rabbits are furry animals";

// search() — returns position of first match, or -1


var pos = [Link](/bits/);
[Link](pos); // 3

// test() — returns true or false


var result = /furry/.test(str);
[Link](result); // true

// match() — returns array of matches


var matches = [Link](/[aeiou]/g); // All vowels
[Link]([Link]); // Count of vowels

// replace() — replace matches


var newStr = [Link](/furry/, "fluffy");
[Link](newStr); // Rabbits are fluffy animals

// split() — split string at pattern


var words = [Link](/ /);
[Link](words[0]); // "Rabbits"

13.6 Practical: Form Validation Examples


// Validate an email address (basic)
function isValidEmail(email) {
return /^[\w]+@[\w]+\.[a-z]{2,4}$/.test(email);
}

// Validate a phone number (Indian mobile: 10 digits)


function isValidPhone(phone) {
return /^[6-9]\d{9}$/.test(phone);
}

// Check if string has only letters


function isAlpha(str) {
return /^[A-Za-z]+$/.test(str);
}

// Example usage
var email = prompt("Enter email:", "");
if (isValidEmail(email)) {
alert("Valid email!");
} else {
alert("Invalid email. Please try again.");
}
14. Complete Frontend + Backend-Style Examples
14.1 Example: Student Grade Calculator (Frontend)
This is a complete HTML page with embedded JavaScript that calculates a student's grade
based on marks entered.
<!DOCTYPE html>
<html>
<head>
<title>Grade Calculator</title>
<style>
body { font-family: Arial; max-width: 500px; margin: 40px auto; }
input { width: 100%; padding: 8px; margin: 8px 0; }
button { background: #2E75B6; color: white; padding: 10px 20px;
border: none; cursor: pointer; font-size: 16px; }
#result { margin-top: 20px; font-size: 18px; font-weight: bold; }
</style>
<script type="text/javascript">
function calculateGrade() {
var name = [Link]("name").value;
var marks = Number([Link]("marks").value);
var grade, msg;

if (isNaN(marks) || marks < 0 || marks > 100) {


alert("Please enter a valid mark between 0 and 100.");
return;
}

if (marks >= 90) { grade = "A+"; msg = "Excellent!"; }


else if (marks >= 80) { grade = "A"; msg = "Very Good!"; }
else if (marks >= 70) { grade = "B"; msg = "Good"; }
else if (marks >= 60) { grade = "C"; msg = "Average"; }
else if (marks >= 50) { grade = "D"; msg = "Pass"; }
else { grade = "F"; msg = "Fail"; }

var output = name + " scored " + marks + "% — Grade: " + grade + " (" + msg
+ ")";
[Link]("result").innerHTML = output;
}
</script>
</head>
<body>
<h2>Student Grade Calculator</h2>
<label>Student Name:</label>
<input type="text" id="name" placeholder="Enter name" />
<label>Marks (0–100):</label>
<input type="number" id="marks" placeholder="Enter marks" />
<button onclick="calculateGrade()">Calculate Grade</button>
<div id="result"></div>
</body>
</html>
14.2 Example: To-Do List (Frontend with Arrays)
<!DOCTYPE html>
<html>
<head>
<title>To-Do List</title>
<style>
body { font-family: Arial; max-width: 400px; margin: 40px auto; }
li { margin: 6px 0; }
button { margin-left: 10px; cursor: pointer; }
</style>
<script type="text/javascript">
var tasks = [];

function addTask() {
var input = [Link]("taskInput");
var task = [Link]();
if (task === "") {
alert("Please enter a task!");
return;
}
[Link](task);
[Link] = "";
renderList();
}

function removeTask(index) {
[Link](index, 1);
renderList();
}

function renderList() {
var ul = [Link]("taskList");
[Link] = "";
for (var i = 0; i < [Link]; i++) {
[Link] += "<li>" + tasks[i]
+ " <button onclick='removeTask(" + i + ")'>Remove</button></li>";
}
}
</script>
</head>
<body>
<h2>My To-Do List</h2>
<input type="text" id="taskInput" placeholder="Enter a task" />
<button onclick="addTask()">Add Task</button>
<ul id="taskList"></ul>
</body>
</html>

14.3 Example: Form Validation (Regex + Functions)


<!DOCTYPE html>
<html>
<head>
<title>Registration Form</title>
<style>
body { font-family: Arial; max-width: 500px; margin: 40px auto; }
label { display: block; margin-top: 12px; font-weight: bold; }
input { width: 100%; padding: 8px; box-sizing: border-box; }
.error { color: red; font-size: 13px; }
.ok { color: green; font-size: 13px; }
button { margin-top: 16px; background: #1F4788; color: white;
padding: 10px 24px; border: none; cursor: pointer; }
</style>
<script type="text/javascript">
function validate() {
var name = [Link]("name").[Link]();
var email = [Link]("email").[Link]();
var phone = [Link]("phone").[Link]();
var pass = [Link]("pass").value;
var ok = true;

// Name: only letters, at least 2 chars


if (!/^[A-Za-z ]{2,}$/.test(name)) {
[Link]("nameErr").innerHTML = "Only letters, min 2
characters";
ok = false;
} else {
[Link]("nameErr").innerHTML = "✓";
[Link]("nameErr").className = "ok";
}

// Email
if (!/^[\w.-]+@[\w.-]+\.[a-z]{2,}$/.test(email)) {
[Link]("emailErr").innerHTML = "Enter a valid email";
ok = false;
} else {
[Link]("emailErr").innerHTML = "✓";
[Link]("emailErr").className = "ok";
}

// Phone: 10 digits
if (!/^\d{10}$/.test(phone)) {
[Link]("phoneErr").innerHTML = "Phone must be 10 digits";
ok = false;
} else {
[Link]("phoneErr").innerHTML = "✓";
[Link]("phoneErr").className = "ok";
}

// Password: at least 8 characters


if ([Link] < 8) {
[Link]("passErr").innerHTML = "Minimum 8 characters";
ok = false;
} else {
[Link]("passErr").innerHTML = "✓";
[Link]("passErr").className = "ok";
}
if (ok) {
alert("Form submitted successfully!");
}
}
</script>
</head>
<body>
<h2>Registration Form</h2>
<label>Full Name</label>
<input type="text" id="name" placeholder="Your full name" />
<span id="nameErr" class="error"></span>

<label>Email</label>
<input type="text" id="email" placeholder="user@[Link]" />
<span id="emailErr" class="error"></span>

<label>Phone Number</label>
<input type="text" id="phone" placeholder="10-digit number" />
<span id="phoneErr" class="error"></span>

<label>Password</label>
<input type="password" id="pass" placeholder="Minimum 8 characters" />
<span id="passErr" class="error"></span>

<button onclick="validate()">Register</button>
</body>
</html>
15. Quick Reference Cheat Sheet
15.1 Common Patterns for Exams / Assignments
// 1. Read input, convert, display
var x = Number(prompt("Enter number:", ""));
alert("You entered: " + x);

// 2. Loop and sum


var sum = 0;
for (var i = 1; i <= n; i++) { sum += i; }

// 3. Find max in array


var nums = [3, 7, 1, 9, 4];
var max = nums[0];
for (var i = 1; i < [Link]; i++) {
if (nums[i] > max) max = nums[i];
}

// 4. Factorial
function factorial(n) {
if (n <= 1) return 1;
return n * factorial(n - 1); // Recursive
}

// 5. Check if string contains substring


"hello world".indexOf("world") !== -1 // true

// 6. Access form field value


var val = [Link]("myInput").value;

// 7. Update page content


[Link]("result").innerHTML = "New content";

15.2 Falsy and Truthy Values


Falsy (treated as false) Truthy (treated as true)
false true
0 (zero) Any non-zero number
"" (empty string) Any non-empty string (including "0"!)
null Any object
undefined Any array (even empty [])
NaN Any function

15.3 Common Errors and How to Avoid Them


Common Mistake Fix
Using = instead of == in if if (x === 5) not if (x = 5)
Off-by-one in loops Arrays start at 0; use i < [Link]
Forgetting break in switch Always add break; after each case
Month is 0-indexed in Date January = 0, so add 1 when displaying
prompt() returns a string Use Number() to convert before math
== vs === Prefer === to avoid unexpected conversions
Modifying array while looping Loop backwards or use a copy

— End of Study Notes —

You might also like