let person = {
name: "Ajay",
lastname: "Kumar",
address:{
city:"Haridwar",
state:"Uttarakhand",
country: "India",
}
};
let person2 = Object.assign({}, person);
person2.name="Vijay"
person2.address.city = "Roorkee";
person2.address.state="U.P."
console.log("person 1 name is", person.address);
// *************** Output 1 Person **************//
{
firstName: 'Ajay',
lastName: 'Kumar',
address: {
city: 'Roorkee',
state: 'U.P.',
country :"India"
}
console.log("person 2 name is ", person2.address);
// *************** Output 2 Person **************//
{
firstName: 'Vijay',
lastName: 'Kumar',
address: {
city: 'Roorkee',
state: 'U.P.',
country :"India"
}
}
In this example
function Clipboard() {
/* Get the text field */
let copyText = document.getElementById("IdOfTextToCopy");
/* Select the text field */
copyText.select();
/* Copy the text inside the text field */
document.execCommand("copy");
/* Use below command to access the value of copied text */
console.log(copyText.value);
}
const person={
name:"Ajay",
lastname:"Kumar"
}
// using spread operator
let p1 ={
...person
}
console.log("spread",p1)
//using object assign
let p2=Object.assign({},person)
console.log("object assign",p2)
//using JSON
let p3= JSON.parse(JSON.stringify(person))
console.log("JSON",p3)
or
var person = {
name: "Ajay",
lastname: "Kumar",
};
var person2 = Object.assign({}, person);
person.name = "Vijay";
console.log("person 1 name is", person.name); // Vijay
console.log("person 2 name is ", person2.name); //Ajay
let counter = 1;
let copiedCounter = counter;
copiedCounter = 2;
console.log(counter); //1
However, if you use the assignment operator for a reference value, it will not copy the
value.
let person = {
firstName: 'Ajay',
lastName: 'Kumar'
};
let copiedPerson = person;
copiedPerson.firstName = 'Vijay';
console.log(person);
Output
{ firstName: 'Vijay', lastName: 'Kumar' }
Deep Copy Example :
let person = {
name: "Ajay",
lastname: "Kumar",
address:{
city:"Haridwar",
state:"Uttarakhand",
country:"India"
}
};
let person2 = JSON.parse(JSON.stringify(person))
person2.address.city = "Roorkee";
person2.address.state="U.P."
console.log("person 1 name is", person.address); // {city: 'Haridwar', state: 'Uttarakhand',country:"India"}
console.log("person 2 name is ", person2.address); // {city: 'Roorkee', state: 'U.P.',country:"India"}
function add(x, y) {
return x + y;
}
console.log(add.length); // 2
console.log(add.prototype); // Object{}
const person ={
firstName:"Ajay",
lastName:"Kumar",
birth:1998,
fullName:function(){
return this.firstName+" "+this.lastName;
},
currentAge:function(){
let myAge = new Date().getFullYear() - this.birth;
return myAge;
}
}
console.log(person.fullName()) //Ajay kumar
console.log(person.currentAge()) //25
In the example above, this refers to the person object.
console.log(this === window); // true
or
this.color= 'Red';
console.log(window.color); // 'Red'
or
function show() {
"use strict";
console.log(this === undefined); // true
function display() {
console.log(this === undefined); // true
}
display();
}
show();
object.objectMethod.call( objectInstance, arguments )
Parameters: It takes two parameters:
const person = {
fullName: function () {
return this.firstName + " " + this.lastName;
},
agePerson:function(){
let myAge = new Date().getFullYear()- this.age;
return myAge;
}
};
const person1 = {
firstName: "Ajay",
lastName: "Kumar",
age:1998,
};
const person2 = {
firstName: "Vijay",
lastName: "Kumar",
age:1999,
};
console.log(person.fullName.call(person2)); //Vijay Kumar
console.log(person.agePerson.call(person2)); //24
const person = {
fullName: function(city,state, country) {
return this.firstName + " " + this.lastName + "," + city +"," +state +"," + country;
}
}
const person1 = {
firstName:"Ajay",
lastName: "Kumar"
}
console.log(person.fullName.call(person1, "Haridwar","Uttarakhand" ,"India"));
// Ajay Kumar,Haridwar,Uttarakhand,India
object.objectMethod.apply(objectInstance, arrayOfArguments)
Parameters: It takes two parameters:
const person = {
fullName: function() {
return this.firstName + " " + this.lastName;
}
}
const person1 = {
firstName: "Ajay",
lastName: "Kumar"
}
console.log(person.fullName.apply(person1)) // Ajay Kumar
const person = {
fullName: function(city,state, country) {
return this.firstName + " " + this.lastName + "," + city +"," +state +"," + country;
}
}
const person1 = {
firstName:"Ajay",
lastName: "Kumar"
}
console.log(person.fullName.apply(person1, ["Haridwar","Uttarakhand" ,"India"]));
// Ajay Kumar,Haridwar,Uttarakhand,India
# | JavaScript call() Method | JavaScript apply() Method |
---|---|---|
1 | It is used to write such a method that can be used on different objects. | It is used to write methods, which can be used on different objects |
2 | It is a Predefined Method in Javascript | Its return value is the result of the calling function along provided this value and arguments. |
3 | It is used for an object to use a method that belongs to a different object. | We can use a list with this function instead of the array |
4 | This method can also accept parameters. | This method takes the parameter as an array |
const person = {
firstName:"Ajay",
lastName: "Kumar",
fullName: function () {
return this.firstName + " " + this.lastName;
}
}
const member = {
firstName:"Vijay",
lastName: "Kumar",
}
let fullName = person.fullName.bind(member);
console.log(fullName)
// ƒ () {
// return this.firstName + " " + this.lastName;
// }
or
const person = {
firstName:"Ajay",
lastName: "Kumar",
fullName: function () {
return this.firstName + " " + this.lastName;
}
}
const member = {
firstName:"Vijay",
lastName: "Kumar",
}
let fullName = person.fullName.bind(member);
console.log(fullName()) // Vijay Kumar
or
let fullName = person.fullName.bind(member)();
console.log(fullName) // Vijay Kumar
this is lost
let person = {
name: 'Ajay Kumar',
getName: function() {
console.log(this.name); //Ajay Kumar
}
};
console.log(person.getName()) //undefined
let globalLet = "This is a global variable";
function fun() {
let localLet = "This is a local variable";
console.log(globalLet); // This is a global variable
console.log(localLet); // This is a local variable
}
fun();
or
let globalLet = "This is a global variable";
function fun() {
let localLet = "This is a local variable";
}
fun();
console.log(globalLet); // This is a global variable
console.log(localLet); // localLet is not defined
or
Word of caution : Whenever you are declaring variables, always use the prefix
let. If you don’t use the let keyword, then the variables are by default created in the
global scope. For instance, in the above example.
let globalLet = "This is a global variable";;
function fun() {
localLet = "This is a local variable";
}
fun();
console.log(globalLet); // This is a global variable
console.log(localLet); // This is a local variable
Example : One of the most asked questions in interviews is the scenario where the
global as well as local variable has the same name. Let’s see what happens then.
let globalLet = "This is a global variable"
function fun() {
let globalLet = "This is a local variable"
}
fun();
console.log(globalLet); // This is a global variable
or
let globalLet = "This is a global variable";
function fun() {
let globalLet = "This is a local variable";
console.log(window.globalLet); // This is a global variable
}
fun();
Output: In this example, we have declared a local as well as global variable
“globalLet”. What matters here is the scope in which we are accessing it. In this
example, we are accessing it in global scope, so it will output the global variable as a
local variable is not present in its scope.
let globalLet = "This is a global variable";
function fun() {
let globalLet = "This is a local variable";
console.log(window.globalLet); // This is a global variable
}
fun();
Example 4 :
function fun(){
function fun2(){
i = 100;
}
fun2();
console.log(i); // 100
}
fun();
Output : In this example, as we didn’t use the keyword let, the variable “i” was
assumed to be declared in the global scope, and thus the output was 100.
function fun(){
function fun2(){
let i = 100;
}
fun2();
console.log(i); // i is not defined
}
fun();
Output : In this example, “i” became a local variable and thus was not
accessible
outside the scope of that function
function fun(){
if(true){
let i = 100;
}
console.log(i); // i is not defined
}
fun();
Output : hence in the above example we get an error instead of the value 100. In
earlier versions If we change the let to var we will get 100 as output as “if..else”
block
was not considered a block scope earlier, only functions were considered block scope.
function hello(name) {
var message = "hello " + name;
return function hello() {
console.log(message); // hello World
};
}
//generate closure
var helloWorld = hello("World");
//use closure
helloWorld();
Example 2 :
function counterwrapper(){
let count = 0;
return function(){
count++;
console.log(count) //1 //2
}
}
const updateCount= counterwrapper();
updateCount();
updateCount();
let name = 'Ajay';
function greeting() {
let message = 'Hi';
console.log(message + ' '+ name); // Hi Ajay
}
greeting();
function greeting() {
let message = 'Hi';
function sayHi() {
console.log(message); // Hi
}
sayHi();
}
greeting();
function greeting() {
let message = 'Hi';
function sayHi() {
console.log(message); // Hi
}
return sayHi;
}
let hi = greeting();
hi();
function greeting(message) {
return function(name){
return message + ' ' + name;
}
}
let sayHi = greeting('Hi');
let sayHello = greeting('Hello');
console.log(sayHi('Ajay')); // Hi Ajay
console.log(sayHello('Ajay')); // Hello Ajay
(function (){
// Function Logic Here.
})();
//********* or ***************//
(() => {
//...
})();
(function(){
let x="Ajay"
console.log(x) // Ajay
})();
Example 2 :
(function(a,b){
console.log(a+b) // 30
return a + b;
})(10,20);
Example 3 :
(function() {
var counter = 0;
function add(a, b) {
return a + b;
}
console.log(add(10,20)); // 30
}());
Example 4 :
(function() {
var counter = 0;
function add(a, b) {
return a + b;
}
console.log(add(10,20)); // 30
}());
Important Point
function myFunc()
{
console.log("Welcome to"); // Welcome to
// This will be executed after executing the previous log.
(function() {
console.log("Ajay Kumar"); // Ajay Kumar
})();
console.log("Hi There!"); // Hi There!
}
myFunc();
// Declaring the parameter required.
(function(dt) {
console.log(dt.toLocaleTimeString()); // 6:12:57 PM
// Passing the Parameter.
})(new Date());
let ajay = ()=> {
return "Hello Ajay";
}
console.log(ajay()) // Hello Ajay
let ajay = ()=> "Hello Ajay";
console.log(ajay()) // Hello Ajay
Advantages of Arrow functions:
const add= (x,y,z) => {
console.log(x+y+z) //60
}
add(10,20,30);
function sum(...args) {
console.log(...args) // 4 10 100 66
let sum = 0;
for (let i of args) {
sum += i;
}
return sum;
}
let x = sum(4, 10, 100, 66);
console.log(x); // 180
function sum(a,b,c) {
console.log(a,b,c) // 4 10 20
return a+b+c;
}
let x = sum(4, 10,20,6);
console.log(x); 34
function sum(a,b,c,d) {
console.log(a,b,c,d) // 4 10 undefined undefined
return a+b+c+d; // 14+undefined = NaN
}
let x = sum(4, 10);
console.log(x); //NaN
Example 3 :
// rest with function and other arguments
function fun(a, b, ...c) {
console.log(`${a} ${b}`); // Ajay Vijay
console.log(c); // [ "Lalit", "Sagar", "Bhuvnesh" ]
console.log(...c); // Lalit Sagar Bhuvnesh
console.log(c[0]); // Lalit
console.log(c.length); //3
console.log(c.indexOf("Lalit")); //0
}
fun("Ajay", "Vijay", "Lalit", "Sagar", "Bhuvnesh");
const combine = (...args) => {
return args.reduce(function (prev, curr) {
return prev + ' ' + curr;
});
};
let message = combine('JavaScript', 'Rest', 'Parameters'); // =>
console.log(message); // JavaScript Rest Parameters
function myDisplayer(ajay){
console.log("Ajay" +" "+ ajay)
}
function myFirst() {
myDisplayer("Hello"); // Ajay Hello
}
function mySecond() {
myDisplayer("Goodbye"); // Ajay Goodbye
}
myFirst();
mySecond();
function myDisplayer(result){
console.log("Result" +" "+ result) // Result 10
}
function myCalculator(num1,num2) {
let sum = num1+ num2;
return sum;
}
let result=myCalculator(5,5);
myDisplayer(result);
function myDisplayer(result){
console.log("Result" +" "+ result) // Result 10
}
function myCalculator(num1,num2) {
let sum = num1+ num2;
myDisplayer(sum);
}
myCalculator(5,5);
function myDisplayer(result) {
console.log("Result" + " " + result); // Result 10
}
function myCalculator(num1, num2, myCallback) {
let sum = num1 + num2;
myCallback(sum);
}
myCalculator(5, 5, myDisplayer);
function mainFunction(callback) {
console.log("Performing operation...");
setTimeout(function () {
callback("Operation complete");
}, 2000);
}
// Define the callback function
function callbackFunction(result) {
console.log("Result: " + result);
}
// Call the main function with the callback function
mainFunction(callbackFunction);
//Output
Performing operation...
Operation complete
// Callback function, passed as a parameter in the higher order function
function callbackFunction(){
console.log('I am a callback function'); //2 time I am a callback function
}
// higher order function
function higherOrderFunction(func){
console.log('I am higher order function') //1 time => I am higher order function
func()
}
higherOrderFunction(callbackFunction);
const arr = [1, 2, 3, 4, 5];
const output = arr.map((num) => num += 10)
console.log(arr); // [1, 2, 3, 4, 5]
console.log(output); // [11, 12, 13, 14, 15]
const users = [
{firstName: 'John', lastName: 'Doe', age: 25},
{firstName: 'Jane', lastName: 'Doe', age: 30},
{firstName: 'Jack', lastName: 'Doe', age: 35},
{firstName: 'Jill', lastName: 'Doe', age: 40},
{firstName: 'Joe', lastName: 'Doe', age: 45},
]
const result = users.map((user) => user.firstName + ' ' + user.lastName)
console.log(result); // ['John Doe', 'Jane Doe', 'Jack Doe', 'Jill Doe', 'Joe Doe']
function addcn(a, b, c) {
return a + b + c;
}
function addcn_curried(a)//curried function {
return function (b) {
return function (c) {
return a + b + c
}
}
}
let res = addcn(1, 2, 3);
console.log(res);
let mc1 = addcn_curried(1);
let mc2 = mc1(2);
let res2 = mc2(3);
console.log(res2);
let res3 = addcn_curried(1)(2)(3);
console.log(res3);
//Output :
6
6
6
// function constructor
function Person(name, job, yearOfBirth){
this.name= name;
this.job= job;
this.yearOfBirth= yearOfBirth;
}
// this will show Person's prototype property.
console.log(Person.prototype);
Output :
constructor: ƒ Person(name, job, yearOfBirth)
[[Prototype]]: Object
let user = {
getFullName: function () {
return this.firstName + " " + this.lastName;
},
getAge: function () {
let myAge = new Date().getFullYear() - this.age;
return myAge;
},
};
let student = {
firstName: "Ajay",
lastName: "Kumar",
age: 1998,
};
let teacher = {
firstName: "Gunjit",
lastName: "Chauhan",
age: 1990,
};
student.__proto__=user;
teacher.__proto__=user;
console.log(student.getFullName()); // Ajay kumar
console.log(student.getAge()); // 25
console.log(teacher.getFullName()); // Gunjit Chauhan
console.log(teacher.getAge()); //33
# | Debouncing | Throttling |
---|---|---|
1 | Debouncing waits for a certain time before invoking the function again. | Throttling limits the number of times the function can be called over a certain period. |
2 | Ensures that the function is called only once, even if the event is triggered multiple times. | Ensures that the function is called at a regular interval, even if the event is triggered multiple times. |
3 | Useful when you want to delay the invocation of a function until a certain period of inactivity has passed. | Useful when you want to list the Frequency of function calls. |
4 | Eg. You can debounce an async API request function that is called every time the user types in an input field. | Eg. You can throttle a slide change Function that is called every time the user clicks a button in a carousel. |