0% found this document useful (0 votes)
3 views37 pages

Unit 5 - JavaScript Language

JavaScript is a versatile programming language primarily used for creating interactive web content, featuring client-side scripting, event-driven programming, and asynchronous operations. It supports object-oriented programming through prototypes and is compatible across various browsers, making it essential for modern web development. Key concepts include variables, functions, control flow, and object-oriented principles like encapsulation and inheritance.

Uploaded by

savaskv5
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)
3 views37 pages

Unit 5 - JavaScript Language

JavaScript is a versatile programming language primarily used for creating interactive web content, featuring client-side scripting, event-driven programming, and asynchronous operations. It supports object-oriented programming through prototypes and is compatible across various browsers, making it essential for modern web development. Key concepts include variables, functions, control flow, and object-oriented principles like encapsulation and inheritance.

Uploaded by

savaskv5
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

Unit - 4 PWA

Unit V: JavaScript Language


JavaScript is a versatile programming language primarily used for
creating interactive and dynamic content on web pages. Here’s an
overview of JavaScript, its key features, and its role in web
development:
Key Features of JavaScript
1. Client-Side Scripting:
○ JavaScript is primarily executed on the client-side (in the
user's browser).
○ It enhances user interactions and provides dynamic behavior
to web pages.
2. Interactivity:
○ Enables interactive elements such as dropdown menus,
form validations, sliders, and more.
○ Allows user-triggered actions (clicks, scrolls, etc.) to
dynamically modify content.
3. Event-Driven Programming:
○ JavaScript relies heavily on event-driven programming.
○ Actions (events) like clicks, scrolls, and input changes trigger
corresponding JavaScript functions.
4. Asynchronous Programming:
○ Supports asynchronous operations using callbacks,
promises, and async/await.
○ Allows non-blocking execution, making it suitable for tasks
like fetching data from servers without freezing the UI.
5. Object-Oriented and Prototype-Based:
○ JavaScript is object-oriented with support for objects,
inheritance, and prototypes.
○ Object prototypes allow objects to inherit properties and
methods from other objects.
6. Cross-Browser Compatibility:
YIASCM 2024
Unit - 4 PWA
Works across different browsers (Chrome, Firefox, Safari,

Edge, etc.) with consistent behavior.
○ Modern JavaScript (ES6+) ensures better compatibility and
performance.
7. Libraries and Frameworks:
○ Extensively used with libraries and frameworks like React,
Angular, [Link] for building complex web applications.
○ Libraries like jQuery simplify DOM manipulation and AJAX
requests.
Role in Web Development
● DOM Manipulation: JavaScript manipulates the Document
Object Model (DOM) to dynamically update HTML and CSS.
● Form Validation: Validates user input on forms before
submitting data to the server.
● AJAX: Performs Asynchronous JavaScript and XML (AJAX)
requests to fetch or send data to/from a server without reloading
the entire page.
● Animations and Effects: Creates animations and visual effects
using CSS transitions/transforms or JavaScript libraries like
GSAP (GreenSock Animation Platform).
● Frontend Frameworks: Integrates with frontend frameworks
(React, Angular, [Link]) to build single-page applications (SPAs)
and progressive web apps (PWAs).
● Server-Side Development: With [Link], JavaScript can be used
for server-side development, enabling full-stack JavaScript
development.
JavaScript Versions
● ECMAScript (ES): JavaScript is based on ECMAScript standards.
ES6 (ES2015) introduced major enhancements like arrow
functions, classes, modules, and more.
● Browser Support: Newer JavaScript features are gradually
supported across browsers. Transpilers like Babel enable

YIASCM 2024
Unit - 4 PWA
developers to use ES6+ features while ensuring compatibility with
older browsers.
Learning JavaScript
● Resources: Online tutorials, documentation (MDN Web Docs),
courses (free and paid), and community forums (Stack Overflow,
GitHub) are invaluable resources for learning JavaScript.
● Practice: Hands-on practice and building projects (e.g., simple
games, interactive forms, SPA) reinforce learning and improve
proficiency.
JavaScript’s versatility and ubiquity make it a fundamental language
for web development, offering powerful capabilities for creating modern
and interactive web experiences.
Overview and Syntax
JavaScript is a widely used programming language primarily known for
its ability to add interactivity to web pages. Here's a concise overview of
its key aspects:
Overview
JavaScript (JS):
● Purpose: Used primarily for front-end web development to make
web pages interactive and dynamic. Also used for back-end
development ([Link]) and other applications (e.g., desktop apps,
mobile apps).
● Execution Environment: Originally executed in web browsers
but now also on servers ([Link]) and other environments.
● Syntax: C-like syntax with curly braces {}, semicolons ;, and
variables defined using var, let, or const.
Syntax
Variables and Data Types

YIASCM 2024
Unit - 4 PWA
javascript
Copy code
// Variables
var x = 5; // Global scope (pre-ES6)
let y = 10; // Block-scoped variable
const z = 15; // Block-scoped constant

// Data Types
let num = 5; // Number
let str = "Hello"; // String
let bool = true; // Boolean
let arr = [1, 2, 3]; // Array
let obj = { name: "John", age: 30 }; // Object

Functions
javascript
Copy code
// Function Declaration
function greet(name) {
return "Hello, " + name + "!";
}

// Function Expression
const greet = function(name) {
return "Hello, " + name + "!";
};

// Arrow Function (ES6+)


const greet = (name) => {

YIASCM 2024
Unit - 4 PWA
return `Hello, ${name}!`;
};

Control Flow
javascript
Copy code
// if-else statement
let hour = 15;
if (hour < 18) {
greeting = "Good day";
} else {
greeting = "Good evening";
}

// for loop
for (let i = 0; i < 5; i++) {
[Link](i);
}

// while loop
let i = 0;
while (i < 5) {
[Link](i);
i++;
}

// switch statement
switch (new Date().getDay()) {
case 0:

YIASCM 2024
Unit - 4 PWA
day = "Sunday";
break;
case 1:
day = "Monday";
break;
default:
day = "Unknown";
}

Objects and Arrays


javascript
Copy code
// Object
let person = {
firstName: "John",
lastName: "Doe",
age: 30,
fullName: function() {
return [Link] + " " + [Link];
}
};

// Accessing Object Properties


[Link]([Link]); // John
[Link](person["age"]); // 30

// Array
let fruits = ["Apple", "Banana", "Cherry"];

YIASCM 2024
Unit - 4 PWA
// Accessing Array Elements
[Link](fruits[0]); // Apple
[Link]([Link]); // 3

Asynchronous Programming (Promises and async/await)


javascript
Copy code
// Promises
function fetchData() {
return new Promise((resolve, reject) => {
// Simulated async operation
setTimeout(() => {
resolve("Data fetched successfully");
}, 2000);
});
}

fetchData().then(data => {
[Link](data);
}).catch(error => {
[Link](error);
});

// async/await (ES8+)
async function fetchData() {
try {
let data = await fetchData();
[Link](data);
} catch (error) {

YIASCM 2024
Unit - 4 PWA
[Link](error);
}
}

JavaScript's flexibility and ubiquity make it a powerful language for


both front-end and back-end development. Its syntax is versatile,
supporting a wide range of programming paradigms, from procedural
to object-oriented and functional programming. As JavaScript
continues to evolve (with ES6 and beyond), new features enhance its
capabilities and improve developer productivity.

Variables and Control Statements


Variables
In JavaScript, variables are used to store data values. There are three
ways to declare variables:
var: Declares a variable globally, or locally to an entire function
regardless of block scope.
javascript
Copy code
var x = 5;

1.
Variables declared with var can be reassigned and their

scope can leak out of block statements.
let: Declares a block-scoped local variable, optionally initializing it to
a value.
javascript
Copy code
let y = 10;

2.

YIASCM 2024
Unit - 4 PWA
Introduced in ES6 (ES2015), let allows variables to have

block scope, which means they are only accessible within
the block they are defined in.
const: Declares a block-scoped read-only constant, which cannot be
reassigned.
javascript
Copy code
const z = 15;

3.
○ Also introduced in ES6, const variables must be initialized
with a value and cannot be reassigned or redeclared within
their scope.
Control Statements
Control statements in JavaScript allow you to control the flow of
execution based on conditions or loop through blocks of code.
if-else statement: Executes a block of code if a specified condition is
true; otherwise, executes another block of code.
javascript
Copy code
let hour = 15;
let greeting;

if (hour < 18) {


greeting = "Good day";
} else {
greeting = "Good evening";
}

[Link](greeting); // Output: Good day

YIASCM 2024
Unit - 4 PWA
1.
for loop: Executes a block of code a specified number of times.
javascript
Copy code
for (let i = 0; i < 5; i++) {
[Link](i);
}

// Output:
// 0
// 1
// 2
// 3
// 4

2.
while loop: Executes a block of code as long as a specified condition
is true.
javascript
Copy code
let i = 0;
while (i < 5) {
[Link](i);
i++;
}

// Output:
// 0
// 1
// 2

YIASCM 2024
Unit - 4 PWA
// 3
// 4

3.
switch statement: Evaluates an expression and executes code
associated with the matching case label.
javascript
Copy code
let day;
switch (new Date().getDay()) {
case 0:
day = "Sunday";
break;
case 1:
day = "Monday";
break;
default:
day = "Unknown";
}

[Link](day); // Output: Monday (depending on the


current day)

