Javascript Doc
Javascript Doc
Reverse a string
function reverseStringInbuilt(str) {
return str.split('').reverse().join('');
}
function reverseStringCustom(str) {
let reversedStr = '';
for (let i = str.length - 1; i >= 0; i--) {
reversedStr += str[i];
}
return reversedStr;
}
function findUniqueElements(arr) {
const elementCount = {};
const uniqueElements = [];
// Count the occurrences of each element
for (const element of arr) {
elementCount[element] = (elementCount[element] || 0) + 1;
}
// Filter elements that occur only once
for (const element of arr) {
if (elementCount[element] === 1) {
uniqueElements.push(element);
}
}
return uniqueElements;
}
function findUniqueElements(arr) {
return result;
}, {});
}
4. Sorting function
function sortArrayCustom(arr) {
let n = arr.length;
for (let i = 0; i < n - 1; i++) {
for (let j = 0; j < n - 1 - i; j++) {
if (arr[j] < arr[j + 1]) {
let temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}return arr;
}
5. find duplicate items in an array
function findDuplicatesInbuilt(arr) {
return arr.filter(
);
function findDuplicatesCustom(arr) {
const duplicates = [];
for (let i = 0; i < arr.length; i++) {
for (let j = i + 1; j < arr.length; j++) {
if (arr[i] === arr[j] && !duplicates.includes(arr[i])) {
duplicates.push(arr[i]);
}
}
}
return duplicates;
}
function x() {
console.log("Hi)";
};
function y(x) {
x();
};
y();
The call method calls a function with a given this value and arguments provided
const person = {
fullName: function () {
return this.firstName + " " + this.lastName;
},
};
const person1 = {
firstName: "John",
lastName: "Doe",
};
console.log(person.fullName.call(person1));
const person = {
fullName: function (city, country) {
return this.firstName + " " + this.lastName + ", " + city + ", " +
country;
},
};
const person1 = {
firstName: "John",
lastName: "Doe",
};
console.log(person.fullName.apply(person1, ["Oslo", "Norway"]));
The bind method creates a new function that, when called, has its this value set to
the provided value, with a given sequence of arguments
const person = {
firstName: "John",
lastName: "Doe",
fullName: function () {
return this.firstName + " " + this.lastName;
},
};
const person1 = {
firstName: "Jane",
lastName: "Doe",
};
console.log(fullName());
Q: Hoisting
Q: Memoization
Memoization:
Q: Closure
A closure is a function that has access to its outer function scope even after
the function has returned. Meaning, A closure can remember and access
variables and arguments reference of its outer function even after the function
has returned.
If a function needs to access a variable, it first goes to its local memory. When it
does not find it there, it goes to the memory of its lexical parent.
function x() {
var a = 7;
function y() {
console.log(a);
}
return y;
}
var z = x();
console.log(z); // value of z is entire code of function y.