0% found this document useful (0 votes)
1 views19 pages

Topic No 1 Java Script

The document provides an overview of JavaScript, detailing its features, syntax, and common use cases, particularly in web development. It covers fundamental concepts such as variables, data types, control statements, and functions, emphasizing the language's versatility and importance for creating interactive web applications. Additionally, it outlines the structure of JavaScript code and its execution in web browsers.

Uploaded by

jadhao060704
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views19 pages

Topic No 1 Java Script

The document provides an overview of JavaScript, detailing its features, syntax, and common use cases, particularly in web development. It covers fundamental concepts such as variables, data types, control statements, and functions, emphasizing the language's versatility and importance for creating interactive web applications. Additionally, it outlines the structure of JavaScript code and its execution in web browsers.

Uploaded by

jadhao060704
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 19

ZEAL EDUCATION SOCIETY’S

ZEAL INSTITUTE OF BUSINESS ADMINISTRATION,


COMPUTER APPLICATION AND RESEARCH (ZIBACAR)
NARHE │PUNE -41 │ INDIA
Programme – MBA & MCA
Doc No:- ZEAL/ZB/ACAD/P-05/F-15 Revision: 00 Date:01/09/2023
NOTES

Programme : MCA Course Coordinator Name: Prof. Ashok Deokar


Class : MCA I Course Code: EC11-2
Division : A Course Name: Web Development
Semester: I Specialization: Computer

Chapter no. 1: Basic JavaScript


Section Topic
no
1.1 1.1 Introduction of Java Script

Notes JavaScript is a high-level, dynamic, and interpreted programming language primarily used to
create interactive and dynamic content on websites. It is one of the core technologies of the
web, alongside HTML and CSS. While HTML structures the content and CSS styles it,
JavaScript brings websites to life by enabling dynamic behavior, interactivity, and real-time
updates without needing to reload the page.

JavaScript is a client-side scripting language, meaning it runs in the browser on the user’s
device rather than on the web server. However, it can also be used on the server side through
environments like Node.js.

Key Features of JavaScript

1. Interactivity:
o JavaScript allows web pages to respond to user actions (like clicks, keypresses, mouse
movements, etc.). This makes websites interactive, such as providing form validation,
dynamic content updates, and animations.

2. Dynamic Content:
o JavaScript allows websites to update content dynamically without requiring a page
reload. This is achieved through techniques like AJAX (Asynchronous JavaScript
and XML), which enables fetching and displaying new data asynchronously.

3. Lightweight:
o JavaScript is a relatively lightweight language compared to other programming
languages. It runs directly in the browser, making it faster and more efficient for tasks
like DOM manipulation and event handling.

4. Versatility:
o JavaScript can be used for both client-side scripting (running in the browser) and
server-side scripting (using frameworks like Node.js). This versatility allows
developers to use JavaScript throughout the entire stack of web development.

5. Event-Driven:
o JavaScript is event-driven, meaning that it responds to events (such as clicks,
keypresses, or mouse movements) by executing specific code. This is especially
useful for building interactive user interfaces.

6. Cross-Browser Compatibility:
o JavaScript is supported by all modern web browsers, ensuring that code can run
consistently across different platforms (Chrome, Firefox, Safari, etc.).

How JavaScript Works:

JavaScript operates in the following way on a typical webpage:

1. Script Tag:
o JavaScript code is embedded within an HTML file using the <script> tag. It can
either be placed directly in the HTML file or linked to an external .js file. Example:

html
Copy code
<script src="script.js"></script>

2. Browser Execution:
o When a user loads a webpage, the browser reads the HTML content, then parses the
JavaScript and executes it. This happens on the client-side, in the user's browser,
providing a responsive and interactive experience.

3. Event Handling:
o JavaScript interacts with the HTML elements (like buttons, forms, or links) through
event listeners. These listeners detect user actions (e.g., clicks or keypresses) and
trigger functions to respond to these events.

Basic JavaScript Syntax

1. Variables:
o Variables are used to store data. In JavaScript, variables can be declared using var,
let, or const.

javascript
Copy code
let x = 10; // A variable with a value of 10
const name = "John"; // A constant variable (cannot be
reassigned)