Understanding variables and control statements in JavaScript is


fundamental for writing effective scripts and applications. Variables
allow you to store and manipulate data, while control statements
enable you to make decisions and repeat actions based on conditions.
Mastery of these foundational concepts is crucial for becoming
proficient in JavaScript programming.

Functions and Prototypes

YIASCM 2024
Unit - 4 PWA
Functions
Functions in JavaScript are blocks of reusable code designed to
perform a specific task. They are fundamental building blocks of
JavaScript programs.
Function Declaration
There are several ways to declare functions in JavaScript:
Function Declaration:
javascript
Copy code
function greet(name) {
return "Hello, " + name + "!";
}

[Link](greet("John")); // Output: Hello, John!

1.
Function Expression:
javascript
Copy code
const greet = function(name) {
return "Hello, " + name + "!";
};

[Link](greet("Jane")); // Output: Hello, Jane!

2.
Arrow Function (ES6+):
javascript
Copy code
const greet = (name) => {

YIASCM 2024
Unit - 4 PWA
return `Hello, ${name}!`;
};

[Link](greet("Alice")); // Output: Hello, Alice!

3.
Function Parameters and Return Values
Functions can take parameters (inputs) and return values (outputs):
javascript
Copy code
function add(a, b) {
return a + b;
}

let result = add(3, 5); // result = 8

