Unit-3
JavaScript: Adding Interactivity to Web Pages
JavaScript is a high-level, interpreted programming language primarily used to make web
pages interactive and dynamic.
Fundamentals of JavaScript Programming:
o Variables and Data Types:
Variables: Containers for storing data. Declared using var, let, or
const. let and const are preferred for block-scoping and immutability
respectively.
Data Types: JavaScript is dynamically typed. Common data types
include:
Primitives: string (text), number (integers and floats), boolean
(true/false), null (intentional absence of any object value),
undefined (variable declared but no value assigned), symbol
(unique identifier), bigint (arbitrary-precision integers).
Objects: Complex data structures like Object, Array, Function,
Date, RegExp.
o Operators: Perform operations on values and variables.
Arithmetic: +, -, *, /, % (modulus), ** (exponentiation).
Assignment: =, +=, -=, etc.
Comparison: == (loose equality), === (strict equality), !=, !==, >, <,
>=, <=.
Logical: && (AND), || (OR), ! (NOT).
o Control Flow: Dictates the order in which statements are executed.
Conditional Statements: if, else if, else, switch for executing different
code blocks based on conditions.
Loops: for, while, do...while, for...in (for object properties), for...of
(for iterable objects like arrays) for repeatedly executing code.
o Functions: Reusable blocks of code that perform a specific task. Can accept
arguments and return values.
JavaScript
function greet(name) {
return `Hello, ${name}!`;
}
console.log(greet("World")); // Output: Hello, World!
o Objects and Arrays:
Objects: Collections of key-value pairs. Used to represent real-world
entities.
JavaScript
let person = {
name: "Alice",
age: 30,
isStudent: false
};
console.log(person.name); // Output: Alice
Arrays: Ordered lists of values.
JavaScript
let colors = ["red", "green", "blue"];
console.log(colors[0]); // Output: red
DOM Manipulation (Document Object Model): The DOM is a programming
interface for HTML and XML documents. It represents the page structure as a tree of
objects, allowing JavaScript to access and manipulate the content, structure, and style
of web pages.
o Selecting Elements:
document.getElementById('idName'): Selects an element by its ID.
document.getElementsByClassName('className'): Selects a collection
of elements by their class name.
document.getElementsByTagName('tagName'): Selects a collection of
elements by their tag name.
document.querySelector('selector'): Selects the first element that
matches a CSS selector.
document.querySelectorAll('selector'): Selects all elements that match
a CSS selector.
o Changing Content:
element.innerHTML: Gets or sets the HTML content inside an
element.
element.textContent: Gets or sets the text content inside an element
(sanitizes HTML).
o Modifying Attributes:
element.setAttribute('attributeName', 'value'): Sets the value of an
attribute.
element.getAttribute('attributeName'): Gets the value of an attribute.
element.removeAttribute('attributeName'): Removes an attribute.
o Changing Styles:
element.style.propertyName: Directly manipulates inline styles (e.g.,
element.style.color = 'blue').
element.classList.add('className'),
element.classList.remove('className'),
element.classList.toggle('className'): Best practice for
adding/removing/toggling CSS classes.
o Creating and Removing Elements:
document.createElement('tagName'): Creates a new HTML element.
parentNode.appendChild(childNode): Adds a child element to a parent.
parentNode.removeChild(childNode): Removes a child element from a
parent.
Event Handling: Events are actions or occurrences that happen in the browser, such
as a user clicking a button, a page loading, or an input field changing. JavaScript
allows you to respond to these events.
o Event Listeners: The primary way to handle events.
JavaScript
const button = document.getElementById('myButton');
button.addEventListener('click', function() {
alert('Button clicked!');
});
// Event object provides information about the event
button.addEventListener('mouseover', function(event) {
console.log('Mouse over at X:', event.clientX);
});
o Common Events: click, mouseover, mouseout, keydown, keyup, submit,
load, change, focus, blur.
Asynchronous Programming with Promises and async/await: JavaScript is single-
threaded, meaning it executes one task at a time. However, many operations (like
fetching data from a server) are time-consuming and would block the main thread,
making the UI unresponsive. Asynchronous programming handles these operations
without blocking.
o Callbacks (Traditional): Functions passed as arguments to be executed when
an asynchronous operation completes. Can lead to "callback hell" (deeply
nested callbacks).
o Promises (ES6): Objects that represent the eventual completion (or failure) of
an asynchronous operation and its resulting value. They provide a cleaner way
to handle asynchronous code than callbacks.
new Promise((resolve, reject) => { ... }): Creates a new promise.
resolve is called on success, reject on failure.
.then(onFulfilled, onRejected): Handles the successful resolution or
rejection of a promise.
.catch(onRejected): Handles only rejections.
.finally(): Executes a callback regardless of success or failure.
JavaScript
function fetchData() {
return new Promise((resolve, reject) => {
setTimeout(() => {
const success = true; // Simulate success/failure
if (success) {
resolve("Data fetched successfully!");
} else {
reject("Error fetching data.");
}
}, 2000);
});
}
fetchData()
.then(data => console.log(data))
.catch(error => console.error(error))
.finally(() => console.log("Operation complete."));
o async/await (ES2017): Syntactic sugar built on top of Promises, making
asynchronous code look and behave more like synchronous code. It
significantly improves readability and maintainability for complex
asynchronous flows.
async keyword: Used before a function declaration to indicate that the
function will perform asynchronous operations and implicitly returns a
Promise.
await keyword: Can only be used inside an async function. It pauses
the execution of the async function until the Promise it's waiting on
resolves or rejects.
JavaScript
async function getAndDisplayData() {
try {
const data = await fetchData(); // Wait for the promise to resolve
console.log(data);
} catch (error) {
console.error("Failed to get data:", error);
} finally {
console.log("Cleanup after async operation.");
}
}
getAndDisplayData();
IV. Web Development Tools: Essential for Workflow
Efficient web development relies heavily on a set of specialized tools.
Text Editors and IDEs (Integrated Development Environments): These are the
primary interfaces for writing code.
o Text Editors: Lightweight tools focused on code editing, often with syntax
highlighting, auto-completion, and plugin support.
VS Code (Visual Studio Code): Highly popular, free, and open-
source, with extensive extensions for various languages and
frameworks. Offers built-in Git integration and debugging.
Sublime Text: Fast, powerful, and highly customizable, but
proprietary.
Atom: Hackable text editor from GitHub.
o IDEs (Integrated Development Environments): More comprehensive tools
that bundle a text editor with a debugger, build automation tools, and often a
version control system. Typically used for larger, more complex projects.
WebStorm (JetBrains): A powerful commercial IDE specifically for
JavaScript and web development, offering advanced features like
refactoring, smart code completion, and integrated tools.
Version Control with Git: Git is a distributed version control system (VCS) that
tracks changes in source code during software development. It's essential for
collaboration, tracking history, and managing different versions of a project.
o Repositories (Repos): A project's codebase managed by Git. Can be local or
remote (e.g., GitHub, GitLab, Bitbucket).
o Commits: Snapshots of your code at a specific point in time, along with a
message describing the changes.
o Branches: Separate lines of development. Allow developers to work on
features or bug fixes independently without affecting the main codebase.
o Merging: Combining changes from one branch into another.
o Cloning: Creating a local copy of a remote repository.
o Pulling/Pushing: Fetching changes from a remote repository (pull) and
sending local changes to a remote repository (push).
o Key Commands:
git init: Initializes a new Git repository.
git add .: Stages all changes for the next commit.
git commit -m "Message": Creates a new commit.
git status: Shows the status of your working directory.
git log: Displays the commit history.
git branch: Lists, creates, or deletes branches.
git checkout <branch-name>: Switches to a different branch.
git pull: Fetches and integrates changes from a remote repository.
git push: Uploads local commits to a remote repository.
Browser Developer Tools: Modern web browsers come with built-in developer tools
that are indispensable for debugging, inspecting, and optimizing web pages.
Accessible by right-clicking on a page and selecting "Inspect" or pressing F12 (or
Cmd+Option+I on Mac).
o Elements Panel: Inspects and modifies the HTML and CSS of the current
page in real-time. Useful for debugging layout and styling issues.
o Console Panel: Displays JavaScript errors, warnings, and messages logged by
console.log(). Crucial for debugging JavaScript code.
o Sources Panel: Debugs JavaScript code by setting breakpoints, stepping
through code, and inspecting variables.
o Network Panel: Monitors network requests (e.g., fetching images, CSS,
JavaScript files, API calls), showing their status, size, and timing. Essential for
performance optimization.
o Performance Panel: Analyzes the rendering performance of a web page.
o Application Panel: Inspects local storage, session storage, cookies, and
service workers.
o Lighthouse/Audits Panel: Runs audits for performance, accessibility, best
practices, and SEO.