2. Data Types:
o JavaScript has several data types, including:
 String: A sequence of characters (e.g., "Hello, World!").
 Number: Numeric values (e.g., 42, 3.14).
 Boolean: A value that can be true or false.
 Object: A collection of key-value pairs.
 Array: An ordered list of values.
 Null & Undefined: Represent empty or non-existent values.

3. Functions:
o Functions are blocks of code designed to perform a specific task. They can be invoked
by their name to execute their code.

javascript
Copy code
function greet(name) {
return "Hello, " + name;
}
console.log(greet("Alice")); // Output: Hello, Alice

4. Control Structures:
o JavaScript includes traditional control structures, like if, else, switch, and loops
(for, while).

javascript
Copy code
let age = 20;
if (age >= 18) {
console.log("You are an adult.");
} else {
console.log("You are a minor.");
}

5. Objects:
o JavaScript allows the creation of objects to store data as key-value pairs.

javascript
Copy code
let person = {
name: "Alice",
age: 30,
greet: function() {
console.log("Hello " + this.name);
}
};
person.greet(); // Output: Hello Alice

Common Use Cases for JavaScript

1. DOM Manipulation:
o JavaScript allows developers to manipulate the Document Object Model (DOM),
which represents the structure of a web page. You can dynamically change HTML
elements, attributes, or content. Example:

javascript
Copy code
document.getElementById("myElement").innerHTML = "New Content";

2. Form Validation:
o JavaScript is often used for validating form input on websites before it is submitted to
a server. It ensures that users provide valid data (e.g., ensuring an email address is in
the correct format). Example:

javascript
Copy code
function validateForm() {
let email = document.getElementById("email").value;
if (!email.includes("@")) {
alert("Invalid email address");
return false;
}
}

3. Interactive Features:
o JavaScript is used to create interactive features on websites, such as image sliders,
pop-ups, dropdown menus, and real-time content updates.

4. AJAX (Asynchronous JavaScript and XML):


o AJAX allows web pages to retrieve data from the server without refreshing the entire
page. This is essential for creating dynamic, fast-loading applications like social
media feeds, online forms, and e-commerce sites. Example:

javascript
Copy code
let xhr = new XMLHttpRequest();
xhr.open("GET", "data.json", true);
xhr.onload = function() {
if (xhr.status === 200) {
let data = JSON.parse(xhr.responseText);
console.log(data);
}
};
xhr.send();

5. Animation and Effects:


o JavaScript can create animations and effects on web pages, such as fading elements in
and out, sliding menus, or complex transitions.

Why Learn JavaScript?

1. Widely Used:
o JavaScript is the most widely used programming language on the web. It's supported
by all modern web browsers, making it essential for web developers.

2. Enhances User Experience:


o JavaScript enables dynamic and interactive web experiences, making it essential for
building modern websites and applications.

3. Full Stack Development:


o JavaScript can be used both on the client-side and server-side (via Node.js), making
it a popular language for full-stack development.

4. Large Ecosystem and Libraries:


o JavaScript has a rich ecosystem of frameworks and libraries, such as React, Angular,
and Vue.js, which simplify development and enhance productivity.

1.2 1.2 Comments, Keywords, Data Types, Variables, Operators, Control Statement and Iterative
statements
Notes In JavaScript, several foundational concepts are used to write efficient and functional code.
This section will cover the following:

 Comments
 Keywords
 Data Types
 Variables
 Operators
 Control Statements
 Iterative Statements

1.2.1 Comments

Comments are used to add explanations or notes in the code. They do not affect the execution
of the program. There are two types of comments in JavaScript:
1. Single-line Comment:
o Used to comment a single line of code.

javascript
Copy code
// This is a single-line comment

2. Multi-line Comment:
o Used to comment out multiple lines of code.

javascript
Copy code
/*
This is a multi-line comment.
It can span multiple lines.
*/

1.2.2 Keywords

Keywords are reserved words in JavaScript that have predefined meanings and are part of the
syntax. You cannot use them as variable names. Some important keywords in JavaScript
include:

 var, let, const (for declaring variables)


 if, else, switch, case (for control flow)
 function (for defining functions)
 return (for returning a value from a function)
 break, continue (for controlling loops)
 try, catch, finally (for exception handling)
 new, this, class, extends (for object-oriented programming)
 false, true, null, undefined (for logical and special values)