Function Scope
Variables defined inside a function are local to that function and
cannot be accessed outside of it, unless explicitly returned:
javascript
Copy code
function calculate() {
let x = 10; // local variable
return x * 2;
}

[Link](calculate()); // Output: 20
// [Link](x); // ReferenceError: x is not defined

YIASCM 2024
Unit - 4 PWA

Prototypes
Prototypes are the mechanism by which JavaScript objects inherit
features from one another. Every JavaScript object has a prototype
(except for null), which is also an object.
Prototype Chain
JavaScript objects have a prototype chain:
● Objects inherit properties and methods from their prototype.
● Prototypes inherit from other prototypes, forming a chain.

Prototypal Inheritance
In JavaScript, inheritance is achieved through prototypes rather than
classes (as in classical object-oriented languages):
javascript
Copy code
// Constructor function
function Person(name, age) {
[Link] = name;
[Link] = age;
}

// Adding a method to the prototype


[Link] = function() {
return `Hello, my name is ${[Link]} and I am
${[Link]} years old.`;
};

// Creating instances

YIASCM 2024
Unit - 4 PWA
let person1 = new Person("John", 30);
let person2 = new Person("Jane", 25);

[Link]([Link]()); // Output: Hello, my name


is John and I am 30 years old.
[Link]([Link]()); // Output: Hello, my name
is Jane and I am 25 years old.

Object Prototypes
Every JavaScript object has a prototype. For example, the prototype of
an array object has properties and methods like length, push(),
pop(), etc., which can be accessed and used by all array instances.

javascript
Copy code
let numbers = [1, 2, 3];
[Link]([Link]); // Output: 3
[Link](4);
[Link](numbers); // Output: [1, 2, 3, 4]

Functions are essential for organizing code into reusable blocks,


