Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
449 views

Java Script Notes

JavaScript is a lightweight, versatile programming language created by Brendan Eich in 1995, designed to make web pages interactive. Key features include being interpreted, dynamic, event-driven, and supporting both client-side and server-side development. The document covers essential JavaScript concepts such as variables, data types, functions, arrays, objects, and advanced topics like promises, async/await, and array methods like map, filter, and reduce.

Uploaded by

shivamraj009955
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)
449 views

Java Script Notes

JavaScript is a lightweight, versatile programming language created by Brendan Eich in 1995, designed to make web pages interactive. Key features include being interpreted, dynamic, event-driven, and supporting both client-side and server-side development. The document covers essential JavaScript concepts such as variables, data types, functions, arrays, objects, and advanced topics like promises, async/await, and array methods like map, filter, and reduce.

Uploaded by

shivamraj009955
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
You are on page 1/ 10

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.

Key Features of JavaScript


• Interpreted: No need for compilation.
• Dynamic: Variables and types can change at runtime.
• Event-Driven: Handles user interactions like clicks and keyboard input.
• Versatile: Works on both client-side (browser) and server-side (Node.js).
• Object-Oriented: Supports objects, classes, and inheritance.

**JavaScript Basics: Comprehensive Notes**

---

### **1. Variables**


- Variables are containers for storing data values.
- Declared using `var`, `let`, or `const`:
- **`var`**: Function-scoped, can be redeclared, not recommended for modern use.
- **`let`**: Block-scoped, can be reassigned but not redeclared.
- **`const`**: Block-scoped, cannot be reassigned or redeclared.

```javascript
var x = 10; // Function-scoped
let y = 20; // Block-scoped
const z = 30; // Block-scoped and constant
```

---

### **2. Data Types**


- **Primitive Types**:
- String
- Number
- Boolean
- Undefined
- Null
- Symbol
- BigInt

- **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
```

---

### **3. Scope**


- **Global Scope**: Variables declared outside any function or block.
- **Function Scope**: Variables declared with `var` inside a function are accessible only within that function.
- **Block Scope**: Variables declared with `let` and `const` inside a block (`{}`) are only accessible within
that block.

```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
}
```

---

### **4. Functions**


- Functions allow reusable blocks of code.
- Types of functions:
- **Function Declaration**:
```javascript
function greet(name) {
return `Hello, ${name}`;
}
```

- **Function Expression**:
```javascript
const greet = function(name) {
return `Hello, ${name}`;
};
```

- **Arrow Function**:
```javascript
const greet = (name) => `Hello, ${name}`;
```

---

### **5. Arrays**


- Arrays are used to store multiple values in a single variable.
- Methods:
- `push()`, `pop()`, `shift()`, `unshift()`, `splice()`, `slice()`, `map()`, `filter()`, `reduce()`, etc.

```javascript
let fruits = ["Apple", "Banana", "Cherry"];
fruits.push("Date"); // Adds "Date"
fruits.pop(); // Removes "Date"
console.log(fruits[0]); // Access element
```

---

### **6. Objects**


- Objects are collections of key-value pairs.
- Access using dot (`.`) or bracket (`[]`) notation.

```javascript
let person = {
name: "John",
age: 30,
greet() {
console.log(`Hello, ${this.name}`);
},
};

console.log(person.name); // Access with dot


console.log(person["age"]); // Access with brackets
person.greet(); // Call method
```

---

### **7. IIFE (Immediately Invoked Function Expression)**


- A function that runs immediately after being defined.

```javascript
(function () {
console.log("IIFE executed!");
})();
```

- Useful for creating isolated scopes.

---

### **8. Events**


- JavaScript can interact with HTML elements using events.
- Common events: `click`, `mouseover`, `keydown`, etc.

```javascript
let button = document.getElementById("myButton");
button.addEventListener("click", () => {
console.log("Button clicked!");
});
```

---

### **9. Promises**


- Promises are used for asynchronous operations.
- States: `Pending`, `Fulfilled`, `Rejected`.
```javascript
let promise = new Promise((resolve, reject) => {
let success = true;
if (success) {
resolve("Success!");
} else {
reject("Error!");
}
});

promise
.then((result) => console.log(result)) // Success
.catch((error) => console.log(error)); // Error
```

---

### **10. Async/Await**


- Simplifies working with Promises.

```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();
```

---

### **11. DOM Manipulation**


- Access and manipulate HTML elements.

```javascript
let element = document.getElementById("myElement");
element.textContent = "Hello, World!";
element.style.color = "red";
```

---

### **12. Closures**


- A closure is created when a function retains access to variables in its lexical scope, even after the outer
function has returned.

```javascript
function outer() {
let count = 0;
return function inner() {
count++;
console.log(count);
};
}

let counter = outer();


counter(); // 1
counter(); // 2
```

---

### **13. Hoisting**


- Variable and function declarations are moved to the top of their scope during execution.

```javascript
console.log(x); // undefined (var is hoisted)
var x = 10;

console.log(y); // ReferenceError (let is not hoisted)


let y = 20;
```

---

### **14. Template Literals**


- Allows embedding expressions in strings.

```javascript
let name = "Shivam";
let greeting = `Hello, ${name}!`;
console.log(greeting); // Hello, Shivam!
```

---

### **15. Modules**


- Import and export code between files.

```javascript
// Export
export const greet = (name) => `Hello, ${name}`;

// Import
import { greet } from "./greet.js";
console.log(greet("Shivam"));
```

---

### **16. Error Handling**


- Handle errors using `try`, `catch`, and `finally` blocks.

```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

Shift And Unshift Method

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];

// Removing the first element


let removed = arr.shift();
console.log(arr); // [2, 3, 4, 5] (original array is modified)
console.log(removed); // 1 (the removed element)

// Attempting shift on an empty array


let emptyArr = [];
let result = emptyArr.shift();
console.log(result); // undefined
unshift()
javascript
CopyEdit
let arr = [2, 3, 4, 5];

// Adding elements to the beginning


let newLength = arr.unshift(1); // Adds 1 at the beginning
console.log(arr); // [1, 2, 3, 4, 5]
console.log(newLength); // 5 (new length of the array)

// Adding multiple elements


arr.unshift(-1, 0); // Adds -1 and 0 at the beginning
console.log(arr); // [-1, 0, 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

8. Comparison with splice()


• While shift() and unshift() specifically handle elements at the beginning, splice() can insert, remove,
or replace elements anywhere in the array.
New :-
JavaScript provides powerful array methods to work with data collections efficiently. Among the most
commonly used methods are map, filter, and reduce. Here's a complete guide to these functions with
definitions, syntax, and examples.

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);

console.log(squared); // Output: [1, 4, 9, 16]


console.log(numbers); // Original array remains unchanged: [1, 2, 3, 4]

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);

console.log(greaterThan15); // Output: [20, 25]


console.log(numbers); // Original array remains unchanged: [10, 15, 20, 25]

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

Combined Example of map, filter, and reduce


Let's use all three methods together.
Problem: From an array of numbers, double the even numbers and calculate their total sum.
javascript
CopyEdit
const numbers = [1, 2, 3, 4, 5, 6];

// Step 1: Filter even numbers


const evens = numbers.filter(num => num % 2 === 0); // [2, 4, 6]

// Step 2: Double the even numbers


const doubled = evens.map(num => num * 2); // [4, 8, 12]

// Step 3: Calculate the sum of doubled numbers


const total = doubled.reduce((sum, num) => sum + num, 0); // 24

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.

You might also like