Topic No 1 Java Script
Topic No 1 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.
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.).
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.
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
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.
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();
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.
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:
JavaScript has several primitive data types and non-primitive data types.
javascript
Copy code
let name = "Alice";
javascript
Copy code
let age = 25;
let height = 5.9;
javascript
Copy code
let isActive = true;
let isComplete = false;
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
javascript
Copy code
let person = {
name: "Alice",
age: 30,
greet: function() {
console.log("Hello " + this.name);
}
};
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:
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";
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:
javascript
Copy code
let sum = 10 + 5; // sum = 15
let difference = 10 - 5; // difference = 5
javascript
Copy code
let x = 10;
x += 5; // x = 15
javascript
Copy code
5 == 5; // true
5 === "5"; // false (strict comparison)
javascript
Copy code
let result = (5 > 3) && (3 < 5); // true
let isValid = !(5 === 5); // false
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"
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");
}
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
}
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:
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".
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;
}
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
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;
}
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);
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"];
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
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.
javascript
Copy code
let fruits = ["apple", "banana"];
fruits.push("orange");
console.log(fruits); // Output: ["apple", "banana", "orange"]
javascript
Copy code
fruits.pop();
console.log(fruits); // Output: ["apple", "banana"]
javascript
Copy code
fruits.shift();
console.log(fruits); // Output: ["banana"]
javascript
Copy code
fruits.unshift("grape");
console.log(fruits); // Output: ["grape", "banana"]
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"]
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
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.
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:
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');
}
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:
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. 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.
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. 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.
Let’s break down what frameworks and libraries are, the differences between them, and
provide examples for both.
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.
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;
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);
});
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.
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>
);
}
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.listen(3000, () => {
console.log('Server running on port 3000');
});
3.6
Notes
3.7
Notes
3.8
Notes
3.9
Notes