accepting inputs, and producing outputs. Prototypes play a crucial role
in JavaScript's object-oriented programming model, facilitating
inheritance and sharing behavior among objects. Understanding both
concepts is key to mastering JavaScript and leveraging its capabilities
effectively.

Object-oriented programming (OOP) concepts in JavaScript


Object Creation

YIASCM 2024
Unit - 4 PWA
Objects can be created using object literals {}, constructor functions,
and classes (introduced in ES6).
Object Literal:
javascript
Copy code
let person = {
firstName: "John",
lastName: "Doe",
fullName: function() {
return [Link] + " " + [Link];
}
};

Constructor Function:
javascript
Copy code
function Person(firstName, lastName) {
[Link] = firstName;
[Link] = lastName;
[Link] = function() {
return [Link] + " " + [Link];
};
}

let person1 = new Person("John", "Doe");

Class (ES6):
javascript

YIASCM 2024
Unit - 4 PWA
Copy code
class Person {
constructor(firstName, lastName) {
[Link] = firstName;
[Link] = lastName;
}

fullName() {
return `${[Link]} ${[Link]}`;
}
}

let person2 = new Person("Jane", "Smith");

2. Encapsulation
Encapsulation refers to bundling data (properties) and methods
(functions) that operate on the data into a single unit (object).
javascript
Copy code
function Person(firstName, lastName) {
let fullName = firstName + " " + lastName;

[Link] = function() {
return fullName;
};

[Link] = function(newLastName) {
lastName = newLastName;

YIASCM 2024
Unit - 4 PWA
fullName = firstName + " " + lastName;
};
}

let person = new Person("John", "Doe");


[Link]([Link]()); // Output: John Doe

[Link]("Johnson");
[Link]([Link]()); // Output: John
Johnson

3. Inheritance
JavaScript uses prototype-based inheritance, where objects can inherit
properties and methods from other objects.
Prototypal Inheritance
Every object in JavaScript has a prototype object,
● Prototype Chain:
which acts as a template for properties and methods.
● Constructor Prototype: Constructor functions have a prototype
property that can be used to add methods and properties to all
instances of an object type.
javascript
Copy code
function Person(firstName, lastName) {
[Link] = firstName;
[Link] = lastName;
}

[Link] = function() {

YIASCM 2024
Unit - 4 PWA
return [Link] + " " + [Link];
};

function Employee(firstName, lastName, position) {


[Link](this, firstName, lastName);
[Link] = position;
}

[Link] = [Link]([Link]);
[Link] = Employee;

let employee = new Employee("Jane", "Smith",


"Developer");
[Link]([Link]()); // Output: Jane Smith

4. Polymorphism
Polymorphism allows objects to be treated as instances of their parent
class or interface, while still maintaining their own specialized
behavior.
Method Overriding
javascript
Copy code
function Animal() {}
[Link] = function() {
return "Some generic sound";
};

function Dog() {}
[Link] = [Link]([Link]);

YIASCM 2024
Unit - 4 PWA
[Link] = Dog;

[Link] = function() {
return "Bark bark!";
};

let animal = new Animal();


let dog = new Dog();

[Link]([Link]()); // Output: Some generic


sound
[Link]([Link]()); // Output: Bark bark!

JavaScript's approach to OOP with prototypes offers flexibility and


dynamic behavior. Understanding these concepts helps developers
effectively design and structure applications, manage complexity, and
leverage JavaScript's powerful features for object-oriented
programming.

Callbacks, Promises, and async/await


Callbacks, Promises, and async/await are mechanisms in JavaScript
used for managing asynchronous operations and handling
asynchronous code in a more readable and maintainable way. Here's
an overview of each:
1. Callbacks
Callbacks are functions passed as arguments to another function to be
executed later when a task is completed, often used in asynchronous
programming.
Example of Callbacks:
javascript
YIASCM 2024
Unit - 4 PWA
Copy code
function fetchData(callback) {
setTimeout(() => {
callback("Data fetched successfully");
}, 2000);
}

function processData(data) {
[Link]("Processing data:", data);
}

fetchData(processData);
// Output after 2 seconds: Processing data: Data fetched
successfully

Pros:
● Simple and widely supported.
● Suitable for handling asynchronous operations.

