Java Script Notes
Java Script Notes
JavaScript: is a versatile, lightweight language commonly used to make websites interactive. Here's everything
you need to know to get started:
Founding of JavaScript
• Founder: Brendan Eich
• Year Created: 1995
• Initially Named: Mocha (later renamed to Live Script and finally to JavaScript)
• Developed By: Netscape
• Purpose: To make web pages interactive, such as responding to user actions, animations, or form
validation.
---
```javascript
var x = 10; // Function-scoped
let y = 20; // Block-scoped
const z = 30; // Block-scoped and constant
```
---
- **Non-Primitive Types**:
- Object (including Arrays, Functions, etc.)
```javascript
let str = "Hello, World!"; // String
let num = 42; // Number
let bool = true; // Boolean
let nothing = null; // Null
let undef; // Undefined
let bigInt = 123456789012345678901234567890n; // BigInt
```
---
```javascript
let x = 10; // Global
function test() {
let y = 20; // Function-scoped
if (true) {
let z = 30; // Block-scoped
console.log(z); // Accessible
}
console.log(y); // Accessible
}
```
---
- **Function Expression**:
```javascript
const greet = function(name) {
return `Hello, ${name}`;
};
```
- **Arrow Function**:
```javascript
const greet = (name) => `Hello, ${name}`;
```
---
```javascript
let fruits = ["Apple", "Banana", "Cherry"];
fruits.push("Date"); // Adds "Date"
fruits.pop(); // Removes "Date"
console.log(fruits[0]); // Access element
```
---
```javascript
let person = {
name: "John",
age: 30,
greet() {
console.log(`Hello, ${this.name}`);
},
};
---
```javascript
(function () {
console.log("IIFE executed!");
})();
```
---
```javascript
let button = document.getElementById("myButton");
button.addEventListener("click", () => {
console.log("Button clicked!");
});
```
---
promise
.then((result) => console.log(result)) // Success
.catch((error) => console.log(error)); // Error
```
---
```javascript
async function fetchData() {
try {
let response = await fetch("https://api.example.com/data");
let data = await response.json();
console.log(data);
} catch (error) {
console.error(error);
}
}
fetchData();
```
---
```javascript
let element = document.getElementById("myElement");
element.textContent = "Hello, World!";
element.style.color = "red";
```
---
```javascript
function outer() {
let count = 0;
return function inner() {
count++;
console.log(count);
};
}
---
```javascript
console.log(x); // undefined (var is hoisted)
var x = 10;
---
```javascript
let name = "Shivam";
let greeting = `Hello, ${name}!`;
console.log(greeting); // Hello, Shivam!
```
---
```javascript
// Export
export const greet = (name) => `Hello, ${name}`;
// Import
import { greet } from "./greet.js";
console.log(greet("Shivam"));
```
---
```javascript
try {
let result = riskyOperation();
} catch (error) {
console.error("An error occurred:", error);
} finally {
console.log("Execution completed.");
}
```
splice(): Modifies the original array by adding or removing elements.
slice(): Returns a shallow copy of a portion of an array without modifying the original array.
Mutability
• splice(): Mutates the original array.
• slice(): Does not mutate the original array.
3. Parameters
splice(start, deleteCount, item1, item2, ...)
• start: Index at which to start modifying the array.
• deleteCount: Number of elements to remove (optional; defaults to 0 if not specified).
• item1, item2, ...: Elements to add at the start index (optional).
slice(start, end)
• start: Start index (inclusive) of the portion to extract.
• end: End index (exclusive); if omitted, extracts to the end of the array.
4. Return Value
• splice(): Returns an array of the removed elements (if any).
• slice(): Returns a new array containing the extracted elements.
5. Use Cases
• splice():
o Removing elements: array.splice(2, 1); → Removes 1 element at index 2.
o Adding elements: array.splice(2, 0, 'a', 'b'); → Inserts 'a' and 'b' at index 2.
o Replacing elements: array.splice(2, 1, 'x'); → Replaces 1 element at index 2 with 'x'.
• slice():
o Extracting a portion of an array: array.slice(1, 3); → Returns elements from index 1 to 2.
o Copying an array: array.slice(); → Returns a shallow copy of the entire array.
6. Examples
splice()
javascript
CopyEdit
let arr = [1, 2, 3, 4, 5];
// Removing elements
let removed = arr.splice(2, 2); // Removes 2 elements starting at index 2
console.log(arr); // [1, 2, 5]
console.log(removed); // [3, 4]
// Adding elements
arr.splice(2, 0, 'a', 'b'); // Adds 'a' and 'b' at index 2
console.log(arr); // [1, 2, 'a', 'b', 5]
// Replacing elements
arr.splice(2, 2, 'x', 'y'); // Replaces 2 elements starting at index 2 with 'x' and 'y'
console.log(arr); // [1, 2, 'x', 'y', 5]
slice()
javascript
CopyEdit
let arr = [1, 2, 3, 4, 5];
// Extracting a portion
let sliced = arr.slice(1, 4); // Extracts elements from index 1 to 3
console.log(arr); // [1, 2, 3, 4, 5] (original array unchanged)
console.log(sliced); // [2, 3, 4]
// Copying an array
let copied = arr.slice();
console.log(copied); // [1, 2, 3, 4, 5]
7. Key Points
Feature splice() slice()
Modification Modifies the original array Does not modify the original array
Return Value Array of removed elements New array of extracted elements
Purpose Add, remove, or replace elements Extract a portion of the array
Immutable
Mutability Mutates the original array
The shift() and unshift() methods in JavaScript are used to manipulate arrays by working with elements at
the beginning of the array. Here's a detailed breakdown:
1. Purpose
• shift(): Removes the first element from an array and returns it.
• unshift(): Adds one or more elements to the beginning of an array and returns the new length of the
array.
2. Mutability
• shift(): Mutates the original array by removing its first element.
• unshift(): Mutates the original array by adding elements to the beginning.
3. Parameters
• shift(): Takes no parameters.
• unshift(element1, element2, ...): Takes one or more elements to be added to the beginning of the
array.
4. Return Value
• shift(): Returns the removed element. If the array is empty, it returns undefined.
• unshift(): Returns the new length of the array after the elements are added.
5. Use Cases
• shift():
o Removing the first element of an array (e.g., processing a queue).
o Extracting data from the front of the array.
• unshift():
o Adding elements at the beginning of an array (e.g., creating a new queue with prepended
data).
6. Examples
shift()
javascript
CopyEdit
let arr = [1, 2, 3, 4, 5];
7. Key Points
Feature shift() unshift()
Modification Removes the first element Adds elements to the beginning
Mutability Mutates the original array Mutates the original array
Return Value The removed element New length of the array
Purpose Removing from the front of array Adding to the front of array
1. map() Method
The map() method creates a new array by applying a function to each element of the original array. It does
not mutate the original array.
Syntax
javascript
CopyEdit
const newArray = array.map(callback(element, index, array));
• callback: A function that executes for each array element.
o element: The current element being processed.
o index (optional): The index of the current element.
o array (optional): The array map was called upon.
• Returns: A new array with transformed elements.
Example
javascript
CopyEdit
const numbers = [1, 2, 3, 4];
const squared = numbers. Map(num => num * num);
2. filter () Method
The filter () method creates a new array containing elements that pass a specific condition defined in a
callback function. It does not mutate the original array.
Syntax
javascript
CopyEdit
const newArray = array.filter(callback(element, index, array));
• callback: A function to test each element.
o element: The current element being processed.
o index (optional): The index of the current element.
o array (optional): The array filter was called upon.
• Returns: A new array with elements that pass the condition.
Example
javascript
CopyEdit
const numbers = [10, 15, 20, 25];
const greaterThan15 = numbers.filter(num => num > 15);
3. reduce() Method
The reduce() method applies a function to accumulate all array elements into a single value. It iterates
through the array, carrying forward a result (known as an accumulator).
Syntax
javascript
CopyEdit
const result = array.reduce(callback(accumulator, element, index, array), initialValue);
• callback: A function executed for each element.
o accumulator: The accumulated result from the previous callback execution.
o element: The current element being processed.
o index (optional): The index of the current element.
o array (optional): The array reduce was called upon.
• initialValue: The initial value of the accumulator (optional).
• Returns: A single accumulated value.
Example
javascript
CopyEdit
const numbers = [1, 2, 3, 4];
const sum = numbers.reduce((accumulator, current) => accumulator + current, 0);
console.log(sum); // Output: 10
console.log(total); // Output: 24
Key Differences Between map, filter, and reduce
Method Purpose Returns Mutates Original Array?
map Transforms each element. New array. No
filter Filters elements based on a condition. New array. No
reduce Combines all elements into a single value. Single value. No
Summary
• Use map when you want to transform elements in an array.
• Use filter when you want to extract elements that meet specific conditions.
• Use reduce when you want to combine all elements into a single result, such as a sum, average, or
object.