1.2.3 Data Types

JavaScript has several primitive data types and non-primitive data types.

1. Primitive Data Types:


o String: Represents a sequence of characters.

javascript
Copy code
let name = "Alice";

o Number: Represents numeric values (both integers and floating-point


numbers).

javascript
Copy code
let age = 25;
let height = 5.9;

o Boolean: Represents true or false values.

javascript
Copy code
let isActive = true;
let isComplete = false;

o Null: Represents an intentionally empty or non-existent value.

javascript
Copy code
let data = null;

o Undefined: Represents a variable that has been declared but has not yet been
assigned a value.

javascript
Copy code
let value;
console.log(value); // Output: undefined

2. Non-Primitive Data Types:


o Object: A collection of key-value pairs.

javascript
Copy code
let person = {
name: "Alice",
age: 30,
greet: function() {
console.log("Hello " + this.name);
}
};

o Array: A collection of values in an ordered list.

javascript
Copy code
let fruits = ["apple", "banana", "orange"];

1.2.4 Variables

Variables are used to store values that can be used and manipulated later in the program. In
JavaScript, there are three ways to declare variables:

1. var: A traditional way to declare variables (function-scoped or globally scoped).

javascript
Copy code
var x = 10;

2. let: A modern way to declare variables (block-scoped, more predictable than var).

javascript
Copy code
let name = "Alice";

3. const: Declares a constant (a variable whose value cannot be reassigned).

javascript
Copy code
const pi = 3.14;

1.2.5 Operators
Operators are symbols used to perform operations on variables and values. JavaScript has
several types of operators:

1. Arithmetic Operators: Used to perform basic arithmetic operations.


o +, -, *, /, %, ++, --

javascript
Copy code
let sum = 10 + 5; // sum = 15
let difference = 10 - 5; // difference = 5

2. Assignment Operators: Used to assign values to variables.


o =, +=, -=, *=, /=, %=

javascript
Copy code
let x = 10;
x += 5; // x = 15

3. Comparison Operators: Used to compare two values.


o ==, ===, !=, !==, >, <, >=, <=

javascript
Copy code
5 == 5; // true
5 === "5"; // false (strict comparison)

4. Logical Operators: Used to perform logical operations.


o && (AND), || (OR), ! (NOT)

javascript
Copy code
let result = (5 > 3) && (3 < 5); // true
let isValid = !(5 === 5); // false

5. Ternary (Conditional) Operator: A shorthand for if-else statements.

javascript
Copy code
let age = 18;
let isAdult = (age >= 18) ? "Yes" : "No"; // "Yes"

6. Type Operators:
o typeof: Returns the type of a variable.

javascript
Copy code
typeof 42; // "number"
typeof "Hello"; // "string"

1.2.6 Control Statements

Control statements allow you to control the flow of execution based on conditions or other
criteria.

1. If-Else Statement:
o Executes a block of code if a condition is true, and another block if it is false.

javascript
Copy code
let age = 18;
if (age >= 18) {
console.log("You are an adult.");
} else {
console.log("You are a minor.");
}

2. Switch Statement:
o Used to execute one of many blocks of code based on a condition.

javascript
Copy code
let day = 3;
switch (day) {
case 1:
console.log("Monday");
break;
case 2:
console.log("Tuesday");
break;
case 3:
console.log("Wednesday");
break;
default:
console.log("Invalid day");
}

1.2.7 Iterative (Loop) Statements

Iterative statements are used to repeatedly execute a block of code as long as a specified
condition is true.

1. For Loop:
o Repeats a block of code a set number of times.

javascript
Copy code
for (let i = 0; i < 5; i++) {
console.log(i); // Output: 0, 1, 2, 3, 4
}

2. While Loop:
o Repeats a block of code as long as a specified condition is true.

javascript
Copy code
let i = 0;
while (i < 5) {
console.log(i); // Output: 0, 1, 2, 3, 4
i++;
}

3. Do-While Loop:
o Similar to the while loop, but it guarantees at least one execution of the code
block.