Cons:
● Callback Hell: Nested callbacks can lead to unreadable code
(callback within callback).
2. Promises
Promises provide a more structured way to deal with asynchronous
programming, allowing chaining of operations and handling success or
failure.
Example of Promises:
javascript
Copy code
YIASCM 2024
Unit - 4 PWA
function fetchData() {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve("Data fetched successfully");
}, 2000);
});
}

fetchData()
.then(data => {
[Link]("Promise resolved:", data);
})
.catch(error => {
[Link]("Promise rejected:", error);
});
// Output after 2 seconds: Promise resolved: Data fetched
successfully

Pros:
● Mitigates callback hell with chaining .then() and .catch().
● Supports error handling through .catch().
Cons:
● Slightly more complex syntax compared to callbacks.

3. async/await
async/await is syntactic sugar built on top of promises, providing a
more concise and readable way to write asynchronous code.
Example of async/await:

YIASCM 2024
Unit - 4 PWA
javascript
Copy code
function fetchData() {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve("Data fetched successfully");
}, 2000);
});
}

async function getData() {


try {
let data = await fetchData();
[Link]("Async/await:", data);
} catch (error) {
[Link]("Async/await error:", error);
}
}

getData();
// Output after 2 seconds: Async/await: Data fetched
successfully

Pros:
● Cleaner and more readable code, resembling synchronous code.
● Error handling with try/catch blocks.

Cons:
● Requires ES8 (ES2017) or later support.

YIASCM 2024
Unit - 4 PWA
● May not handle multiple concurrent asynchronous operations as
efficiently as Promise chains.
Comparison and Usage
● Callbacks: Basic, widely supported, but prone to callback hell.
● Promises: Structured, chainable, with built-in error handling.
● async/await: Syntactic sugar for promises, improves readability
and error handling.
Choosing Between Them:
● Use callbacks for simple asynchronous operations or when
working in an environment with limited ES6+ support.
● Prefer promises for more complex async flows, chaining
operations, and handling errors.
● Use async/await for writing asynchronous code that looks
synchronous, making it easier to understand and maintain.
In modern JavaScript development, async/await is often preferred due
to its readability and ease of use, especially when dealing with complex
asynchronous workflows.
Error handling and debugging techniques
Error handling and debugging are crucial skills for JavaScript
developers to ensure their code runs smoothly and effectively. Here are
techniques and best practices for error handling and debugging in
JavaScript:
Error Handling Techniques
1. Try/Catch Blocks
Use try and catch blocks to handle errors gracefully within your code.
javascript
Copy code
try {

YIASCM 2024
Unit - 4 PWA
// Code that may throw an error
throw new Error("Something went wrong");
} catch (error) {
// Handle the error
[Link]("Error:", [Link]);
}

2. Error Object
When an error occurs, JavaScript generates an Error object
containing information about the error.
javascript
Copy code
try {
// Code that may throw an error
throw new Error("Custom error message");
} catch (error) {
[Link]("Error name:", [Link]); // Error
[Link]("Error message:", [Link]); //
Custom error message
[Link]("Stack trace:", [Link]); // Stack
trace
}

3. Throw Statement
Manually throw errors using the throw statement to indicate
exceptional conditions in your code.
javascript
Copy code
YIASCM 2024
Unit - 4 PWA
function divide(a, b) {
if (b === 0) {
throw new Error("Division by zero");
}
return a / b;
}

try {
[Link](divide(10, 0)); // Throws an error
} catch (error) {
[Link]("Error:", [Link]);
}

Debugging Techniques
1. Logging
Use [Link]() statements to output values and check the flow of
your code.
javascript
Copy code
function calculateTotal(price, quantity) {
[Link]("Calculating total...");
let total = price * quantity;
[Link]("Total:", total);
return total;
}

2. Debugging Tools

YIASCM 2024
Unit - 4 PWA
Most modern browsers come with built-in developer tools that include
debugging features:
● Chrome DevTools: Offers breakpoints, step-through debugging,
watch expressions, and more.
● Firefox Developer Tools: Provides similar debugging capabilities
to Chrome.
● Edge DevTools: Microsoft Edge also has its set of developer tools.

3. Breakpoints
Set breakpoints in your code to pause execution at specific lines and
inspect variable values.
javascript
Copy code
function calculateTotal(price, quantity) {
debugger; // Breakpoint
let total = price * quantity;
[Link]("Total:", total);
return total;
}

4. Stack Traces
When an error occurs, examine the stack trace in the console to trace
the sequence of function calls that led to the error.
javascript
Copy code
function foo() {
throw new Error("Custom error");
}

YIASCM 2024
Unit - 4 PWA
function bar() {
foo();
}

function baz() {
bar();
}

baz(); // Call to initiate the stack trace

5. Debugging Techniques
● Inspecting Network Requests: Use network tabs in developer tools to
debug AJAX requests or fetch API calls.
● Performance Profiling: Analyze code performance using profiling
tools to identify bottlenecks.
Best Practices
●Handle Errors Gracefully: Use try/catch blocks to handle
exceptions and provide meaningful error messages.
● Use Descriptive Error Messages: Provide clear and concise error
messages to aid in debugging.
● Test Edge Cases: Ensure your code handles unexpected inputs
or edge cases gracefully.
● Use Debugging Tools Effectively: Familiarize yourself with
browser developer tools and use them to debug efficiently.
● Review Stack Traces: Analyze stack traces to understand the
flow of execution leading to errors.
By applying these techniques and best practices, developers can
effectively manage errors and debug JavaScript code to improve
reliability and performance.

YIASCM 2024
Unit - 4 PWA

Introduction to popular JavaScript frameworks (e.g., React,


Angular, Vue)
JavaScript frameworks like React, Angular, and [Link] are widely used
for building interactive and dynamic user interfaces. Each framework
has its own strengths and is suited to different types of projects and
developer preferences. Here's an introduction to each of these popular
JavaScript frameworks:
1. React
Overview:
● Library vs. Framework: React is often referred to as a library
rather than a full-fledged framework. It focuses primarily on the
view layer of the application.
● Component-Based: React uses a component-based architecture
where UIs are composed of reusable components.
● Virtual DOM: React uses a virtual DOM for efficient rendering,
updating only the parts of the DOM that actually change.
● JSX: JSX is a syntax extension for JavaScript that allows
HTML-like code to be written within JavaScript.
Features:
● Declarative: React makes it easy to create interactive UIs by
using a declarative style where developers describe how the UI
should look based on the current application state.
● Component Reusability: Components are self-contained and can
be reused throughout the application.
● React Router: React Router provides routing capabilities for
single-page applications (SPAs).
● State Management: While React itself doesn't include a built-in
state management solution, tools like Redux or React's own
Context API are commonly used for managing application state.

YIASCM 2024
Unit - 4 PWA
Example:
jsx
Copy code
import React from 'react';

function App() {
return (
<div>
<h1>Hello, React!</h1>
<p>Welcome to React world.</p>
</div>
);
}

export default App;

2. Angular
Overview:
● Full-Fledged Framework: Angular is a comprehensive framework
maintained by Google. It offers a complete solution for building
client-side applications.
● MVVM Architecture: Angular follows the Model-View-ViewModel
(MVVM) architecture where components represent the View and
ViewModels manage the data and behavior.
● Two-Way Data Binding: Angular provides two-way data binding
between components and their templates, automatically
synchronizing changes in both directions.
● Dependency Injection: Angular has a powerful dependency
injection system for managing dependencies and promoting
modular code.
YIASCM 2024
Unit - 4 PWA
Features:
● Component-Based: Like React, Angular also uses a
component-based architecture.
● Directives: Angular offers built-in directives like ngIf, ngFor,
etc., for manipulating the DOM.
● RxJS Integration: Angular uses RxJS for reactive programming
and handling asynchronous operations.
● Angular CLI: Command-line interface for scaffolding and
managing Angular projects.
Example:
typescript
Copy code
import { Component } from '@angular/core';

@Component({
selector: 'app-root',
template: `
<h1>Hello, Angular!</h1>
<p>Welcome to Angular world.</p>
`
})
export class AppComponent {}

3. [Link]
Overview:
● Progressive Framework: [Link] is often described as a
progressive framework because it can be incrementally adopted
into existing projects.

