0% found this document useful (0 votes)
14 views

Jsmethods

javascript

Uploaded by

sk02480ak
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

Jsmethods

javascript

Uploaded by

sk02480ak
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 4

1.

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

// Mutable method: pop()


arr.pop(); // Removes last element, changes original array
console.log(arr); // [1, 2]

// Immutable method: concat()


let newArr = arr.concat([4, 5]); // Does not change original, returns new array
console.log(newArr); // [1, 2, 4, 5]
3. Pass by Reference and Pass by Value
Pass by Value: Primitive data types (numbers, strings, etc.) are copied when passed to a function.
Pass by Reference: Objects and arrays are passed by reference, so changes inside functions affect the original.
Example:

javascript
Copy code
let x = 10; // pass by value
function modifyValue(val) {
val = 20;
}
modifyValue(x);
console.log(x); // still 10

let obj = { key: "value" }; // pass by reference


function modifyObj(objRef) {
objRef.key = "newValue";
}
modifyObj(obj);
console.log(obj.key); // "newValue"
4. Array Methods
Basics:

pop() (Mutable): Removes the last element.


let arr = [1, 2, 3];
arr.pop(); // [1, 2]

push() (Mutable): Adds an element to the end.


arr.push(4); // [1, 2, 4]

concat() (Immutable): Combines arrays.


let newArr = arr.concat([5, 6]); // [1, 2, 4, 5, 6]

slice() (Immutable): Returns a portion of the array.


let sliced = arr.slice(1, 2); // [2]

splice() (Mutable): Adds/removes elements.


arr.splice(1, 1); // Removes element at index 1

join() (Immutable): Converts array to string.


let joined = arr.join("-"); // "1-2-4"

flat() (Immutable): Flattens nested arrays.


let nested = [1, [2, 3], 4];
let flatArr = nested.flat(); // [1, 2, 3, 4]

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

includes() (Immutable): Checks if the array contains a value.


let hasTwo = arr.includes(2); // true

findIndex() (Immutable): Returns the index of the first matching element.


let idx = arr.findIndex(num => num === 4); // 2

Higher Order Functions:


forEach() (Immutable): Executes a function for each element.
arr.forEach(num => console.log(num));

filter() (Immutable): Filters array elements based on a condition.


let filtered = arr.filter(num => num > 1); // [2, 4]

map() (Immutable): Transforms array elements.


let doubled = arr.map(num => num * 2); // [2, 4, 8]

reduce() (Immutable): Reduces array to a single value.


let sum = arr.reduce((acc, num) => acc + num, 0); // 7

sort() (Mutable): Sorts array elements.


arr.sort((a, b) => a - b); // [1, 2, 4]

Advanced: Array Method Chaining


let result = arr
.filter(num => num > 1)
.map(num => num * 2)
.reduce((acc, num) => acc + num, 0); // 12

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: returns a new string


let newStr = str.replace("world", "JavaScript");
console.log(newStr); // "hello JavaScript"

6. Object Methods and Operations


Mutable Methods:
let obj = { name: "Alice", age: 25 };

// Adding a new property (Mutable)


obj.location = "New York";
console.log(obj); // { name: "Alice", age: 25, location: "New York" }

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;

console.log(b); // Error: b is not defined (let is not initialized)


let b = 10;

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

return function inner() {


console.log(outerVar); // Has access to outerVar
};
}
const closureFunc = outer();
closureFunc(); // "I am outer"

10. Higher Order Functions


A higher-order function is a function that takes another function as an argument or returns a function.
Example:
Copy code
function greet(name) {
return function(message) {
console.log(message + ", " + name);
};
}
const greetUser = greet("Alice");
greetUser("Hello"); // "Hello, Alice"

You might also like