javascript
Copy code
let i = 0;
do {
console.log(i); // Output: 0, 1, 2, 3, 4
i++;
} while (i < 5);

4. For...in Loop:
o Used to iterate over the properties of an object.

javascript
Copy code
let person = { name: "Alice", age: 25 };
for (let key in person) {
console.log(key + ": " + person[key]);
}

5. For...of Loop:
o Used to iterate over the values of an iterable object (like an array).

javascript
Copy code
let fruits = ["apple", "banana", "orange"];
for (let fruit of fruits) {
console.log(fruit); // Output: apple, banana, orange
}

1.3 1.3 Functions, Array

Notes In JavaScript, functions and arrays are essential concepts that are frequently used to write
modular, dynamic, and efficient code. Here’s an overview of both:

1.3.1 Functions in JavaScript

A function is a block of code designed to perform a particular task. Functions help to keep
your code modular, reusable, and organized.

Defining a Function

You can define a function in JavaScript using the function keyword followed by a name,
parameters (optional), and a block of code.

javascript
Copy code
function greet(name) {
console.log("Hello, " + name);
}

Here, greet is the function name, and name is the parameter passed to the function. When
you call greet("Alice"), it will print "Hello, Alice".

Function Parameters and Return Values

Functions can accept parameters (also called arguments), which are passed when calling the
function, and they can return values using the return keyword.

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

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


console.log(result); // Output: 8

Function Expressions

In addition to function declarations, you can also define functions as expressions and assign
them to variables.

javascript
Copy code
const square = function(x) {
return x * x;
};

console.log(square(4)); // Output: 16

Arrow Functions

JavaScript also supports arrow functions, which provide a shorter syntax for writing
functions. Arrow functions are particularly useful for callbacks and functional programming.

javascript
Copy code
const multiply = (x, y) => x * y;
console.log(multiply(4, 5)); // Output: 20

Functions as First-Class Citizens

In JavaScript, functions are first-class citizens, meaning they can be passed as arguments to
other functions, returned from other functions, and assigned to variables.

javascript
Copy code
function greet(name) {
return "Hello, " + name;
}

function executeGreeting(greetingFunction, name) {


console.log(greetingFunction(name));
}

executeGreeting(greet, "Alice"); // Output: Hello, Alice

Anonymous Functions

Anonymous functions are functions without a name, commonly used for callbacks.

javascript
Copy code
setTimeout(function() {
console.log("This message is delayed.");
}, 2000);

1.3.2 Arrays in JavaScript

An array is a data structure that allows you to store multiple values in a single variable.
Arrays are particularly useful for handling lists or collections of data.

Creating an Array

You can create an array using square brackets [] and separating elements by commas.

javascript
Copy code
let fruits = ["apple", "banana", "orange"];

Accessing Array Elements

Array elements are indexed, starting from 0. You can access elements using their index.

javascript
Copy code
let fruits = ["apple", "banana", "orange"];
console.log(fruits[0]); // Output: apple
console.log(fruits[2]); // Output: orange

Modifying Array Elements

You can modify an element in an array by assigning a new value to a specific index.

javascript
Copy code
let fruits = ["apple", "banana", "orange"];
fruits[1] = "mango"; // Replaces "banana" with "mango"
console.log(fruits); // Output: ["apple", "mango", "orange"]

Array Methods

Arrays come with a variety of built-in methods that allow you to manipulate the elements
inside them.

1. push() - Adds one or more elements to the end of an array.

javascript
Copy code
let fruits = ["apple", "banana"];
fruits.push("orange");
console.log(fruits); // Output: ["apple", "banana", "orange"]

2. pop() - Removes the last element from an array.

javascript
Copy code
fruits.pop();
console.log(fruits); // Output: ["apple", "banana"]

3. shift() - Removes the first element of an array.

javascript
Copy code
fruits.shift();
console.log(fruits); // Output: ["banana"]

4. unshift() - Adds one or more elements to the beginning of an array.

javascript
Copy code
fruits.unshift("grape");
console.log(fruits); // Output: ["grape", "banana"]

5. splice() - Adds or removes elements at a specific index.

