Skip to content

Instantly share code, notes, and snippets.

@gajjardarshithasmukhbhai
Last active March 24, 2023 19:49
Show Gist options
  • Save gajjardarshithasmukhbhai/b9009a298f14b6e2f8a753e6dfd620d1 to your computer and use it in GitHub Desktop.
Save gajjardarshithasmukhbhai/b9009a298f14b6e2f8a753e6dfd620d1 to your computer and use it in GitHub Desktop.
Java Script Various Concepts like ES6, Vanilla JavaScript, OOP Concepts of JavaScript and many more

JavaScript Deep Dive Concepts

Behind The Scenes of JavaScript & How it works, the weired Parts & ES5 vs ES6+

No ES5 ES6
1 Supporting in basically all browser including old IE Supported in modern browser can be transpiled to ES5
2 Only had var, not let or const Many New Features that help to write the cleaner and faster code
3 Syntax are same as like ES6 but quite some missing Features still under active development and big step forward

Understanding the Hoisting

  • In JavaScript, a variable can be declared after it has been used.
  • In other words; a variable can be used before it has been declared.
name = "Test";
console.log("name: ", name);
name: Test;
var name;

but if you are used the let so it will throw the error

name = "Test";
console.log("name: ", name); // Cannot access 'name' before initialization
name: Test;
let name;

Strict Mode and writing the good code

  • strict mode is basically used for follow the proper way & discipline of the rules in JavaScript ex. You will not do the hoisting kind of things after usign the 'use strict'

How code is parsed and compiled in JavaScript and Deep Dive into the JavaScript Engine

alt text

  • our Java Script Code will work in Java Script Engine through below Image

rHj331.png

  • Heap Memory is Persistent memory and Stack is temp memory

Object with the Function

const user = {
  name: "Darshit",
  subject: (subjectName) => {
    return `My Name is ${user.name} and My subject is ${subjectName}`;
  },
  address: "Dev Ashish Sky",
};
console.log(user.subject("Competive coding"));

Arrow Function in JavaScript

  • Fat Arrow function give return statment functionality rHRB10.png
const sum = (a, b) => a + b;
console.log("sum the value", sum);

Default Argument of the Expression

  • you will be used the default argument in function and variables
const name = () => `Hello`;
console.log(name() || "Yes");

Rest paramter in JavaScript

const myName = ({ name, ...otherValue }) => {
  console.log(otherValue);
};
myName({ name: "hello", subject: "12th standard", userName: "DarshitGajjar" });

Function inside the another Function

  • function inside function is basically use for the manipulate to third value
  • mostly this concept we are said like the Closure in JavaScript
const sum = (sumNumber) => {
  return (multiply = (multiplyNumber) => {
    return sumNumber * multiplyNumber;
  });
};

const number = sum(12);
console.log(number(12));

Callback Function in javascript

  • callBack Function is basically use when we call one function and calling one function through we perform the certain other operation so that time we used the callback
const callMe1 = (value, callback) => {
  callback("Your Value");
};
const callMe2 = (name) => {
  console.log("My Name is khan", name);
};
callMe1("Test", callMe2);

call and apply used in javaScript

  • The call() method is a predefined JavaScript method.

  • It can be used to invoke (call) a method with an owner object as an argument (parameter).

const person = {
  fullName: function () {
    return this.firstName + " " + this.lastName;
  },
};

const person1 = {
  firstName: "John",
  lastName: "Doe",
};
console.log(person.fullName.call(person1));
const person = {
  user: function (middleName, address) {
    return (
      this.firstName + " " + this.lastName + " " + middleName + " " + address
    );
  },
};

const person1 = {
  firstName: "Darshit",
  lastName: "Gajjar",
};
console.log(person.user.call(person1, "Hasmukhbhai", "Dev Ashish Sky"));

Array and String Series

  • Interable -> means in human terms object when you can use for for-loops
  • Various Methods for Creating the Arrays in JavaScript

alt text

  • for array prespective mostly we use the Below Methods
    1. const data = [1,2,3]; // more cleaner and perspective base more good
    1. If you want to convert string into so that time this method so much helpful
    • ex.Array.from("hi!"); [O/P] ['h','i','!']

Splice and Slice in JavaScript

Splice
  • splice(start, deleteCount, item1)
  • start: The index at which to start changing the array.
  • deleteCount: An integer indicating the number of elements in the array to remove from start.
  • splice(start)
  • splice(start, deleteCount)
  • splice(start, deleteCount, item1)
  • splice(start, deleteCount, item1, item2, itemN)
