Jsmethods
Jsmethods
Loops
for loop
The for loop repeats a block of code a specified number of times. It is best used when you know how many times you
Example:
javascript
Copy code
for (let i = 0; i < 5; i++) {
console.log(i); // prints numbers from 0 to 4
}
forEach loop
The forEach method executes a function once for each array element. It cannot be stopped like a for loop.
Example:
javascript
Copy code
const arr = [1, 2, 3, 4];
arr.forEach(num => console.log(num)); // prints each number in the array
for..in loop
The for..in loop iterates over the properties of an object (or the index of an array).
Example:
javascript
Copy code
const person = { name: "Alice", age: 25 };
for (let key in person) {
console.log(key, person[key]); // logs "name Alice" and "age 25"
}
for..of loop
The for..of loop iterates over iterable objects like arrays, strings, etc. It retrieves values directly.
Example:
javascript
Copy code
const numbers = [1, 2, 3];
for (let num of numbers) {
console.log(num); // prints each number in the array
}
while loop
A while loop will run as long as the condition is true.
Example:
javascript
Copy code
let i = 0;
while (i < 3) {
console.log(i); // prints 0, 1, 2
i++;
}
2. Mutable and Immutable Methods in Strings and Arrays
Mutable: Changes the original array or string.
Immutable: Does not change the original, but returns a new value.
Strings (Immutable)
javascript
Copy code
let str = "hello";
let upperStr = str.toUpperCase(); // Immutable method, returns new string
console.log(str); // "hello"
console.log(upperStr); // "HELLO"
Arrays (Mutable and Immutable)
javascript
Copy code
let arr = [1, 2, 3];
javascript
Copy code
let x = 10; // pass by value
function modifyValue(val) {
val = 20;
}
modifyValue(x);
console.log(x); // still 10
Finding:
find() (Immutable): Returns the first matching element.
let found = arr.find(num => num === 2); // 2
indexOf() (Immutable): Returns the index of the first occurrence.
let index = arr.indexOf(4); // 2
5. String Methods
Mutable Methods:
Strings are immutable in JavaScript, meaning that no method can modify the original string. Methods like replace(), to
let str = "hello world";
Immutable Methods:
// Immutable method: Object.assign() creates a copy
let newObj = Object.assign({}, obj, { age: 30 });
console.log(newObj); // { name: "Alice", age: 30, location: "New York" }
7. Hoisting
Variables and functions are hoisted to the top of their scope. let and const are hoisted but not initialized.
console.log(a); // undefined (var is hoisted)
var a = 5;
8. Scopes
Global Scope: Variables declared outside functions are globally accessible.
Function Scope: Variables declared inside functions are accessible only within that function.
Block Scope: Variables declared inside blocks (if, for) using let or const are block-scoped.
9. Closures
A closure is a function that has access to its own scope, the outer function's scope, and the global scope.
Example:
javascript
Copy code
function outer() {
let outerVar = "I am outer";