javascript
Copy code
let numbers = [1, 2, 3, 4];
numbers.splice(2, 1, 5, 6); // Removes one element at index 2, and
adds 5 and 6
console.log(numbers); // Output: [1, 2, 5, 6, 4]
6. slice() - Creates a shallow copy of a portion of an array.

javascript
Copy code
let fruits = ["apple", "banana", "orange"];
let slicedFruits = fruits.slice(1, 3); // Extracts from index 1 to 2
console.log(slicedFruits); // Output: ["banana", "orange"]

7. forEach() - Executes a provided function once for each array element.

javascript
Copy code
let fruits = ["apple", "banana", "orange"];
fruits.forEach(function(fruit) {
console.log(fruit);
});
// Output:
// apple
// banana
// orange

8. map() - Creates a new array by applying a function to every element of the array.

javascript
Copy code
let numbers = [1, 2, 3];
let doubled = numbers.map(function(num) {
return num * 2;
});
console.log(doubled); // Output: [2, 4, 6]

9. filter() - Creates a new array with all elements that pass a test.

javascript
Copy code
let numbers = [1, 2, 3, 4, 5];
let evenNumbers = numbers.filter(function(num) {
return num % 2 === 0;
});
console.log(evenNumbers); // Output: [2, 4]

10. reduce() - Applies a function against an accumulator and each element to reduce it to
a single value.

javascript
Copy code
let numbers = [1, 2, 3, 4];
let sum = numbers.reduce(function(accumulator, currentValue) {
return accumulator + currentValue;
}, 0);
console.log(sum); // Output: 10

Multidimensional Arrays

Arrays in JavaScript can also be multidimensional (arrays within arrays), useful for tables or
matrices.

javascript
Copy code
let matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
console.log(matrix[1][2]); // Output: 6

1.4 1.4 Java Script Architecture

Notes JavaScript architecture refers to the structure and the underlying components that make
JavaScript work, both in a browser environment and on a server-side context (such as with
Node.js). It involves understanding how JavaScript engines, the call stack, the event loop, and
other parts of the execution environment interact to process JavaScript code efficiently.

Let's break down the architecture of JavaScript in the context of a web browser and Node.js
runtime.

1.4.1 JavaScript Architecture in a Web Browser

In a browser, JavaScript code is executed within a JavaScript Engine. The JavaScript engine
is responsible for interpreting and executing the code written in JavaScript. Popular engines
include:

 V8 (used in Chrome and Node.js)


 SpiderMonkey (used in Firefox)
 JavaScriptCore (used in Safari)

Components of the Browser's JavaScript Architecture

1. Call Stack
o The call stack is a data structure that keeps track of function calls.
o When a function is called, it is added to the stack, and when the function completes, it
is removed from the stack.
o JavaScript is single-threaded, meaning that at any given time, only one piece of code
can be executed, and the call stack helps manage this flow.

Example:

javascript
Copy code
function first() {
second(); // second() is pushed to the call stack
}

function second() {
console.log('Hello from second function');
}

first(); // first() is pushed to the call stack

In this example, first() is called, pushing it to the call stack, then second() is called
from within first(), adding it to the stack as well. After second() completes, it is
popped off the stack, followed by first().

2. Event Loop
o The event loop is responsible for handling asynchronous code (like setTimeout,
promises, and event listeners).
o JavaScript executes synchronous code first (from the call stack), and when an
asynchronous operation is encountered, the event loop moves it to the callback
queue.
o Once the call stack is empty, the event loop takes the next task from the callback
queue and pushes it onto the call stack for execution.
Example of asynchronous behavior:

javascript
Copy code
console.log("First");

setTimeout(function() {
console.log("Second");
}, 1000);

console.log("Third");

Execution Order:

4. "First" is logged immediately.


5. The setTimeout function is asynchronous, so it gets added to the callback queue and
waits for the call stack to be empty.
6. "Third" is logged immediately after.
7. After 1 second, the event loop moves the setTimeout callback from the queue to the
call stack, logging "Second".

3. Web APIs (Browser APIs)