const name = ["Gajjar", "Darshit", "Hasmukhbhai", "Hello"];
name.splice(1,0,"Good);
o/p: name => ["Gajjar","Good","Darshit","Hasmukhbhai","Hello"]
name.splice(1,1,"Good");
o/p: name => ["Gajjar", "Good", "Hasmukhbhai", "Hello"]
name.splice(1,1,"hello"); => First Character for replacing the string, Second one removing after that string
o/p: name => ["Gajjar", "hello"]
  • Splice basically used for different Application like to accept certain value in Array
name.splice(4);
console.log(name); // O/P :=> [ 'Hello', 'Name', 'Test', 'How Are You ?' ]
Slice
  • Slice Array basically Return the Brand New Copy of the Array
  • slice()
  • slice(start)
  • slice(start, end)
start:
Zero-based index at which to start extraction.

A negative index can be used, indicating an offset from the end of the sequence. slice(-2) extracts the last two elements in the sequence.
---------------------------------------------------------------------
end:
The index of the first element to exclude from the returned array.
slice extracts up to but not including end.
For example, slice(1,4) extracts the second element through the fourth element (elements indexed 1, 2, and 3).
const person = ["darshit", "bhavin"];
const person2 = person;
- If we will push the push the value in person it automatically reflect person2.
- so person2 refer the person variable.
- so we need to shaddow copy for that

solution:

const person = ["darshit","bhavin"];
const person2 = person.slice();
const person.push("Nikunj");
console.log(person); => ["darshit","bhavin","Nikunj"]
console.log(person2); => ["darshit","Bhavin"]

code

const name = [0,11,12,13];
console.log(name.slice(2)); => [12,13]
index 0 => 0
index 1 => 11
index 2 => 12
index 3 => 13
- So it will take remove before 2 index and consider after 2 index
- Behaviour is same in slice and Splice
- console.log(name.slice(1,2)); => O/P : [11,12,13]
let name = [0,11,12,13];
console.log(name.slice(-3,-1)); => [11,12]
- In Right To Left it will go -3 Index => 11 then after consider -1 means
[11,12] but not 13
Concat
  • Concat is used to bind the data in Array

  • After Adding element if you want to create the shallow copy so that time it is useful

  • Ex.

let name = [11,12]
const newName = name.concat([13,14]);
console.log(newName); o/p => [11,12,13,14]
name.push(22);
console.log(name); o/p => [11,12,22]
console.log(newName); o/p => [11,12,13,14]
last Index of
  • Last index of is not working for Object
  • It Only Work for the Array ex.
const name = [11,12,13,14]
const person = [{name: "darshit"}, {name: "gajjar"}]
console.log(name.indexOf(14)); o/p => 3
console.log(person.indexOf({name:"darshit"})); o/p => -1 => It won't work for object
Find
const person = [{name: "darshit"}, {name: "hasmukh"}]
const indexOfPerson = person.find((person, index, personArray) => {
    return person.name === "hasmukh"
})
console.log(indexOfPerson); o/p => { name: 'hasmukh' }
- personArray return entire Array
Find Index
const person = [{name: "darshit"}, {name: "hasmukh"}]
const indexOfPerson = person.findIndex((person, index, personArray) => {
    return person.name === "hasmukh"
})
console.log(indexOfPerson); o/p => 1
- personArray return entire Array
Some Function
const fruits = [
    { name: 'apple', color: 'red' },
    { name: 'banana', color: 'yellow' },
    { name: 'grape', color: 'purple' }
];

function test() {
  const isAnyRed = fruits.some(f => f.color == 'red');
  console.log(isAnyRed); // true
}
ForEach Function
  • forEach Function Not Return Anything
const taxPrice = [10.99,11.99,12.99];
const tax = 5.2;
const taxtAdjustmenr = [];
taxPrice.forEach((price,index,prices) => {
    const priceObj = {index: index, taxAdjPice: price * (1+tax) }
    taxtAdjustmenr.push(priceObj);
});

console.log(taxtAdjustmenr); // [ { index: 0, taxAdjPice: 68.138 },{ index: 1, taxAdjPice: 7433800000000001 },{ index: 2, taxAdjPice: 80.538 } ]
Map Function
  • Map Function Return unlike forEach function
  • Map set the Value as Array Form
const taxPrice = [10.99,11.99,12.99];
const tax = 5.2;
const taxtAdjustmenr = [];
const value = taxPrice.map((price,index,prices) => {
    const priceObj = {index: index, taxAdjPice: price * (1+tax) }
    return priceObj;
});

console.log(value); // [ { index: 0, taxAdjPice: 68.138 },{ index: 1, taxAdjPice: 7433800000000001 },{ index: 2, taxAdjPice: 80.538 } ]
Reduce Function
const prices = [1,2,3,4];
const sum = prices.reduce((previousValue,currentValue,currentIndex, prices) => {
    return currentValue + previousValue;
},15);
console.log(sum); //O/p => 25
// Reduce consist of the Previous Value, currentValue and it is also flexible so it give the intialValue
// arrangement like ==> 15, so Function will start so it will some ==> 1+2+3+4 ==> 10 + 15 ==> Intial Value
Include
const name = [11,12,13,14];
console.log(name.includes(15)); // true
Array & String ,Split and Join
const person =  "new York; 10:99; Ahmedabad";
const value = person.split(";");
console.log(value); // ['new York','10:99','Ahmedabad']
// If You Want to Join Array into the String through this method
const personJoin = ["Max", "SchrujMuller"];
console.log(personJoin.join("-")); // Array converted into the String O/p => Max-ShrujMuller
UnderStanding the Array Destructuring
const nameData = ["I", "💓", "Java Script", "python", "Ruby"];
const [firstName, lastName, ...otherValue] = nameData;
console.log(firstName); // o/p => I
Map and Set Overview

uu0iYG.png

Closer Look in Objects

uu9jFS.png

Adding in Object and Calling The Function
let newMovie = {
    name: "start",
    theater: "ejnejne",
    age: (value) => {
        return `My Name is ${value}`
    }

}
newMovie.isHealthOkay = "YES";
console.log(newMovie); // { name: 'start',theater: 'ejnejne',age: [λ: age],isHealthOkay: 'YES' }
console.log(newMovie.age("Khan")); // My Name is Khan
Accessing the Difficult / Dynamic Key through this Method
const person = {
    name: "Darshit",
    "first name +++": "Gajjar"
}
console.log(person["first name +++"]); // Gajjar
Property Types and Property Order
  • we know In array the key are always be in Ascending Order so this same thing for Object
const number = {5: "darshit", 2: "gajjar"};
console.log(number); // O/P => {2: "gajjar", 5: "darshit"}
Set the Dynamic Key in Object
const ahmedabad = "location";
const user = {
    name: "darshit",
    age: 22,
    subject : "Computer Science",
    [ahmedabad]: "Bopal Ambli"
}
console.log(user); // { name: 'darshit',age: 22,subject: 'Computer Science',location: 'Bopal Ambli' }
get the all object dynamic properties
const ahmedabad = "location";
const user = {
    name: "darshit",
    age: 22,
    subject : "Computer Science",
    [ahmedabad]: "Bopal Ambli"
}
for(let key in user) {
    console.log(user[key]); // darshit 22 Computer Science Bopal Ambli
}
spread Operator in Java Script
  • spread operator is used in varierty of Application like cretaing the shallow of property
const person = {
    name: "Darshit",
    age: 23,
    subject: "computer science"
};
const newPerson = {...person, isHaveSuperPower: true};
we have used the same person but adding the additional property
Object Assign
  • as best practice we have to used the spread operator
  • but Object Assign another way to do that
  • but Object Assign has multiple browser support
const person = {name: "max"}
const person2 = object.assign(name, {age: 25}) // object.assign(target, source)
O/P => person2 = {name: "max", age: 25}
Object Destructuring
const person = {
    name: "Darshit",
    lastName: "Gajjar",
    Address: "Dev Ashish Sky"
}

const {name, ...user} = person;
console.log(user); // { lastName: 'Gajjar', Address: 'Dev Ashish Sky' }
console.log(name); // Darshit
checking property existence

-> If object key is not exist so in throw undefined as value -> So In object key undefined means not exist

const person = {
    name: "Gajjar",
    address: "Dev Ashish Sky",
    lastName: "Gajjar",
};
const checkPerson = ('sirName' in person) ? "Hello" : "Guruji";
console.log('checkPerson: ', checkPerson); // checkPerson: Guruji
This Keyword
  • This keyword basically responsible for who calling the function. which function you need to retun back the response

  • Note
    • An arrow function doesn’t have its own this value and the arguments object. Therefore, you should not use it as an event handler, a method of an object literal, a prototype method, or when you have a function that uses the arguments object
    • Instead of use the normal JavaScript Function
const mySirName = "sirName";
const person = {
    specialPerson: {
        name: "Darshit",
        [mySirName]: "Gajjar",
        address: "Ahmedabad",
    },
    getFullAddress() {
        return `Name: ${this.specialPerson.name}  ${this.specialPerson.address}`
    }
}
console.log(person.getFullAddress());
Getter and Setter Concept
  • getter and Setter add one addtional level of security in Java Script
  • Practical schenario : In normal Obj you're able to update the object. but it caused problem when you want to give extra level of securtiy like you unable to set object key
  • so that time this Getter and setter concepts are very useful
const person = {
    bio: "very Humble and Punctual person",
    set name(value) { // setter work like key
        if(value.trim() === "") {
            this._name = 'DEFAULT';
            return;
        }
        this._name = value;
    },
    get name () {
        return this._name; // _ basically this conversation precedence used for to display private variable variable
    }
}
person.name = "darshit gajjar";
console.log(person.name); // darshit gajjar
Without setter try to set the value so what Happen ?
  • If you do without setter it will throw the error
const person = {
  bio: "very Humble and Punctual person",
  get name () {
      return this._name; // _ basically this conversation precedence used for to display private variable variable
  }
}
person.name = "darshit gajjar"; // uncaught TypeError: cannot set the property
console.log(person.name);
Java Script Advanced concepts like Object Oriented Programming

u1fuJC.png

class PhotoList {
    constructor (photoTitle, photoPrice, photoUrl) {
        this.photoTitle = photoTitle; // this keyword refer the class property keep in mind this point
        this.photoPrice = photoPrice;
        this.photoUrl = photoUrl;
    }
}

const imageList = {
    photoGallery : [new PhotoList('Darshit Gajjar','$2.56','https://jsshshs/sjhs.png'),
    new PhotoList('Hasmukh Gajjar','$3.2', 'https://sjhsjhsh/sjjshs.png'),
    new PhotoList('Anandi Gajjar', '$23.3', 'https://sjshs/sjhs.png')]
};
console.log(imageList);
// O/P :
// { photoGallery:
//     [ PhotoList { photoTitle: 'Darshit Gajjar',
//         photoPrice: '$2.56',
//         photoUrl: 'https://jsshshs/sjhs.png' },
//       PhotoList { photoTitle: 'Hasmukh Gajjar',
//         photoPrice: '$3.2',
//         photoUrl: 'https://sjhsjhsh/sjjshs.png' },
//       PhotoList { photoTitle: 'Anandi Gajjar',
//         photoPrice: '$23.3',
//         photoUrl: 'https://sjshs/sjhs.png' } ] }

u1fLnT.png

Static Keyword in Java Script
  • Static Method is Utility Function that are used to call method directly through class method
class Person {
    static name = "Darshit";
    constructor() {}
    static age() {
        return "Hi, I will touch 25 LPA package under 3 years";
    }
}
console.log(Person.age());
When to use Classes

u1H1PF.png

Inheritance in Java Script :: Video No:16 :: Module 10,11 and 12
  • Work in Progress ################################################################### ##################################################################### ################################################################## ##########################################

More On Number and String

Generate the Random Number Between 1 to 10 programme
const randomNumberGenearte = (min,max) => {
    const randomNumber = Math.floor(Math.random()*(max-min) + 1)
    console.log('randomNumber: ', randomNumber);
}
randomNumberGenearte(1,10)
StartsWith Method in JavaScript
  • The startsWith() method determines whether a string begins with the characters of a specified string, returning true or false as appropriate.
const str1 = 'Saturday night plans';

console.log(str1.startsWith('Sat'));
// expected output: true

console.log(str1.startsWith('at', 2));
// expected output: false
Trim Method in JavaScript
  • The trim() method removes whitespace from both ends of a string and returns a new string, without modifying the original string
const greeting = '   Hello world!   ';

console.log(greeting);
// expected output: "   Hello world!   ";

console.log(greeting.trim());
// expected output: "Hello world!";
Repeat Method in JavaScript
const chorus = 'Because I\'m happy. ';

console.log(`Chorus lyrics for "Happy": ${chorus.repeat(27)}`);

// expected output: "Chorus lyrics for "Happy": Because I'm happy. Because I'm happy. Because I'm happy. Because I'm happy. Because I'm happy. Because I'm happy. Because I'm happy. Because I'm happy. Because I'm happy. Because I'm happy. Because I'm happy. Because I'm happy. Because I'm happy. Because I'm happy. Because I'm happy. Because I'm happy. Because I'm happy. Because I'm happy. Because I'm happy. Because I'm happy. Because I'm happy. Because I'm happy. Because I'm happy. Because I'm happy. Because I'm happy. Because I'm happy. Because I'm happy. "

Async Call, Working With CallBacks, Promises and Async and Await

JavaScript Engine Works As Single Thread

68747470733a2f2f692e696d2e67652f323032322f30372f30312f75736e596a722e706e67

Blocking The Code & Event Loop Concept

How Event Loop and JS Engine Works When Asynchronous Code Call

68747470733a2f2f692e696d2e67652f323032322f30372f30312f75446d66534d2e706e67

  • Event Loop : Event Loop is Js Machanism it will check every time anything remaining in Code or Not. If It will there so it will pick and put in the Java Script Engine

  • when Any Browser Api Find Like setTimeOut or setInterval so it will go Java Script Engine and then After goes on the Browser API section so Browser Handle Async Manner.

  • But Js Engine not stop it's working still it will continue his process and add other function and it's code.all things goes to the

  • Message Queue Works like toDo kind of let say Any Asynchronous code or when stack full so remaining thing add in message queue. so once Java script Execution complete one by one it will execute.

  • And event loop has key role to doing this.

Promise in Async Code
  • Promise is nothing But the Object. That is Used to create the Async Kind Of code.
  • So wither Resolve or Reject so both the side are possible
Catch Block Follow The Order
  • We are not used Catch Block Anywhere Else Ex. This is the Order We are follow when we are used the Catch
getPosition().then(posData => {
  const setTime = `${posData} Hi`
  return setTime;
  })
.then(dummyData => {
  const modifyData = dummyData + 1;
  return modifyData;
})
.catch(err => {
  return `Ohh.....I Got Error ${err}`;
});

But If we are modify this Order so what happen Ex.

getPosition()
.then(posData => {  ----------------------------(1)
  const setTime = `${posData} Hi`
  return setTime;
  })
  .catch(err => {  ------------------------------(2)
  return `Ohh.....I Got Error ${err}`;
})
.then(dummyData => { ----------------------------(3)
  const modifyData = dummyData + 1;
  return modifyData;
})
  • Problem of Above code Order (1) Execute if Any thing Wrong Happen in order (1). so that is goes to the catch block but problem is our order No (3) will not work but in this case it works.
  • Because After Catch As per our JavaScript behavirour it goes to order no (3) also.
  • And run that code so it happer our desired output
How Catch Structure Help The our Code
  • If you Want to not crash something or If you want to skip something
  • So this things is somuch Important
  • You will Also Use Multiple Catch Blocks ex.
getFun()
.then(data => {
  const myName = `${data} Ye Hello`;
  return myName;
})
.catch(err => err)
.then(afterSkip => {
  const changeTitle = `${afterSkip} whatsApp`;
  return changeTitle;
})
.catch(err => {
  return `${err} e Hello Hows The going`;
})
Deep Copies Issue In React & Object Copies in JavaScript
  • Best Article : Deep Copies Issue

  • Best Article For TypeScript : TypeScript Concepts

  • If you want to create deep copies without JSON.parse(JSON.string()) so you will use Lodash Function _.clonedeep() for Deep Copies.

const food = { beef: '🥩', bacon: '🥓' }


// "Spread"
{ ...food }


// "Object.assign"
Object.assign({}, food)


// "JSON"
JSON.parse(JSON.stringify(food))

// RESULT:
// { beef: '🥩', bacon: '🥓' }
Promise All, Promise Race, Promise resetteled

Promise Race :

  • Promise Race Condition is used when You have multiple Promise and You want to consider the Fastest Promise so that time Promise Race is used.
  • Note: If Fastest Promise is Resolved so it will not care about the Other promise.it means one resolved and other is not resolved but still it not throw the Error
Promise.race([getPosition(),setTime(1000)]).then(data => {
  console.log(data);
});

Promise All :

  • It will Resolved the all promises Ex.
Promise.all([getPosition(),setTime(1000)]).then(promiseData => {
  console.log(promiseData);
});

Promise all Settled :

  • It will Either Reject All promise or Accept the all promises Ex.
Promise.allSettled([getPosition(),setTime(1000)]).then(promiseData => {
  console.log(promiseData);
});

It return the Output like this one

[{
  status: "fullfilled",
  value: "....."
},{
  status: "fullfilled",
  value: "....."
}]
Https Requests

Screenshot 2022-08-08 002921

Fetch API Use

Screenshot 2022-08-08 003517

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment