Unit 5 - JavaScript Language
Unit 5 - JavaScript Language
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 + "!";
};
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";
}
// Array
let fruits = ["Apple", "Banana", "Cherry"];
YIASCM 2024
Unit - 4 PWA
// Accessing Array Elements
[Link](fruits[0]); // Apple
[Link]([Link]); // 3
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);
}
}
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;
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";
}
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 + "!";
}
1.
Function Expression:
javascript
Copy code
const greet = function(name) {
return "Hello, " + name + "!";
};
2.
Arrow Function (ES6+):
javascript
Copy code
const greet = (name) => {
YIASCM 2024
Unit - 4 PWA
return `Hello, ${name}!`;
};
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;
}
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;
}
// Creating instances
YIASCM 2024
Unit - 4 PWA
let person1 = new Person("John", 30);
let person2 = new Person("Jane", 25);
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]
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];
};
}
Class (ES6):
javascript
YIASCM 2024
Unit - 4 PWA
Copy code
class Person {
constructor(firstName, lastName) {
[Link] = firstName;
[Link] = lastName;
}
fullName() {
return `${[Link]} ${[Link]}`;
}
}
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;
};
}
[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];
};
[Link] = [Link]([Link]);
[Link] = Employee;
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!";
};
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);
});
}
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();
}
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
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>
);
}
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>
<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>
YIASCM 2024
Unit - 4 PWA
<p id="demo">This text will change when you click the
button.</p>
</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