YIASCM 2024
Unit - 4 PWA
Component-Based: [Link] also uses a component-based

architecture similar to React and Angular.
● Virtual DOM: [Link] utilizes a virtual DOM for efficient rendering
and updating.
● Reactivity: [Link] provides built-in reactivity, automatically
updating the UI when data changes.
Features:
● Simple and Approachable: [Link] is known for its simplicity and
ease of integration.
● Directives: [Link] provides directives like v-if, v-for, etc., for
manipulating the DOM.
● Vue Router: Vue Router provides routing capabilities for SPAs.
● Vuex: State management library inspired by Flux and Redux for
managing application state.
Example:
vue
Copy code
<template>
<div>
<h1>Hello, Vue!</h1>
<p>Welcome to Vue world.</p>
</div>
</template>

<script>
export default {
name: 'App'
}
</script>

YIASCM 2024
Unit - 4 PWA
Comparison
● React: Best for building large-scale applications with complex
state management. Provides flexibility and performance
optimizations.
● Angular: Ideal for enterprise-level applications requiring a
full-fledged framework with strong opinions on architecture and
best practices.
● [Link]: Perfect for building smaller to medium-sized applications
quickly and efficiently, known for its simplicity and ease of
learning.
Conclusion
Choosing the right JavaScript framework depends on factors like
project size, complexity, team expertise, and specific requirements.
React, Angular, and [Link] each have their own strengths and
ecosystems, catering to different needs in the JavaScript development
community.
JavaScript with HTML
Integrating JavaScript with HTML is fundamental for creating
interactive and dynamic web pages. Here's an overview of how
JavaScript can be used within HTML documents:
Inline JavaScript
Inline JavaScript refers to JavaScript code directly embedded within
HTML using <script> tags. Here's how you can include inline
JavaScript in an HTML file:
html
Copy code
<!DOCTYPE html>
<html lang="en">
<head>

YIASCM 2024
Unit - 4 PWA
<meta charset="UTF-8">
<title>JavaScript with HTML</title>
</head>
<body>

<h1>Inline JavaScript Example</h1>

<p id="demo">This text will change when you click the


button.</p>

<button onclick="changeText()">Click me</button>

<script>
function changeText() {
[Link]("demo").innerHTML =
"Button clicked!";
}
</script>

</body>
</html>

In this example:
● The onclickattribute of the button element calls the
changeText() function when the button is clicked.
● The changeText() function uses [Link]()
to locate the <p> element with id "demo" and changes its
innerHTML property to "Button clicked!".

YIASCM 2024
Unit - 4 PWA
External JavaScript
For larger applications or cleaner code organization, JavaScript code
can be placed in an external .js file and included in the HTML
document using the <script> tag:
[Link]:
javascript
Copy code
// [Link] file
function changeText() {
[Link]("demo").innerHTML = "Button
clicked!";
}

[Link]:
html
Copy code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JavaScript with HTML</title>
<script src="[Link]"></script> <!-- Include
external JavaScript file -->
</head>
<body>

<h1>External JavaScript Example</h1>

YIASCM 2024
Unit - 4 PWA
<p id="demo">This text will change when you click the
button.</p>

<button onclick="changeText()">Click me</button>

</body>
</html>

In this setup:
● The <script src="[Link]"></script> tag in the <head>
section of the HTML document includes the external JavaScript
file [Link].
● The changeText() function defined in [Link] can now be
used inline in the HTML document, similar to the inline
JavaScript example.
Best Practices
1. Separation of Concerns: Keep JavaScript separate from HTML
for better maintainability and organization.
2. Event Handling: Use event listeners (addEventListener()) for
handling events in JavaScript instead of inline event handlers
when possible.
3. DOM Manipulation: Use methods like
[Link](), [Link](),
and others to interact with HTML elements dynamically.
4. Loading Order: Ensure JavaScript files are loaded in the correct
order if they depend on one another, especially when using
external scripts.
Integrating JavaScript with HTML allows for creating dynamic and
interactive web pages. Whether using inline JavaScript or linking to
external scripts, understanding these techniques enables developers to
YIASCM 2024
Unit - 4 PWA
build powerful and responsive web applications. This foundation is
essential for mastering front-end web development with JavaScript.

YIASCM 2024

You might also like