JavaScript Advanced Topics - Exam Theory
1. JavaScript and Objects
What is JavaScript?
JavaScript is a high-level, interpreted, object-oriented programming language primarily used for client-
side web development. It was created by Brendan Eich in 1995 at Netscape Communications.
Object-Oriented Nature of JavaScript:
JavaScript is fundamentally an object-based language where almost everything is an object or can be
treated as an object.
Key Characteristics:
Dynamic Language: Variables and objects can be modified at runtime
Prototype-based: Objects can inherit directly from other objects
Loosely Typed: Variables don't need explicit type declarations
First-class Functions: Functions are objects and can be manipulated like any other object
Event-driven: Responds to user interactions and system events
Objects in JavaScript:
Definition:
Objects are collections of key-value pairs where keys are strings (properties) and values can be any
data type including functions (methods).
Object Creation Methods:
1. Object Literal Notation:
javascript
let student = {
name: "John",
age: 20,
grade: "A",
study: function() {
return this.name + " is studying";
}
};
2. Object Constructor:
javascript
let student = new Object();
student.name = "John";
student.age = 20;
student.study = function() {
return this.name + " is studying";
};
3. Constructor Function:
javascript
function Student(name, age, grade) {
this.name = name;
this.age = age;
this.grade = grade;
this.study = function() {
return this.name + " is studying";
};
}
let student1 = new Student("John", 20, "A");
Object Properties and Methods:
Properties: Store data/state of the object
Methods: Functions that operate on object data
Property Access:
Dot notation: object.property
Bracket notation: object["property"]
Dynamic Properties: Can add/delete properties at runtime
Object Characteristics:
Objects are reference types
Objects are mutable
Objects can contain other objects (composition)
Objects support inheritance through prototypes
2. JavaScript's Own Objects
Built-in Global Objects:
JavaScript provides several built-in objects that are available globally and provide essential
functionality.
Core Built-in Objects:
1. Object:
Purpose: Base object for all JavaScript objects
Key Methods:
Object.keys() : Returns array of object's property names
Object.values() : Returns array of object's values
Object.assign() : Copies properties from source to target
Object.create() : Creates new object with specified prototype
2. Array:
Purpose: Stores ordered collections of elements
Key Properties: length
Key Methods:
Mutating: push() , pop() , shift() , unshift() , splice()
Non-mutating: slice() , concat() , join()
Iteration: forEach() , map() , filter() , reduce()
Search: indexOf() , find() , includes()
3. String:
Purpose: Manipulates text data
Key Properties: length
Key Methods:
charAt() : Returns character at index
substring() , substr() , slice() : Extract portions
indexOf() , search() : Find text
replace() : Replace text
split() : Convert to array
toUpperCase() , toLowerCase() : Change case
4. Number:
Purpose: Handles numeric operations
Static Properties: Number.MAX_VALUE , Number.MIN_VALUE , Number.NaN
Key Methods:
toString() : Convert to string
toFixed() : Format decimal places
parseInt() , parseFloat() : Parse strings to numbers
5. Math:
Purpose: Mathematical operations and constants
Properties: Math.PI , Math.E
Key Methods:
Math.round() , Math.floor() , Math.ceil() : Rounding
Math.max() , Math.min() : Find extremes
Math.random() : Generate random numbers
Math.pow() , Math.sqrt() : Power and square root
6. Date:
Purpose: Handle dates and times
Creation: new Date() , new Date(year, month, day)
Key Methods:
getFullYear() , getMonth() , getDate() : Get components
setFullYear() , setMonth() , setDate() : Set components
toString() , toDateString() : Convert to string
getTime() : Get timestamp
7. Boolean:
Purpose: Logical operations
Values: true , false
Methods: toString() , valueOf()
8. Function:
Purpose: Create and manipulate functions
Properties: length (number of parameters), name
Methods: call() , apply() , bind()
9. RegExp:
Purpose: Pattern matching with regular expressions
Creation: /pattern/flags or new RegExp(pattern, flags)
Methods: test() , exec()
Global Functions:
parseInt() : Parse string to integer
parseFloat() : Parse string to float
isNaN() : Check if value is NaN
isFinite() : Check if value is finite
eval() : Execute JavaScript code from string
3. The DOM and Web Browser Environment
What is DOM?
The Document Object Model (DOM) is a platform and language-neutral interface that represents
HTML/XML documents as a tree structure of objects that can be manipulated with JavaScript.
DOM Structure:
Document: Root of the DOM tree
Elements: HTML tags represented as objects
Attributes: Properties of HTML elements
Text: Content within elements
Comments: HTML comments
DOM Tree Hierarchy:
Document
└── html
├── head
│ ├── title
│ └── meta
└── body
├── div
├── p
└── script
DOM Object Types:
1. Document Object:
Purpose: Represents the entire HTML document
Key Properties: title , URL , domain
Key Methods:
getElementById() : Select element by ID
getElementsByClassName() : Select elements by class
getElementsByTagName() : Select elements by tag
querySelector() : Select first matching element
querySelectorAll() : Select all matching elements
createElement() : Create new element
write() : Write content to document
2. Element Object:
Purpose: Represents HTML elements
Key Properties: innerHTML , textContent , id , className
Key Methods:
getAttribute() , setAttribute() : Handle attributes
appendChild() : Add child element
removeChild() : Remove child element
addEventListener() : Add event listener
3. Window Object:
Purpose: Represents browser window
Key Properties: location , navigator , screen , history
Key Methods:
alert() , confirm() , prompt() : User interaction
setTimeout() , setInterval() : Timing functions
open() , close() : Window manipulation
Web Browser Environment Objects:
1. Navigator Object:
Purpose: Information about browser
Properties: userAgent , platform , language , cookieEnabled
2. Location Object:
Purpose: Information about current URL
Properties: href , hostname , pathname , search
Methods: reload() , replace()
3. History Object:
Purpose: Browser's session history
Methods: back() , forward() , go()
4. Screen Object:
Purpose: Information about user's screen
Properties: width , height , colorDepth
DOM Manipulation:
Selecting Elements:
javascript
// By ID
let element = document.getElementById("myId");
// By Class
let elements = document.getElementsByClassName("myClass");
// By Tag
let paragraphs = document.getElementsByTagName("p");
// CSS Selectors
let element = document.querySelector("#myId");
let elements = document.querySelectorAll(".myClass");
Modifying Elements:
javascript
// Change content
element.innerHTML = "<strong>Bold text</strong>";
element.textContent = "Plain text";
// Change attributes
element.setAttribute("src", "image.jpg");
element.id = "newId";
// Change styles
element.style.color = "red";
element.style.backgroundColor = "yellow";
Creating and Adding Elements:
javascript
// Create element
let newDiv = document.createElement("div");
newDiv.textContent = "New content";
// Add to document
document.body.appendChild(newDiv);
Event Handling:
Events are actions that occur in the browser (clicks, loads, etc.)
Common Events:
Mouse Events: click , mouseover , mouseout
Keyboard Events: keydown , keyup , keypress
Form Events: submit , change , focus , blur
Window Events: load , resize , scroll
Event Handling Methods:
javascript
// Method 1: Event handler property
element.onclick = function() {
alert("Clicked!");
};
// Method 2: addEventListener (recommended)
element.addEventListener("click", function() {
alert("Clicked!");
});
4. Forms and Validations
HTML Forms in JavaScript:
Forms are used to collect user input and send it to a server. JavaScript can validate and manipulate
form data before submission.
Form Object:
The form element is represented as a Form object in JavaScript with properties and methods for
manipulation.
Accessing Forms:
Methods to Access Forms:
javascript
// By name attribute
let form = document.forms["formName"];
// By index
let form = document.forms[0];
// By ID
let form = document.getElementById("formId");
Form Properties:
elements: Collection of all form controls
length: Number of form elements
name: Form's name attribute
action: Form's action attribute (URL)
method: Form's method (GET/POST)
Form Methods:
submit(): Submit form programmatically
reset(): Reset form to initial values
Form Elements:
1. Input Elements:
Text Input: <input type="text">
Password: <input type="password">
Email: <input type="email">
Number: <input type="number">
Checkbox: <input type="checkbox">
Radio: <input type="radio">
Submit: <input type="submit">
2. Other Form Elements:
Textarea: <textarea></textarea>
Select: <select><option></option></select>
Button: <button></button>
Accessing Form Element Values:
javascript
// Text input
let name = document.getElementById("nameInput").value;
// Checkbox
let isChecked = document.getElementById("checkbox").checked;
// Radio button
let radioValue = document.querySelector('input[name="gender"]:checked').value;
// Select dropdown
let selectedValue = document.getElementById("selectList").value;
Form Validation:
Purpose of Validation:
Ensure data quality and completeness
Provide immediate feedback to users
Reduce server load by catching errors early
Improve user experience
Types of Validation:
1. Client-Side Validation:
Performed using JavaScript in the browser
Immediate feedback to users
Cannot be relied upon alone (can be bypassed)
2. Server-Side Validation:
Performed on the server
More secure and reliable
Required for data integrity
JavaScript Form Validation Techniques:
1. Basic Validation Functions:
javascript
function validateRequired(field) {
return field.value.trim() !== "";
}
function validateEmail(email) {
let emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return emailRegex.test(email.value);
}
function validateLength(field, minLength) {
return field.value.length >= minLength;
}
2. Form Validation Example:
javascript
function validateForm() {
let name = document.getElementById("name");
let email = document.getElementById("email");
let password = document.getElementById("password");
// Validate name
if (!validateRequired(name)) {
alert("Name is required");
name.focus();
return false;
}
// Validate email
if (!validateEmail(email)) {
alert("Please enter valid email");
email.focus();
return false;
}
// Validate password
if (!validateLength(password, 6)) {
alert("Password must be at least 6 characters");
password.focus();
return false;
}
return true;
}
Form Events:
Important Form Events:
submit: When form is submitted
reset: When form is reset
change: When form element value changes
input: When user types in input field
focus: When element receives focus
blur: When element loses focus
Event Handling:
javascript
// Prevent form submission if validation fails
document.getElementById("myForm").addEventListener("submit", function(event) {
if (!validateForm()) {
event.preventDefault(); // Stop form submission
}
});
// Real-time validation
document.getElementById("email").addEventListener("blur", function() {
if (!validateEmail(this)) {
this.style.borderColor = "red";
} else {
this.style.borderColor = "green";
}
});
Common Validation Patterns:
1. Required Field Validation:
javascript
function isRequired(field) {
return field.value.trim() !== "";
}
2. Email Validation:
javascript
function isValidEmail(email) {
let pattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$/;
return pattern.test(email);
}
3. Phone Number Validation:
javascript
function isValidPhone(phone) {
let pattern = /^\d{10}$/;
return pattern.test(phone);
}
4. Password Strength Validation:
javascript
function isStrongPassword(password) {
// At least 8 characters, one uppercase, one lowercase, one number
let pattern = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d@$!%*?&]{8,}$/;
return pattern.test(password);
}
Form Validation Best Practices:
1. Validate on both client and server side
2. Provide clear error messages
3. Validate in real-time when possible
4. Use appropriate input types (email, number, etc.)
5. Focus on the first invalid field
6. Use regular expressions for pattern matching
7. Sanitize input data
8. Provide visual feedback (colors, icons)
Advantages of Form Validation:
Improves data quality
Enhances user experience
Reduces server load
Prevents common input errors
Provides immediate feedback
Limitations of Client-Side Validation:
Can be disabled by users
Can be bypassed
Should not be the only validation
Requires JavaScript to be enabled