o The browser provides Web APIs (also called browser APIs), which JavaScript
interacts with to perform tasks like handling DOM manipulation, network requests,
timers, etc.
o Examples of Web APIs:
 DOM API for manipulating the HTML document.
 Fetch API for making network requests.
 setTimeout/setInterval for timers.
 localStorage/sessionStorage for client-side storage.

These Web APIs run outside the JavaScript engine and, once executed, send their
results back to the call stack or callback queue, depending on the nature of the
operation.

4. Callback Queue
o The callback queue (also called the task queue) stores asynchronous tasks (callbacks)
waiting to be executed. The event loop checks the callback queue after each
synchronous task from the call stack finishes executing.

5. Microtask Queue
o Microtasks are a special type of callback queue used for promises and
MutationObserver callbacks. Microtasks are processed before the callback queue.
o Promises, when resolved, are placed in the microtask queue, which gets priority over
the regular callback queue.

Example:

javascript
Copy code
console.log("First");

Promise.resolve().then(function() {
console.log("Second");
});

console.log("Third");
Execution Order:

3. "First" is logged.
4. The promise is resolved and added to the microtask queue.
5. "Third" is logged.
6. The event loop checks the microtask queue and logs "Second".

1.4.2 JavaScript Architecture in Node.js

In Node.js, JavaScript is run in a server-side environment. Node.js is built on top of the V8


JavaScript engine, but it also has its own components tailored for server-side development.

1. V8 Engine
o The V8 engine is the core component of JavaScript execution in Node.js. It is
responsible for compiling JavaScript code into machine code and executing it.
o V8 provides fast execution of JavaScript by directly executing compiled machine
code, optimizing code performance.

2. Event Loop
o Just like in the browser, the event loop is crucial in Node.js. It handles non-blocking
asynchronous operations, such as file I/O, database queries, and HTTP requests, by
using callbacks, promises, and events.

3. Libuv
o Libuv is a C library that provides Node.js with a thread pool for handling I/O
operations asynchronously.
o It allows Node.js to perform non-blocking I/O operations like reading from or writing
to files, network communication, and more. This is essential for Node.js’s high
concurrency and performance.

4. Callback Queue & Event Queue


o Node.js uses an event-driven architecture, where operations like reading from files
or handling HTTP requests are event-based. Once an event is triggered, the associated
callback is added to the event queue to be processed by the event loop.

5. Worker Threads
o Node.js also allows the use of worker threads to perform multi-threaded operations
when needed (e.g., CPU-intensive tasks), although its single-threaded nature is
designed for I/O-heavy tasks.

1.4.3 JavaScript Execution Flow in Both Environments

1. Synchronous Execution:
o JavaScript code execution happens line by line on the call stack for synchronous
operations.

2. Asynchronous Execution:
o JavaScript handles asynchronous operations using the event loop, where tasks such as
callbacks or promises are pushed to the callback queue or microtask queue, waiting
for execution when the call stack is empty.

1.5 1.5 Framework and Libraries


Notes In JavaScript, frameworks and libraries are pre-written collections of code that provide
structure and functionality to simplify development, improve productivity, and reduce the
need to write repetitive code. While both frameworks and libraries are tools for developers,
they serve different purposes and are used in different contexts.

Let’s break down what frameworks and libraries are, the differences between them, and
provide examples for both.

1.5.1 What is a Library?

A library is a collection of functions and utilities that you can use in your code to handle
specific tasks. When you use a library, you control the flow of the application, calling the
functions you need, and using the library's pre-defined methods.

Characteristics of a Library

 Reusable Functions: A library offers pre-written code (functions, methods, objects) that you
can invoke to simplify tasks.
 You Control the Flow: In a library, the developer calls the functions or objects that they
need, meaning they maintain control over the flow of the application.

Examples of Popular JavaScript Libraries

1. jQuery
o Purpose: jQuery is one of the oldest and most widely used JavaScript libraries for
DOM manipulation, event handling, and AJAX interactions.
o Example:

javascript
Copy code
$(document).ready(function() {
$('button').click(function() {
alert('Button clicked!');
});
});

2. Lodash
o Purpose: Lodash is a utility library that provides functions for working with arrays,
objects, numbers, and strings. It helps with data manipulation, iteration, and
functional programming.
o Example:

javascript
Copy code
const numbers = [1, 2, 3, 4];
const doubled = _.map(numbers, num => num * 2);
console.log(doubled); // Output: [2, 4, 6, 8]

3. D3.js
o Purpose: D3.js is a powerful JavaScript library for creating interactive and dynamic
data visualizations using HTML, SVG, and CSS.
o Example:

javascript
Copy code
var dataset = [10, 20, 30, 40, 50];
var width = 500, height = 100;

var svg = d3.select('body').append('svg')


.attr('width', width)
.attr('height', height);

svg.selectAll('circle')
.data(dataset)
.enter().append('circle')
.attr('cx', (d, i) => i * 60 + 30)
.attr('cy', height / 2)
.attr('r', d => d);

4. Axios
o Purpose: Axios is a popular library for making HTTP requests, particularly for
working with APIs. It simplifies the process of handling AJAX requests and promises.
o Example:

javascript
Copy code
axios.get('https://jsonplaceholder.typicode.com/posts')
.then(function(response) {
console.log(response.data);
})
.catch(function(error) {
console.log('Error:', error);
});

1.5.2 What is a Framework?

A framework is a more comprehensive and opinionated set of tools and guidelines that
dictates how you structure and develop your application. Frameworks provide a set of rules or
conventions, and they typically handle much of the application's flow for you.

Characteristics of a Framework

 Structure and Conventions: Frameworks provide structure to your application and enforce
best practices and conventions, which can result in faster development, especially for large
projects.
 Inversion of Control: Unlike libraries, frameworks control the flow of the application. The
framework calls your code, meaning you must work within its structure.
 Feature-Rich: Frameworks often include a variety of built-in tools for routing, state
management, and data binding, reducing the need for external dependencies.

Examples of Popular JavaScript Frameworks

1. React
o Purpose: React is a JavaScript framework (technically a library, but often referred to
as a framework) for building user interfaces, particularly for single-page applications
(SPAs). React focuses on creating components that manage their own state and can be
reused.
o Example:

javascript
Copy code
import React, { useState } from 'react';

function App() {
const [count, setCount] = useState(0);

return (
<div>
<h1>Count: {count}</h1>
<button onClick={() => setCount(count +
1)}>Increase</button>
</div>
);
}

export default App;

2. Angular
o Purpose: Angular is a comprehensive framework for building dynamic, single-page
web applications. It provides features such as two-way data binding, dependency
injection, and comprehensive routing solutions.
o Example:

javascript
Copy code
import { Component } from '@angular/core';

@Component({
selector: 'app-root',
template: `
<h1>{{ title }}</h1>
<button (click)="increment()">Increase</button>
`
})
export class AppComponent {
title = 'Counter App';
count = 0;

increment() {
this.count++;
}
}

3. Vue.js
o Purpose: Vue.js is a progressive JavaScript framework for building user interfaces.
Vue is flexible and allows developers to use it for building both simple and complex
single-page applications.
o Example:

javascript
Copy code
<template>
<div>
<h1>{{ count }}</h1>
<button @click="increment">Increase</button>
</div>
</template>

<script>
export default {
data() {
return {
count: 0
};
},
methods: {
increment() {
this.count++;
}
}
};
</script>

4. Express.js
o Purpose: Express.js is a web application framework for Node.js, providing a robust
set of features for web and mobile applications. It simplifies routing, middleware, and
handling HTTP requests in server-side applications.
o Example:

javascript
Copy code
const express = require('express');
const app = express();

app.get('/', (req, res) => {


res.send('Hello, World!');
});

app.listen(3000, () => {
console.log('Server running on port 3000');
});

1.5.3 Key Differences Between Frameworks and Libraries

Feature Library Framework


You control the flow of the
Control The framework controls the flow.
application.
Provides structure and a complete development
Purpose Provides a set of utility functions.
environment.
Flexibility More flexible, less opinionated. Less flexible, follows specific conventions.
Examples jQuery, Lodash, Axios, D3.js. React, Angular, Vue.js, Express.js.
You build your application around the framework's
Usage You call the library when needed.
structure.

3.6

Notes

3.7

Notes

3.8

Notes

3.9

Notes

Course Class HOD Director


Coordinator Coordinator

You might also like