From 26133300100a3475ab2b25d233f7f4a93bfa229d Mon Sep 17 00:00:00 2001 From: ShubhamSKadam Date: Tue, 27 Dec 2022 11:01:27 +0530 Subject: [PATCH 01/25] Added contributing steps --- CONTRIBUTING.md | 4 ++++ 1 file changed, 4 insertions(+) create mode 100644 CONTRIBUTING.md diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..3789cac --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,4 @@ +## Steps to Contribute : + +1. Feel free to open a pull request of any learnings that I might have missed. +2. Document it appropriately. \ No newline at end of file From ad5fb04b143cf854d6ef8b822f30b6394fcc56d3 Mon Sep 17 00:00:00 2001 From: ShubhamSKadam Date: Wed, 28 Dec 2022 14:39:42 +0530 Subject: [PATCH 02/25] Creating built in methods in objects --- 8_Objects_in_detail/objects.md | 24 ++++++++++++++++++++++++ 8_Objects_in_detail/objects2.js | 19 +++++++++++++++++++ 2 files changed, 43 insertions(+) create mode 100644 8_Objects_in_detail/objects2.js diff --git a/8_Objects_in_detail/objects.md b/8_Objects_in_detail/objects.md index 649aa1a..23e6622 100644 --- a/8_Objects_in_detail/objects.md +++ b/8_Objects_in_detail/objects.md @@ -40,3 +40,27 @@ const property = "age"; console.log(person[property]); // 23 ``` +#### Built-in-Methods + +```js +const dog = { + name: "Fluffy", + bark: () => { + console.log("woof,woof"); + }, +}; + +dog.bark(); // woof,woof + +// this keyword +const car = { + name: "Lambo", + model: 2019, + Details: function () { + console.log(this.name, this.model); + }, +}; + +car.Details(); // Lambo 2019 +``` + diff --git a/8_Objects_in_detail/objects2.js b/8_Objects_in_detail/objects2.js new file mode 100644 index 0000000..94de0c0 --- /dev/null +++ b/8_Objects_in_detail/objects2.js @@ -0,0 +1,19 @@ +const dog = { + name: "Fluffy", + bark: () => { + console.log("woof,woof"); + }, +}; + +dog.bark(); // woof,woof + +// this keyword +const car = { + name: "Lambo", + model: 2019, + Details: function () { + console.log(this.name, this.model); + }, +}; + +car.Details(); // Lambo 2019 From 8163f5a01aa826b6cd4956c0754278b8660cd1b0 Mon Sep 17 00:00:00 2001 From: Sandeep Kushwaha Date: Sun, 1 Jan 2023 10:50:47 +0530 Subject: [PATCH 03/25] Update variablesDataTypes.md --- 1_variables_and_data_types/variablesDataTypes.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/1_variables_and_data_types/variablesDataTypes.md b/1_variables_and_data_types/variablesDataTypes.md index 4a6a151..1b015b6 100644 --- a/1_variables_and_data_types/variablesDataTypes.md +++ b/1_variables_and_data_types/variablesDataTypes.md @@ -41,7 +41,7 @@ There are 3 ways of representing a string: We can use Single Quote or Double Quote if we just want to statically display it. ```js -const singleQuote = "Hello"; +const singleQuote = 'Hello'; const doubleQuote = "Hello"; ``` @@ -115,4 +115,4 @@ console.log(typeof arr); // object // date is an object; const date = new Date(); -console.log(typeof date); // object \ No newline at end of file +console.log(typeof date); // object From fd11debb4cc7b4a5bc12bff684f65464a7e2310e Mon Sep 17 00:00:00 2001 From: ShubhamSKadam Date: Sun, 1 Jan 2023 19:33:08 +0530 Subject: [PATCH 04/25] Additional inbuilt object methods --- 8_Objects_in_detail/object.js | 94 +++++++++++++++++++++++++++++---- 8_Objects_in_detail/objects.md | 73 +++++++++++++++++++++++++ 8_Objects_in_detail/objects2.js | 1 + 3 files changed, 158 insertions(+), 10 deletions(-) diff --git a/8_Objects_in_detail/object.js b/8_Objects_in_detail/object.js index 7d995d0..812d0b0 100644 --- a/8_Objects_in_detail/object.js +++ b/8_Objects_in_detail/object.js @@ -15,19 +15,93 @@ // console.log(person); // Dot notation -const person = { - firstName: "Shubham", +// const person = { +// firstName: "Shubham", +// }; + +// person.dog = { +// name: "fluffy", +// age: 2, +// }; + +// person.age = 23; +// console.log(person.dog.age); + +// Square bracket notation +// const property = "age"; + +// console.log(person[property]); + +// Object.keys() creates an array containg the keys of an object. + +// Intialize an object +const employee = { + boss: "Shubham", + secretary: "Samarth", + sales: "John", + accountant: "Oscar", }; -person.dog = { - name: "fluffy", - age: 2, +// Let's say we want to see all the positions(keys) in the employee object +const positions = Object.keys(employee); +console.log(positions); + +// Object.values() creates an array containg the values of an object. +const session = { + id: 1, + time: `26-July-2022`, + device: "Mobile", + browser: "Chrome", }; -person.age = 23; -console.log(person.dog.age); +const sessionInfo = Object.values(session); +console.log(sessionInfo); -// Square bracket notation -const property = "age"; +// Object.entries() creates an array containg the key/value of an object. +const operatingSystem = { + name: "Ubuntu", + version: "20.04", + license: "Open Source", +}; + +const entries = Object.entries(operatingSystem); + +entries.forEach((entry) => { + let key = entry[0]; + let value = entry[1]; + + console.log(`${key}:${value}`); +}); + +// Object.freeze() prevents modification to +// properties and values of an object, +// and prevents properties from being +// added or removed from an object + +// Intialize an object +// const user = { +// username: "Shubham", +// password: "12345", +// }; + +// const admin = Object.freeze(user); + +// user.username = "Samarth"; // Trying to overwrite the object username +// console.log(user.username); // Shubham (remains the same); + +// Object.seal() prevents new properties +// from being added to an object, +// but allows the modification of existing properties +// Intialize an object + +const user = { + username: "Shubham", + password: "12345", +}; + +const newUser = Object.seal(user); + +newUser.username = "Samarth"; // The username will be changed +newUser.age = 23; // the age property will not be added because we applied Object.seal() -console.log(person[property]); +console.log(user); diff --git a/8_Objects_in_detail/objects.md b/8_Objects_in_detail/objects.md index 23e6622..bf1fef3 100644 --- a/8_Objects_in_detail/objects.md +++ b/8_Objects_in_detail/objects.md @@ -64,3 +64,76 @@ const car = { car.Details(); // Lambo 2019 ``` +#### Methods + +```js +// Object.keys() creates an array containg the keys of an object. + +// Intialize an object +const employee = { + boss: "Shubham", + secretary: "Samarth", + sales: "John", + accountant: "Oscar", +}; + +// Let's say we want to see all the positions(keys) in the employee object +const positions = Object.keys(employee); +console.log(positions); // [ 'boss', 'secretary', 'sales', 'accountant' ] + +// Object.values() creates an array containg the values of an object. +const session = { + id: 1, + time: `26-July-2022`, + device: "Mobile", + browser: "Chrome", +}; + +const sessionInfo = Object.values(session); +console.log(sessionInfo); // [ 1, '26-July-2022', 'Mobile', 'Chrome' ] + +// Object.entries() creates an array containg the key/value of an object. +const operatingSystem = { + name: "Ubuntu", + version: "20.04", + license: "Open Source", +}; + +const entries = Object.entries(operatingSystem); + +console.log(entries); // [ + [ 'name', 'Ubuntu' ], + [ 'version', '20.04' ], + [ 'license', 'Open Source' ] +] + +// Intialize an object +const user = { + username: "Shubham", + password: "12345", +}; + +const admin = Object.freeze(user); + +user.username = "Samarth"; // Trying to overwrite the object username +console.log(user.username); // Shubham (remains the same); + +// Object.seal() prevents new properties +// from being added to an object, +// but allows the modification of existing properties +// Intialize an object + +const user = { + username: "Shubham", + password: "12345", +}; + +const newUser = Object.seal(user); + +newUser.username = "Samarth"; // The username will be changed +newUser.age = 23; // the age property will not be added because we applied Object.seal() + +console.log(user);// { username: 'Samarth', password: '12345' } + +``` + diff --git a/8_Objects_in_detail/objects2.js b/8_Objects_in_detail/objects2.js index 94de0c0..9346c31 100644 --- a/8_Objects_in_detail/objects2.js +++ b/8_Objects_in_detail/objects2.js @@ -17,3 +17,4 @@ const car = { }; car.Details(); // Lambo 2019 + From 6898a103b96b161ca0adb77df7fb95d58edf0b39 Mon Sep 17 00:00:00 2001 From: ShubhamSKadam Date: Mon, 2 Jan 2023 17:21:08 +0530 Subject: [PATCH 05/25] Cloning by Reference and Shallow Cloning --- 9_Value_vs_Reference/script.js | 25 +++++++++++++++ 9_Value_vs_Reference/value_vs_reference.md | 36 ++++++++++++++++++++++ 2 files changed, 61 insertions(+) create mode 100644 9_Value_vs_Reference/script.js create mode 100644 9_Value_vs_Reference/value_vs_reference.md diff --git a/9_Value_vs_Reference/script.js b/9_Value_vs_Reference/script.js new file mode 100644 index 0000000..bab97ed --- /dev/null +++ b/9_Value_vs_Reference/script.js @@ -0,0 +1,25 @@ +// const animals = ["dogs", "cats"]; + +// const otherAnimals = animals; + +// animals.push("pig"); + +// console.log(animals); // [ 'dogs', 'cats', 'pig' ] +// We get the same output for otherAnimals too, +// because the otherAnimals is also referencing the same memory +// as the animals. +// console.log(otherAnimals); // [ 'dogs', 'cats', 'pig' ] + +// Cloning Arrays +// 1st way : Spread Operator +const numbers = [1, 2, 3, 4]; +const copiedNumbers = numbers; + +// Using spread Opeator, +// Also known as Shallow Cloning +const newNumbers = [...numbers]; + +numbers.push(5); +console.log(numbers); // [ 1, 2, 3, 4, 5 ] +console.log(copiedNumbers); // [ 1, 2, 3, 4, 5 ] +console.log(newNumbers); // [ 1, 2, 3, 4 ] diff --git a/9_Value_vs_Reference/value_vs_reference.md b/9_Value_vs_Reference/value_vs_reference.md new file mode 100644 index 0000000..6fa7bf2 --- /dev/null +++ b/9_Value_vs_Reference/value_vs_reference.md @@ -0,0 +1,36 @@ +#### Copy by Reference + +```js +const animals = ["dogs", "cats"]; + +const otherAnimals = animals; + +animals.push("pig"); + +console.log(animals); // [ 'dogs', 'cats', 'pig' ] +// We get the same output for otherAnimals too, +// because the otherAnimals is also referencing the same memory +// as the animals. +console.log(otherAnimals); // [ 'dogs', 'cats', 'pig' ] + +// The behaviour is same even with respect to objects. +``` + +#### Shallow Cloning + +```js +// Cloning Arrays +// 1st way : Spread Operator +const numbers = [1, 2, 3, 4]; +const copiedNumbers = numbers; + +// Using spread Opeator, +// Also known as Shallow Cloning +const newNumbers = [...numbers]; + +numbers.push(5); +console.log(numbers); // [ 1, 2, 3, 4, 5 ] +console.log(copiedNumbers); // [ 1, 2, 3, 4, 5 ] +console.log(newNumbers); // [ 1, 2, 3, 4 ] +``` + From 7dbed120f0fa037878ba5188267360c613b7a19b Mon Sep 17 00:00:00 2001 From: ShubhamSKadam Date: Mon, 2 Jan 2023 17:33:09 +0530 Subject: [PATCH 06/25] Cloning arrays and objects --- 9_Value_vs_Reference/script.js | 44 ++++++++++++++++++---- 9_Value_vs_Reference/value_vs_reference.md | 32 ++++++++++++++++ 2 files changed, 69 insertions(+), 7 deletions(-) diff --git a/9_Value_vs_Reference/script.js b/9_Value_vs_Reference/script.js index bab97ed..ad89a97 100644 --- a/9_Value_vs_Reference/script.js +++ b/9_Value_vs_Reference/script.js @@ -12,14 +12,44 @@ // Cloning Arrays // 1st way : Spread Operator -const numbers = [1, 2, 3, 4]; -const copiedNumbers = numbers; +// const numbers = [1, 2, 3, 4]; +// const copiedNumbers = numbers; // Using spread Opeator, // Also known as Shallow Cloning -const newNumbers = [...numbers]; +// const newNumbers = [...numbers]; -numbers.push(5); -console.log(numbers); // [ 1, 2, 3, 4, 5 ] -console.log(copiedNumbers); // [ 1, 2, 3, 4, 5 ] -console.log(newNumbers); // [ 1, 2, 3, 4 ] +// numbers.push(5); +// console.log(numbers); // [ 1, 2, 3, 4, 5 ] +// console.log(copiedNumbers); // [ 1, 2, 3, 4, 5 ] +// console.log(newNumbers); // [ 1, 2, 3, 4 ] + +// 2nd way : Array.slice() +// const numbers = [1, 2, 3, 4]; +// const copiedNumbers = numbers; + +// Using spread Opeator, +// Also known as Shallow Cloning +// const newNumbers = numbers.slice(); + +// numbers.push(5); +// console.log(numbers); // [ 1, 2, 3, 4, 5 ] +// console.log(copiedNumbers); // [ 1, 2, 3, 4, 5 ] +// console.log(newNumbers); // [ 1, 2, 3, 4 ] + +// Cloning Objects +// 1st way : Spread Operator +// const person = { name: "John", age: 22 }; +// const newPerson = { ...person }; + +// person.age = 23; +// console.log(person); // { name: 'John', age: 23 } +// console.log(newPerson); // { name: 'John', age: 22 } + +// 2nd way : Object.assign() +const person = { name: "John", age: 22 }; +const newPerson = Object.assign({},person); + +person.age = 23; +console.log(person); // { name: 'John', age: 23 } +console.log(newPerson); // { name: 'John', age: 22 } diff --git a/9_Value_vs_Reference/value_vs_reference.md b/9_Value_vs_Reference/value_vs_reference.md index 6fa7bf2..9e20dd5 100644 --- a/9_Value_vs_Reference/value_vs_reference.md +++ b/9_Value_vs_Reference/value_vs_reference.md @@ -32,5 +32,37 @@ numbers.push(5); console.log(numbers); // [ 1, 2, 3, 4, 5 ] console.log(copiedNumbers); // [ 1, 2, 3, 4, 5 ] console.log(newNumbers); // [ 1, 2, 3, 4 ] + +// 2nd way : Array.slice() +const numbers = [1, 2, 3, 4]; +const copiedNumbers = numbers; + +// Using spread Opeator, +// Also known as Shallow Cloning +const newNumbers = numbers.slice(); + +numbers.push(5); +console.log(numbers); // [ 1, 2, 3, 4, 5 ] +console.log(copiedNumbers); // [ 1, 2, 3, 4, 5 ] +console.log(newNumbers); // [ 1, 2, 3, 4 ] +``` + +```js +// Cloning Objects +// 1st way : Spread Operator +const person = { name: "John", age: 22 }; +const newPerson = { ...person }; + +person.age = 23; +console.log(person); // { name: 'John', age: 23 } +console.log(newPerson); // { name: 'John', age: 22 } + +// 2nd way : Object.assign() +const person = { name: "John", age: 22 }; +const newPerson = Object.assign({},person); + +person.age = 23; +console.log(person); // { name: 'John', age: 23 } +console.log(newPerson); // { name: 'John', age: 22 } ``` From f4e4f25fa8b3fc9a921d4874ac7bb008b45157c9 Mon Sep 17 00:00:00 2001 From: ShubhamSKadam Date: Mon, 2 Jan 2023 17:47:33 +0530 Subject: [PATCH 07/25] Deep cloning --- 9_Value_vs_Reference/script.js | 37 +++++++++++++++++++--- 9_Value_vs_Reference/value_vs_reference.md | 29 +++++++++++++++++ 2 files changed, 61 insertions(+), 5 deletions(-) diff --git a/9_Value_vs_Reference/script.js b/9_Value_vs_Reference/script.js index ad89a97..bdd1779 100644 --- a/9_Value_vs_Reference/script.js +++ b/9_Value_vs_Reference/script.js @@ -47,9 +47,36 @@ // console.log(newPerson); // { name: 'John', age: 22 } // 2nd way : Object.assign() -const person = { name: "John", age: 22 }; -const newPerson = Object.assign({},person); +// const person = { name: "John", age: 22 }; +// const newPerson = Object.assign({},person); + +// person.age = 23; +// console.log(person); // { name: 'John', age: 23 } +// console.log(newPerson); // { name: 'John', age: 22 } + +// Deep Cloning +// We can create a shallow copy of person object +// but we have to do it for all the inner objects as well. +// To solve this we can do a deep cloning where we make +// use of JSON.stringify() method + +const person = { + name: "Shubham", + car: { + brand: "BMW", + color: "blue", + wheels: 4, + }, +}; + +const newPerson = JSON.stringify(person); + +// newPerson will be in the form of string, +// to convert it back to an object, +// we use JSON.parse(); + +const updatedPerson = JSON.parse(newPerson); -person.age = 23; -console.log(person); // { name: 'John', age: 23 } -console.log(newPerson); // { name: 'John', age: 22 } +updatedPerson.car.color = "red"; +console.log(person); // { name: 'Shubham', car: { brand: 'BMW', color: 'blue', wheels: 4 } } +console.log(updatedPerson); // { name: 'Shubham', car: { brand: 'BMW', color: 'red', wheels: 4 } } diff --git a/9_Value_vs_Reference/value_vs_reference.md b/9_Value_vs_Reference/value_vs_reference.md index 9e20dd5..eee28ff 100644 --- a/9_Value_vs_Reference/value_vs_reference.md +++ b/9_Value_vs_Reference/value_vs_reference.md @@ -66,3 +66,32 @@ console.log(person); // { name: 'John', age: 23 } console.log(newPerson); // { name: 'John', age: 22 } ``` +```js +// Deep Cloning +// We can create a shallow copy of person object +// but we have to do it for all the inner objects as well. +// To solve this we can do a deep cloning where we make +// use of JSON.stringify() method + +const person = { + name: "Shubham", + car: { + brand: "BMW", + color: "blue", + wheels: 4, + }, +}; + +const newPerson = JSON.stringify(person); + +// newPerson will be in the form of string, +// to convert it back to an object, +// we use JSON.parse(); + +const updatedPerson = JSON.parse(newPerson); + +updatedPerson.car.color = "red"; +console.log(person); // { name: 'Shubham', car: { brand: 'BMW', color: 'blue', wheels: 4 } } +console.log(updatedPerson); // { name: 'Shubham', car: { brand: 'BMW', color: 'red', wheels: 4 } } +``` + From aeaec79877a4472149c08d0bc05f12bb8d31539c Mon Sep 17 00:00:00 2001 From: ShubhamSKadam Date: Mon, 2 Jan 2023 17:50:43 +0530 Subject: [PATCH 08/25] Updated Readme --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index 3a26eb5..47f86b1 100644 --- a/README.md +++ b/README.md @@ -11,3 +11,5 @@ - #### [Hoisting and Closures](/5_Hoisting_and_Closure/HoistingAndClosure.md) - #### [Strings in Detail](/6_Strings_in_detail/strings.md) - #### [Arrays in Detail](/7_Arrays_in_detail/Arrays.md) +- #### [Objects in Detail](/8_Objects_in_detail/objects.md) +- #### [Value vs Reference](/9_Value_vs_Reference/value_vs_reference.md) From 704fc16a741df53159becd068c85005b7292b923 Mon Sep 17 00:00:00 2001 From: ShubhamSKadam Date: Mon, 2 Jan 2023 17:52:10 +0530 Subject: [PATCH 09/25] updated notes.md --- 9_Value_vs_Reference/value_vs_reference.md | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/9_Value_vs_Reference/value_vs_reference.md b/9_Value_vs_Reference/value_vs_reference.md index eee28ff..e66994d 100644 --- a/9_Value_vs_Reference/value_vs_reference.md +++ b/9_Value_vs_Reference/value_vs_reference.md @@ -29,7 +29,7 @@ const copiedNumbers = numbers; const newNumbers = [...numbers]; numbers.push(5); -console.log(numbers); // [ 1, 2, 3, 4, 5 ] +console.log(numbers); // [ 1, 2, 3, 4, 5 ] console.log(copiedNumbers); // [ 1, 2, 3, 4, 5 ] console.log(newNumbers); // [ 1, 2, 3, 4 ] @@ -42,7 +42,7 @@ const copiedNumbers = numbers; const newNumbers = numbers.slice(); numbers.push(5); -console.log(numbers); // [ 1, 2, 3, 4, 5 ] +console.log(numbers); // [ 1, 2, 3, 4, 5 ] console.log(copiedNumbers); // [ 1, 2, 3, 4, 5 ] console.log(newNumbers); // [ 1, 2, 3, 4 ] ``` @@ -59,13 +59,15 @@ console.log(newPerson); // { name: 'John', age: 22 } // 2nd way : Object.assign() const person = { name: "John", age: 22 }; -const newPerson = Object.assign({},person); +const newPerson = Object.assign({}, person); person.age = 23; console.log(person); // { name: 'John', age: 23 } console.log(newPerson); // { name: 'John', age: 22 } ``` +#### Deep Cloning + ```js // Deep Cloning // We can create a shallow copy of person object @@ -94,4 +96,3 @@ updatedPerson.car.color = "red"; console.log(person); // { name: 'Shubham', car: { brand: 'BMW', color: 'blue', wheels: 4 } } console.log(updatedPerson); // { name: 'Shubham', car: { brand: 'BMW', color: 'red', wheels: 4 } } ``` - From 0ef15b9de0cf18c9270d46578e4d042b63f83ba9 Mon Sep 17 00:00:00 2001 From: ShubhamSKadam Date: Tue, 3 Jan 2023 11:07:02 +0530 Subject: [PATCH 10/25] DOM --- 10_DOM/dom.md | 74 +++++++++++++++++++++++++++++++++++++++++++++++ 10_DOM/index.html | 14 +++++++++ 10_DOM/script.js | 1 + 3 files changed, 89 insertions(+) create mode 100644 10_DOM/dom.md create mode 100644 10_DOM/index.html create mode 100644 10_DOM/script.js diff --git a/10_DOM/dom.md b/10_DOM/dom.md new file mode 100644 index 0000000..020d415 --- /dev/null +++ b/10_DOM/dom.md @@ -0,0 +1,74 @@ +## DOM Methods + +- `getElementById`: This method retrieves an element from the document by its ID. + +- `querySelector`: This method retrieves the first element that matches a specified CSS selector. + +- `querySelectorAll`: This method retrieves all elements that match a specified CSS selector. + +- `getElementsByTagName`: This method retrieves all elements with a specified tag name. + +- `getElementsByClassName`: This method retrieves all elements with a specified class name. + + Here are some examples of how you might use these methods: + + ```js + Copy codeconst element = document.getElementById('my-element'); + + const firstParagraph = document.querySelector('p'); + + const listItems = document.querySelectorAll('li'); + + const divs = document.getElementsByTagName('div'); + + const redElements = document.getElementsByClassName('red'); + ``` + +Here is a list of some common DOM (Document Object Model) properties and methods that you can use to manipulate HTML elements: + +#### Properties + +- `innerHTML`: This property gets or sets the HTML content within an element. +- `style`: This property gets or sets the inline style of an element. +- `className`: This property gets or sets the class name of an element. +- `id`: This property gets or sets the ID of an element. +- `value`: This property gets or sets the value of an input element. + +#### Methods + +- `getAttribute`: This method gets the value of an attribute of an element. +- `setAttribute`: This method sets the value of an attribute of an element. +- `addEventListener`: This method adds an event listener to an element. +- `removeEventListener`: This method removes an event listener from an element. +- `appendChild`: This method adds a new child element to an element. + +Here are some examples of how you might use these properties and methods: + +```js +Copy codeconst element = document.getElementById('my-element'); + +element.innerHTML = 'Hello, world!'; + +element.style.color = 'red'; + +element.className = 'highlight'; + +element.id = 'new-id'; + +const input = document.querySelector('input'); +input.value = 'Hello, world!'; + +const attributeValue = element.getAttribute('data-attribute'); + +element.setAttribute('data-attribute', 'new value'); + +element.addEventListener('click', () => { + console.log('Element was clicked!'); +}); + +element.removeEventListener('click', myClickHandler); + +const newElement = document.createElement('p'); +newElement.innerHTML = 'This is a new element'; +element.appendChild(newElement); +``` \ No newline at end of file diff --git a/10_DOM/index.html b/10_DOM/index.html new file mode 100644 index 0000000..3f4f4fb --- /dev/null +++ b/10_DOM/index.html @@ -0,0 +1,14 @@ + + + + + + + DOM + + +

Hello, World!

+

Test 1

+ + + diff --git a/10_DOM/script.js b/10_DOM/script.js new file mode 100644 index 0000000..d3f5a12 --- /dev/null +++ b/10_DOM/script.js @@ -0,0 +1 @@ + From 81d75651cb8950f94186281199ced46250dfc816 Mon Sep 17 00:00:00 2001 From: ShubhamSKadam Date: Tue, 3 Jan 2023 11:59:44 +0530 Subject: [PATCH 11/25] updated all readme --- 5_Hoisting_and_Closure/HoistingAndClosure.md | 58 +++++++++++++++++--- 7_Arrays_in_detail/Arrays.md | 1 + 8_Objects_in_detail/objects.md | 23 ++++++-- 9_Value_vs_Reference/value_vs_reference.md | 31 +++++------ 4 files changed, 81 insertions(+), 32 deletions(-) diff --git a/5_Hoisting_and_Closure/HoistingAndClosure.md b/5_Hoisting_and_Closure/HoistingAndClosure.md index e2bd3a8..5164ec4 100644 --- a/5_Hoisting_and_Closure/HoistingAndClosure.md +++ b/5_Hoisting_and_Closure/HoistingAndClosure.md @@ -1,14 +1,26 @@ ### Hoisting -Bringing the variables to the top of the scope. +In JavaScript, hoisting is the behavior of moving declarations to the top of the current scope. In other words, when the code is executed, declarations are processed before any code is executed. This means that you can use a variable or function before it has been declared. -Only the variable declaration gets to the top. +For example, consider the following code: ```js -console.log(age); // undefined will be displayed -var age = 12; +Copy codeconsole.log(x); // undefined +var x = 10; ``` +Even though `x` is defined on the second line, it is still accessible on the first line because of hoisting. The declarations are moved to the top of the current scope, so the code is effectively rewritten as: + +```js +Copy codevar x; +console.log(x); // undefined +x = 10; +``` + +This behavior is specific to declarations (e.g. `var`, `let`, and `const`). Assignments and other code are not affected by hoisting. + +It is generally a good idea to declare all variables at the top of their respective scopes to avoid any confusion or unexpected behavior related to hoisting. + ```js hoist(); @@ -20,7 +32,7 @@ function hoist() { } ``` -With modern JavaScript we can avoid Hoisting, in the below code we are making use of let and const. +With modern JavaScript we can avoid Hoisting, in the code below we are making use of let and const. ```js console.log(age); // undeclared error @@ -39,13 +51,43 @@ const hoist = () => { }; ``` +### Closure +In JavaScript, a closure is a function that has access to the outer (enclosing) function's variables—scope chain—even after the outer function has returned. -### Closure +Here is an example of a closure in JavaScript: + +```js +function outerFunction(x) { + return function innerFunction(y) { + return x + y; + } +} + +const add5 = outerFunction(5); +console.log(add5(3)); // 8 +``` + +In this example, the `innerFunction` has access to the `x` variable from the outer function even after the outer function has returned. The `innerFunction` is said to close over the variables from the outer function. + +Closures are often used to create private variables in JavaScript. For example: + +```js +function counter() { + let count = 0; + return function() { + return ++count; + } +} + +const myCounter = counter(); +console.log(myCounter()); // 1 +console.log(myCounter()); // 2 +``` -Closure gives you an outer function scope through the inner function. +In this example, the `count` variable is not accessible from outside the `counter` function, but the inner function returned by `counter` has access to it. This allows the inner function to maintain state across multiple invocations. -Below Code shows how JavaScript takes care of the scope. +Closures are an important concept in JavaScript and are commonly used in many different types of code. ```js const outer = () => { diff --git a/7_Arrays_in_detail/Arrays.md b/7_Arrays_in_detail/Arrays.md index fc36204..fc5a2cd 100644 --- a/7_Arrays_in_detail/Arrays.md +++ b/7_Arrays_in_detail/Arrays.md @@ -191,3 +191,4 @@ const total = groceryList.reduce((total, price) => total + price, 0); console.log(total); // 318 ``` +All the code blocks above demonstrates how to use arrays and various array methods in JavaScript. An array is an object that represents a collection of similar type of elements. The code first defines an array `months` and then uses a `for` loop to iterate over the array, printing each element to the console. The code then demonstrates several array methods including `push`, `pop`, `shift`, `unshift`, `splice`, `slice`, `forEach`, `map`, `filter`, and `find`. The `push` method adds a new element to the end of the array, the `pop` method removes the last element of an array, the `shift` method removes the first element of an array, the `unshift` method adds a new value to the start of the array, the `splice` method adds or removes elements in any position of the array, the `slice` method copies a certain part of an array into a new array, the `forEach` method executes a provided function once for each array element, the `map` method creates a new array with the results of calling a provided function on every element in the array, the `filter` method creates a new array with all elements that pass the test implemented by the provided function, and the `find` method returns the first element in the array that satisfies a provided testing function. diff --git a/8_Objects_in_detail/objects.md b/8_Objects_in_detail/objects.md index bf1fef3..d1e691c 100644 --- a/8_Objects_in_detail/objects.md +++ b/8_Objects_in_detail/objects.md @@ -3,10 +3,6 @@ #### Creating an Object ```js -// object is an unordered collection -// of related date in form of -// key value pair - const person = { firstName: "Shubham", lastName: "Kadam", @@ -18,9 +14,11 @@ const person = { }; ``` +The first block of code shows how to create a new object using object literal syntax. An object literal is a list of key-value pairs enclosed in curly braces `{}`. The keys are represented by strings, and the values can be any data type (strings, numbers, arrays, etc). + #### The Dot and Square Notation -``` +```js // Dot notation const person = { firstName: "Shubham", @@ -40,7 +38,11 @@ const property = "age"; console.log(person[property]); // 23 ``` -#### Built-in-Methods +The above code demonstrates two ways to access and modify the properties of an object: dot notation and square bracket notation. + +With dot notation, you can access or set a property of an object using a dot (`.`) followed by the property name. For example, `person.age = 23` sets the `age` property of the `person` object to 23. + +With square bracket notation, you can access or set a property using a string inside square brackets (`[]`). For example, `person['age'] = 23` sets the `age` property of the `person` object to 23. ```js const dog = { @@ -64,6 +66,8 @@ const car = { car.Details(); // Lambo 2019 ``` +`this` notation is useful when you need to access a property whose name is stored in a variable. + #### Methods ```js @@ -137,3 +141,10 @@ console.log(user);// { username: 'Samarth', password: '12345' } ``` +The above block of code demonstrates four methods that are built into JavaScript: `Object.keys()`, `Object.values()`, `Object.entries()`, and `Object.freeze()`. + +- `Object.keys()` creates an array containing the keys (property names) of an object. +- `Object.values()` creates an array containing the values of an object. +- `Object.entries()` is a built-in JavaScript method that returns an array of an object's own enumerable string-keyed property [key, value] pairs, in the same order as that provided by a for...in loop (the difference being that a for-in loop enumerates properties in the prototype chain as well). +- `Object.freeze()` is a method in JavaScript that prevents an object from being modified. It makes the object's properties and values read-only, and prevents new properties from being added, removed, or modified. Once an object is frozen, you can no longer change its properties or values, and you cannot add or remove properties from the object. + diff --git a/9_Value_vs_Reference/value_vs_reference.md b/9_Value_vs_Reference/value_vs_reference.md index e66994d..83a2d9e 100644 --- a/9_Value_vs_Reference/value_vs_reference.md +++ b/9_Value_vs_Reference/value_vs_reference.md @@ -8,14 +8,11 @@ const otherAnimals = animals; animals.push("pig"); console.log(animals); // [ 'dogs', 'cats', 'pig' ] -// We get the same output for otherAnimals too, -// because the otherAnimals is also referencing the same memory -// as the animals. console.log(otherAnimals); // [ 'dogs', 'cats', 'pig' ] - -// The behaviour is same even with respect to objects. ``` +The first block of code demonstrates how variables in JavaScript can be copied by reference, rather than by value. When you assign an array or object to a new variable, the new variable is simply a reference to the original array or object. This means that any changes made to the original array or object will also be reflected in the copied variable, because they are both pointing to the same memory location. + #### Shallow Cloning ```js @@ -24,8 +21,6 @@ console.log(otherAnimals); // [ 'dogs', 'cats', 'pig' ] const numbers = [1, 2, 3, 4]; const copiedNumbers = numbers; -// Using spread Opeator, -// Also known as Shallow Cloning const newNumbers = [...numbers]; numbers.push(5); @@ -37,14 +32,13 @@ console.log(newNumbers); // [ 1, 2, 3, 4 ] const numbers = [1, 2, 3, 4]; const copiedNumbers = numbers; -// Using spread Opeator, -// Also known as Shallow Cloning const newNumbers = numbers.slice(); numbers.push(5); console.log(numbers); // [ 1, 2, 3, 4, 5 ] console.log(copiedNumbers); // [ 1, 2, 3, 4, 5 ] console.log(newNumbers); // [ 1, 2, 3, 4 ] + ``` ```js @@ -66,15 +60,14 @@ console.log(person); // { name: 'John', age: 23 } console.log(newPerson); // { name: 'John', age: 22 } ``` + A shallow copy is a copy that only includes the top-level properties of the original array or object, rather than copying all nested properties as well. + +The first way to create a shallow copy is to use the spread operator (`...`). This creates a new array or object with the same properties as the original, but they are not nested. The second way to create a shallow copy is to use the `Array.slice()` or `Object.assign()` methods. These methods work similarly to the spread operator, but they are more specific to arrays and objects, respectively. + #### Deep Cloning ```js // Deep Cloning -// We can create a shallow copy of person object -// but we have to do it for all the inner objects as well. -// To solve this we can do a deep cloning where we make -// use of JSON.stringify() method - const person = { name: "Shubham", car: { @@ -86,13 +79,15 @@ const person = { const newPerson = JSON.stringify(person); -// newPerson will be in the form of string, -// to convert it back to an object, -// we use JSON.parse(); - const updatedPerson = JSON.parse(newPerson); updatedPerson.car.color = "red"; console.log(person); // { name: 'Shubham', car: { brand: 'BMW', color: 'blue', wheels: 4 } } console.log(updatedPerson); // { name: 'Shubham', car: { brand: 'BMW', color: 'red', wheels: 4 } } ``` + + A deep copy is a copy that includes all nested properties of the original object, rather than just the top-level properties. + +To create a deep copy, the code uses the `JSON.stringify()` and `JSON.parse()` methods. `JSON.stringify()` converts an object to a JSON string, which is a format that can be easily stored or transmitted. `JSON.parse()` converts a JSON string back into an object. + +By using these methods, the code is able to create a deep copy of the original object, which can be modified independently without affecting the original object. From cd9d38081ab03098718959882fabc7d7ea7058d4 Mon Sep 17 00:00:00 2001 From: ShubhamSKadam Date: Wed, 4 Jan 2023 18:09:31 +0530 Subject: [PATCH 12/25] Classes --- 10_DOM/index.html | 19 +++++++++++++++++-- 10_DOM/script.js | 8 ++++++++ 2 files changed, 25 insertions(+), 2 deletions(-) diff --git a/10_DOM/index.html b/10_DOM/index.html index 3f4f4fb..6c2b2c7 100644 --- a/10_DOM/index.html +++ b/10_DOM/index.html @@ -5,10 +5,25 @@ DOM + -

Hello, World!

-

Test 1

+
    + + + + +
diff --git a/10_DOM/script.js b/10_DOM/script.js index d3f5a12..71c5786 100644 --- a/10_DOM/script.js +++ b/10_DOM/script.js @@ -1 +1,9 @@ +const menuClicked = (currEl) => { + const menuItems = document.getElementsByClassName("menu-item"); + for (let i = 0; i < menuItems.length; i++) { + menuItems[i].classList.remove("active"); + } + + currEl.classList.add("active"); +}; From 30bb7c2dfde17ac88e7345309b25fbf644786766 Mon Sep 17 00:00:00 2001 From: ShubhamSKadam Date: Wed, 4 Jan 2023 18:17:59 +0530 Subject: [PATCH 13/25] Creating traversing and removing nodes --- 10_DOM/index.html | 20 ++++---------------- 1 file changed, 4 insertions(+), 16 deletions(-) diff --git a/10_DOM/index.html b/10_DOM/index.html index 6c2b2c7..37e8a07 100644 --- a/10_DOM/index.html +++ b/10_DOM/index.html @@ -5,24 +5,12 @@ DOM - -
    - - - - +
      +
    • Maths
    • +
    • Science
    • +
    • English
    From c9088c5c2ff4cbe07ea994d9cd58f3b4a4c0871f Mon Sep 17 00:00:00 2001 From: ShubhamSKadam Date: Thu, 5 Jan 2023 10:44:52 +0530 Subject: [PATCH 14/25] Updated Readme --- README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 47f86b1..ca27d24 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# Crash Course on JavaScript +# Crash Course on JavaScript ![Javascript](https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRY_6xmpk2NCVs1LezEwt8U8UWIzp4NX5AFCw&usqp=CAU) @@ -13,3 +13,4 @@ - #### [Arrays in Detail](/7_Arrays_in_detail/Arrays.md) - #### [Objects in Detail](/8_Objects_in_detail/objects.md) - #### [Value vs Reference](/9_Value_vs_Reference/value_vs_reference.md) +- #### [DOM](/10_DOM/dom.md) From d176a2b72dbd8eb264fae70f755b48bd29e46f68 Mon Sep 17 00:00:00 2001 From: ShubhamSKadam Date: Thu, 5 Jan 2023 11:32:34 +0530 Subject: [PATCH 15/25] Classes and functional approach --- 11_Classes_this_and_new_keyword/11.md | 53 +++++++++++++++++++++++ 11_Classes_this_and_new_keyword/script.js | 40 +++++++++++++++++ 2 files changed, 93 insertions(+) create mode 100644 11_Classes_this_and_new_keyword/11.md create mode 100644 11_Classes_this_and_new_keyword/script.js diff --git a/11_Classes_this_and_new_keyword/11.md b/11_Classes_this_and_new_keyword/11.md new file mode 100644 index 0000000..530cf87 --- /dev/null +++ b/11_Classes_this_and_new_keyword/11.md @@ -0,0 +1,53 @@ +#### The New Keyword + +```js +// The new keyword +// The new keyword creates an object of num +// which then let's us access to various methods, +// like .toFixed() in the below code. +const num = new Number(100.25); + +console.log(num.toFixed(0));// 100 +``` + +#### This Keyword + +```js +const person = { + name: "John", + getName() { + console.log(this); + }, +}; + +person.getName(); // { name: 'John', getName: [Function: getName] } +``` + +#### Class + +```js +// Class is a schema for +// an object that can save +// many values + +class Person { + constructor(name, age, isWorking) { + this.name = name; + this.age = age; + this.isWorking = isWorking; + } +} + +const user = new Person("John", 22, true); + +console.log(user); // Person { name: 'John', age: 22, isWorking: true } + +// How can we do the same thing above using +// arrow function ? + +const createPerson = (name, age, isWorking) => ({ name, age, isWorking }); + +const user1 = createPerson("Shubham", 23, false); +console.log(user1);//{ name: 'Shubham', age: 23, isWorking: false } +``` + diff --git a/11_Classes_this_and_new_keyword/script.js b/11_Classes_this_and_new_keyword/script.js new file mode 100644 index 0000000..5cb2d02 --- /dev/null +++ b/11_Classes_this_and_new_keyword/script.js @@ -0,0 +1,40 @@ +// The new keyword +// The new keyword creates an object of num +// which then let's us access to various methods, +// like .toFixed() in the below code. +// const num = new Number(100.25); + +// console.log(num.toFixed(0)); // 100 + +// const person = { +// name: "John", +// getName() { +// console.log(this); +// }, +// }; + +// person.getName(); // { name: 'John', getName: [Function: getName] } + +// Class is a schema for +// an object that can save +// many values + +// class Person { +// constructor(name, age, isWorking) { +// this.name = name; +// this.age = age; +// this.isWorking = isWorking; +// } +// } + +// const user = new Person("John", 22, true); + +// console.log(user); + +// HOw can we do the same thing above using +// arrow function ? + +const createPerson = (name, age, isWorking) => ({ name, age, isWorking }); + +const user1 = createPerson("Shubham", 23, false); +console.log(user1);//{ name: 'Shubham', age: 23, isWorking: false } From d57b288a48c131785f5c2b3bb9afefb7a9d309a7 Mon Sep 17 00:00:00 2001 From: ShubhamSKadam Date: Thu, 5 Jan 2023 12:18:45 +0530 Subject: [PATCH 16/25] Intervals and Timers --- 11_Classes_this_and_new_keyword/script.js | 2 +- 12_Asynchronous_Concepts/12.md | 21 +++++++++++++++++++++ 12_Asynchronous_Concepts/script.js | 12 ++++++++++++ 3 files changed, 34 insertions(+), 1 deletion(-) create mode 100644 12_Asynchronous_Concepts/12.md create mode 100644 12_Asynchronous_Concepts/script.js diff --git a/11_Classes_this_and_new_keyword/script.js b/11_Classes_this_and_new_keyword/script.js index 5cb2d02..2d48209 100644 --- a/11_Classes_this_and_new_keyword/script.js +++ b/11_Classes_this_and_new_keyword/script.js @@ -31,7 +31,7 @@ // console.log(user); -// HOw can we do the same thing above using +// How can we do the same thing above using // arrow function ? const createPerson = (name, age, isWorking) => ({ name, age, isWorking }); diff --git a/12_Asynchronous_Concepts/12.md b/12_Asynchronous_Concepts/12.md new file mode 100644 index 0000000..f639da3 --- /dev/null +++ b/12_Asynchronous_Concepts/12.md @@ -0,0 +1,21 @@ +#### Intervals and Timers + +```js +// Asynchronous Code + +// setInterval +// clearInterval + +// outputs Hello, world! Every 2 seconds + const myInterval = setInterval(() => console.log("Hello, world!"), 2000); + clearInterval(myInterval); // Clears the Interval + +// setTimeout +// clearTimeout + +// Outputs Let's Play after 5 seconds +const myTimeout = setTimeout(() => console.log("Lets play"), 5000); + +console.log("logging in the bottom"); +``` + diff --git a/12_Asynchronous_Concepts/script.js b/12_Asynchronous_Concepts/script.js new file mode 100644 index 0000000..44dae6f --- /dev/null +++ b/12_Asynchronous_Concepts/script.js @@ -0,0 +1,12 @@ +// Asynchronous Code + +// setInterval +// clearInterval +// const myInterval = setInterval(() => console.log("Hello, world!"), 2000); +// clearInterval(myInterval); + +// setTimeout +// clearTimeout +const myTimeout = setTimeout(() => console.log("Lets play"), 5000); + +console.log("logging in the bottom"); From 916144acae39dd026d7cc5b11ed84484f5952e87 Mon Sep 17 00:00:00 2001 From: ShubhamSKadam Date: Thu, 5 Jan 2023 12:32:08 +0530 Subject: [PATCH 17/25] Synchronous and Asynchronous --- 12_Asynchronous_Concepts/12.md | 22 +++++++++++++++++++++ 12_Asynchronous_Concepts/script.js | 31 ++++++++++++++++++++++++++++-- 2 files changed, 51 insertions(+), 2 deletions(-) diff --git a/12_Asynchronous_Concepts/12.md b/12_Asynchronous_Concepts/12.md index f639da3..c36c821 100644 --- a/12_Asynchronous_Concepts/12.md +++ b/12_Asynchronous_Concepts/12.md @@ -19,3 +19,25 @@ const myTimeout = setTimeout(() => console.log("Lets play"), 5000); console.log("logging in the bottom"); ``` +#### Introduction to Synchronous and Asynchronous + +```js +// Synchronous Code +const functionOne = () => { + console.log("Function One"); // 1 + + functionTwo(); + + console.log("Function One, Part two"); // 3 +}; + +const functionTwo = () => { + console.log("Function two"); // 2 +}; + +``` + +``` + +``` + diff --git a/12_Asynchronous_Concepts/script.js b/12_Asynchronous_Concepts/script.js index 44dae6f..c7fb7e2 100644 --- a/12_Asynchronous_Concepts/script.js +++ b/12_Asynchronous_Concepts/script.js @@ -7,6 +7,33 @@ // setTimeout // clearTimeout -const myTimeout = setTimeout(() => console.log("Lets play"), 5000); +// const myTimeout = setTimeout(() => console.log("Lets play"), 5000); -console.log("logging in the bottom"); +// console.log("logging in the bottom"); + +// Synchronous Code +// const functionOne = () => { +// console.log("Function One"); // 1 + +// functionTwo(); + +// console.log("Function One, Part two"); // 3 +// }; + +// const functionTwo = () => { +// console.log("Function two"); // 2 +// }; + +const functionOne = () => { + console.log("Function One"); // 1 + + functionTwo(); + + console.log("Function One, Part two"); // 2 +}; + +const functionTwo = () => { + setTimeout(() => console.log("Function two"), 2000); // 3 +}; + +functionOne(); From 261467af2949f7a634177dc8875edee087af9c63 Mon Sep 17 00:00:00 2001 From: ShubhamSKadam Date: Thu, 5 Jan 2023 12:52:59 +0530 Subject: [PATCH 18/25] Callback functions --- 12_Asynchronous_Concepts/12.md | 14 +++++++++++++- 12_Asynchronous_Concepts/script2.js | 12 ++++++++++++ 2 files changed, 25 insertions(+), 1 deletion(-) create mode 100644 12_Asynchronous_Concepts/script2.js diff --git a/12_Asynchronous_Concepts/12.md b/12_Asynchronous_Concepts/12.md index c36c821..30974d1 100644 --- a/12_Asynchronous_Concepts/12.md +++ b/12_Asynchronous_Concepts/12.md @@ -37,7 +37,19 @@ const functionTwo = () => { ``` -``` +#### Callback functions + +```js +// Callback functions + +const fetchUser = (username, callback) => { + setTimeout(() => { + callback({ username }); + }, 2000); +}; +fetchUser("Shubham", (user) => { + console.log(`Hello, ${user.username}`); // Hello, Shubham +}); ``` diff --git a/12_Asynchronous_Concepts/script2.js b/12_Asynchronous_Concepts/script2.js new file mode 100644 index 0000000..9f875c4 --- /dev/null +++ b/12_Asynchronous_Concepts/script2.js @@ -0,0 +1,12 @@ +// Callback functions + +const fetchUser = (username, callback) => { + console.log("Fetching..."); + setTimeout(() => { + callback({ username }); + }, 2000); +}; + +fetchUser("Shubham", (user) => { + console.log(`Hello, ${user.username}`); +}); From f89638fe8d73efe89f691d53a5a9f9cf4b8dc386 Mon Sep 17 00:00:00 2001 From: ShubhamSKadam Date: Thu, 5 Jan 2023 18:13:49 +0530 Subject: [PATCH 19/25] Promises --- 12_Asynchronous_Concepts/12.md | 44 +++++++++++++++++++++++++++++ 12_Asynchronous_Concepts/script2.js | 38 +++++++++++++++++++------ 2 files changed, 73 insertions(+), 9 deletions(-) diff --git a/12_Asynchronous_Concepts/12.md b/12_Asynchronous_Concepts/12.md index 30974d1..a6cf6cd 100644 --- a/12_Asynchronous_Concepts/12.md +++ b/12_Asynchronous_Concepts/12.md @@ -53,3 +53,47 @@ fetchUser("Shubham", (user) => { }); ``` +#### Promises + +```js +//In JavaScript, a Promise is an object that represents the result of an asynchronous //operation. A Promise can be in one of three states: pending, fulfilled, or rejected. + +//A Promise starts in the pending state, and it can either be fulfilled with a value or //rejected with a reason (error). Once a Promise is fulfilled or rejected, it is considered //settled, and it cannot be changed anymore. + +//Promises are used to handle asynchronous operations in a synchronous manner, making it //easier to write and reason about async code. Instead of using callback functions, you can //use the then and catch methods on a Promise to specify what should happen when the Promise //is fulfilled or rejected. + + +const fetchUser = (username) => { + return new Promise((resolve, reject) => { + setTimeout(() => { + console.log("[Now we have the user]"); + + resolve({ username }); + }, 2000); + }); +}; + +const fetchUserPhotos = (username) => { + return new Promise((resolve, reject) => { + setTimeout(() => { + console.log(`Now we have the photos for ${username}`); + resolve(["Photo1", "Photo2"]); + }, 2000); + }); +}; + +const fetchPhotoDetails = (photo) => { + return new Promise((resolve, reject) => { + setTimeout(() => { + console.log(`[Now we have the photo details ${photo}]`); + resolve("details..."); + }, 2000); + }); +}; + +fetchUser("Shubham") + .then((user) => fetchUserPhotos(user.username)) + .then((photos) => fetchPhotoDetails(photos[0])) + .then((details) => console.log(`Your photo details are ${details}`)); +``` + diff --git a/12_Asynchronous_Concepts/script2.js b/12_Asynchronous_Concepts/script2.js index 9f875c4..b49704e 100644 --- a/12_Asynchronous_Concepts/script2.js +++ b/12_Asynchronous_Concepts/script2.js @@ -1,12 +1,32 @@ -// Callback functions +const fetchUser = (username) => { + return new Promise((resolve, reject) => { + setTimeout(() => { + console.log("[Now we have the user]"); -const fetchUser = (username, callback) => { - console.log("Fetching..."); - setTimeout(() => { - callback({ username }); - }, 2000); + resolve({ username }); + }, 2000); + }); }; -fetchUser("Shubham", (user) => { - console.log(`Hello, ${user.username}`); -}); +const fetchUserPhotos = (username) => { + return new Promise((resolve, reject) => { + setTimeout(() => { + console.log(`Now we have the photos for ${username}`); + resolve(["Photo1", "Photo2"]); + }, 2000); + }); +}; + +const fetchPhotoDetails = (photo) => { + return new Promise((resolve, reject) => { + setTimeout(() => { + console.log(`[Now we have the photo details ${photo}]`); + resolve("details..."); + }, 2000); + }); +}; + +fetchUser("Shubham") + .then((user) => fetchUserPhotos(user.username)) + .then((photos) => fetchPhotoDetails(photos[0])) + .then((details) => console.log(`Your photo details are ${details}`)); From 442b8d4efd57a66bf74096aaab78a19abef44b00 Mon Sep 17 00:00:00 2001 From: ShubhamSKadam Date: Thu, 5 Jan 2023 18:25:23 +0530 Subject: [PATCH 20/25] Async and Await --- 12_Asynchronous_Concepts/script2.js | 21 +++++++++++++++++---- 1 file changed, 17 insertions(+), 4 deletions(-) diff --git a/12_Asynchronous_Concepts/script2.js b/12_Asynchronous_Concepts/script2.js index b49704e..b1f7d6a 100644 --- a/12_Asynchronous_Concepts/script2.js +++ b/12_Asynchronous_Concepts/script2.js @@ -26,7 +26,20 @@ const fetchPhotoDetails = (photo) => { }); }; -fetchUser("Shubham") - .then((user) => fetchUserPhotos(user.username)) - .then((photos) => fetchPhotoDetails(photos[0])) - .then((details) => console.log(`Your photo details are ${details}`)); +// This was one way of calling the function +// fetchUser("Shubham") +// .then((user) => fetchUserPhotos(user.username)) +// .then((photos) => fetchPhotoDetails(photos[0])) +// .then((details) => console.log(`Your photo details are ${details}`)); + +// The second way is using Async ==> Await + +const displayData = async () => { + const user = await fetchUser("Shubham"); + const photos = await fetchUserPhotos(user.username); + const details = await fetchPhotoDetails(photos[0]); + + console.log(details); +}; + +displayData(); From 7e5217767f1b2ea35ba25ce1c61856777937370e Mon Sep 17 00:00:00 2001 From: ShubhamSKadam Date: Fri, 6 Jan 2023 18:08:26 +0530 Subject: [PATCH 21/25] Updated Readme --- README.md | 22 ++++++++++++---------- 1 file changed, 12 insertions(+), 10 deletions(-) diff --git a/README.md b/README.md index ca27d24..f18baa8 100644 --- a/README.md +++ b/README.md @@ -4,13 +4,15 @@ ## Contents - -- #### [Variables and Data Types](/1_variables_and_data_types/variablesDataTypes.md) -- #### [Operators](/2_Operators/Operators.md) -- #### [Logic and Control Flow](/3_Logic_and_Control_flow/LogicAndControlFlow.md) -- #### [Functions](/4_Functions/Functions.md) -- #### [Hoisting and Closures](/5_Hoisting_and_Closure/HoistingAndClosure.md) -- #### [Strings in Detail](/6_Strings_in_detail/strings.md) -- #### [Arrays in Detail](/7_Arrays_in_detail/Arrays.md) -- #### [Objects in Detail](/8_Objects_in_detail/objects.md) -- #### [Value vs Reference](/9_Value_vs_Reference/value_vs_reference.md) -- #### [DOM](/10_DOM/dom.md) +- #### [Variables and Data Types](/1_variables_and_data_types/variablesDataTypes.md) +- #### [Operators](/2_Operators/Operators.md) +- #### [Logic and Control Flow](/3_Logic_and_Control_flow/LogicAndControlFlow.md) +- #### [Functions](/4_Functions/Functions.md) +- #### [Hoisting and Closures](/5_Hoisting_and_Closure/HoistingAndClosure.md) +- #### [Strings in Detail](/6_Strings_in_detail/strings.md) +- #### [Arrays in Detail](/7_Arrays_in_detail/Arrays.md) +- #### [Objects in Detail](/8_Objects_in_detail/objects.md) +- #### [Value vs Reference](/9_Value_vs_Reference/value_vs_reference.md) +- #### [DOM](/10_DOM/dom.md) +- #### [Classes, this and new keyword](/11_Classes_this_and_new_keyword/11.md) +- #### [Asynchronous Concepts](/12_Asynchronous_Concepts/12.md) From 67110480a6dacc28766583e1adde1293c7e34c8b Mon Sep 17 00:00:00 2001 From: ShubhamSKadam Date: Fri, 6 Jan 2023 18:10:09 +0530 Subject: [PATCH 22/25] Updated Readme --- 12_Asynchronous_Concepts/12.md | 70 +++++++++++++++++----------------- 1 file changed, 36 insertions(+), 34 deletions(-) diff --git a/12_Asynchronous_Concepts/12.md b/12_Asynchronous_Concepts/12.md index a6cf6cd..3ce621d 100644 --- a/12_Asynchronous_Concepts/12.md +++ b/12_Asynchronous_Concepts/12.md @@ -7,8 +7,8 @@ // clearInterval // outputs Hello, world! Every 2 seconds - const myInterval = setInterval(() => console.log("Hello, world!"), 2000); - clearInterval(myInterval); // Clears the Interval +const myInterval = setInterval(() => console.log("Hello, world!"), 2000); +clearInterval(myInterval); // Clears the Interval // setTimeout // clearTimeout @@ -24,17 +24,16 @@ console.log("logging in the bottom"); ```js // Synchronous Code const functionOne = () => { - console.log("Function One"); // 1 + console.log("Function One"); // 1 - functionTwo(); + functionTwo(); - console.log("Function One, Part two"); // 3 + console.log("Function One, Part two"); // 3 }; const functionTwo = () => { - console.log("Function two"); // 2 + console.log("Function two"); // 2 }; - ``` #### Callback functions @@ -43,16 +42,21 @@ const functionTwo = () => { // Callback functions const fetchUser = (username, callback) => { - setTimeout(() => { - callback({ username }); - }, 2000); + setTimeout(() => { + callback({ username }); + }, 2000); }; fetchUser("Shubham", (user) => { - console.log(`Hello, ${user.username}`); // Hello, Shubham + console.log(`Hello, ${user.username}`); // Hello, Shubham }); ``` +The two problems that we faced in callbacks are:- + +1. Callback Hell: Asynchronous operations in JavaScript can be achieved through callbacks. Whenever there are multiple dependent Asynchronous operations it will result in a lot of nested callbacks. This will cause a 'pyramid of doom' like structure. +2. Inversion of control: When we give the control of callbacks being called to some other API, this may create a lot of issues. That API may be buggy, may not call our callback and create order as in the above example, may call the payment callback twice etc. + #### Promises ```js @@ -62,38 +66,36 @@ fetchUser("Shubham", (user) => { //Promises are used to handle asynchronous operations in a synchronous manner, making it //easier to write and reason about async code. Instead of using callback functions, you can //use the then and catch methods on a Promise to specify what should happen when the Promise //is fulfilled or rejected. - const fetchUser = (username) => { - return new Promise((resolve, reject) => { - setTimeout(() => { - console.log("[Now we have the user]"); + return new Promise((resolve, reject) => { + setTimeout(() => { + console.log("[Now we have the user]"); - resolve({ username }); - }, 2000); - }); + resolve({ username }); + }, 2000); + }); }; const fetchUserPhotos = (username) => { - return new Promise((resolve, reject) => { - setTimeout(() => { - console.log(`Now we have the photos for ${username}`); - resolve(["Photo1", "Photo2"]); - }, 2000); - }); + return new Promise((resolve, reject) => { + setTimeout(() => { + console.log(`Now we have the photos for ${username}`); + resolve(["Photo1", "Photo2"]); + }, 2000); + }); }; const fetchPhotoDetails = (photo) => { - return new Promise((resolve, reject) => { - setTimeout(() => { - console.log(`[Now we have the photo details ${photo}]`); - resolve("details..."); - }, 2000); - }); + return new Promise((resolve, reject) => { + setTimeout(() => { + console.log(`[Now we have the photo details ${photo}]`); + resolve("details..."); + }, 2000); + }); }; fetchUser("Shubham") - .then((user) => fetchUserPhotos(user.username)) - .then((photos) => fetchPhotoDetails(photos[0])) - .then((details) => console.log(`Your photo details are ${details}`)); + .then((user) => fetchUserPhotos(user.username)) + .then((photos) => fetchPhotoDetails(photos[0])) + .then((details) => console.log(`Your photo details are ${details}`)); ``` - From 6c1f164a1917ddb9ba6f10f87066908b09646b4e Mon Sep 17 00:00:00 2001 From: ShubhamSKadam Date: Fri, 6 Jan 2023 22:00:21 +0530 Subject: [PATCH 23/25] Promises Updated --- 12_Asynchronous_Concepts/12.md | 44 ++++++++++++++++++++++++++---- 12_Asynchronous_Concepts/script.js | 10 +++++++ 2 files changed, 49 insertions(+), 5 deletions(-) diff --git a/12_Asynchronous_Concepts/12.md b/12_Asynchronous_Concepts/12.md index a6cf6cd..945c53a 100644 --- a/12_Asynchronous_Concepts/12.md +++ b/12_Asynchronous_Concepts/12.md @@ -7,8 +7,8 @@ // clearInterval // outputs Hello, world! Every 2 seconds - const myInterval = setInterval(() => console.log("Hello, world!"), 2000); - clearInterval(myInterval); // Clears the Interval +const myInterval = setInterval(() => console.log("Hello, world!"), 2000); +clearInterval(myInterval); // Clears the Interval // setTimeout // clearTimeout @@ -34,7 +34,6 @@ const functionOne = () => { const functionTwo = () => { console.log("Function two"); // 2 }; - ``` #### Callback functions @@ -55,14 +54,50 @@ fetchUser("Shubham", (user) => { #### Promises -```js //In JavaScript, a Promise is an object that represents the result of an asynchronous //operation. A Promise can be in one of three states: pending, fulfilled, or rejected. //A Promise starts in the pending state, and it can either be fulfilled with a value or //rejected with a reason (error). Once a Promise is fulfilled or rejected, it is considered //settled, and it cannot be changed anymore. //Promises are used to handle asynchronous operations in a synchronous manner, making it //easier to write and reason about async code. Instead of using callback functions, you can //use the then and catch methods on a Promise to specify what should happen when the Promise //is fulfilled or rejected. +```js{ +// Let's say we have a shopping cart +const cart = ['shoes','pants','shirt']; + +// If we had to implement a series of operations +// let's say we have a function to, +// 1. Create an order which will return a orderID +// 2. Proceed to payment with orderId and return payment info. +// 3. Show order summary with payment info + +createOrder(cart,(orderID)=>{ + proceedToPayment(orderID,(paymentInfo)=>{ + showOrderSummary(paymentInfo,()=>{ + displayOrderSummary(); + }) + } +}) +// In the above code we see the call back hell or +// also known as Pyramid of doom + +// We can write the same code using promises +createOrder(cart) +.then((orderId)=>{ + return proceedToPayment(orderId) +}) +.then((paymentInfo)=>{ + return showOrderSummary(paymentInfo) +}) +.then(()=>{ + displayOrderSummary();// not returning anything because we are just displaying +}) + +// why do we use promises ? +// 1. To avoid Inversion of Control [Not calling the fuction over another function] +// 2. To avoid Call Back hell and have better control of our code +``` +```js const fetchUser = (username) => { return new Promise((resolve, reject) => { setTimeout(() => { @@ -96,4 +131,3 @@ fetchUser("Shubham") .then((photos) => fetchPhotoDetails(photos[0])) .then((details) => console.log(`Your photo details are ${details}`)); ``` - diff --git a/12_Asynchronous_Concepts/script.js b/12_Asynchronous_Concepts/script.js index c7fb7e2..08f287f 100644 --- a/12_Asynchronous_Concepts/script.js +++ b/12_Asynchronous_Concepts/script.js @@ -37,3 +37,13 @@ const functionTwo = () => { }; functionOne(); + +// callbacks; + +const cart = ["Shoes", "Shirt", "Pant"]; + +const Promise = createOrder(cart); + +Promise.then((orderId) => { + processPayment(orderId); +}); From 11c73f62d2edc026fab39f8d381c3d1342a5bc28 Mon Sep 17 00:00:00 2001 From: Shubham Kadam <115479576+ShubhamSKadam@users.noreply.github.com> Date: Sun, 8 Jan 2023 08:32:49 +0530 Subject: [PATCH 24/25] Update 12.md --- 12_Asynchronous_Concepts/12.md | 65 ++++++++++++---------------------- 1 file changed, 22 insertions(+), 43 deletions(-) diff --git a/12_Asynchronous_Concepts/12.md b/12_Asynchronous_Concepts/12.md index 2171152..7be7de3 100644 --- a/12_Asynchronous_Concepts/12.md +++ b/12_Asynchronous_Concepts/12.md @@ -24,16 +24,30 @@ console.log("logging in the bottom"); ```js // Synchronous Code const functionOne = () => { - console.log("Function One"); // 1 + console.log("Function One"); // This will be printed first functionTwo(); - console.log("Function One, Part two"); // 3 + console.log("Function One, Part two"); // This will be printed third }; const functionTwo = () => { - console.log("Function two"); // 2 + console.log("Function two"); // This will be printed second }; + +// Asynchronous Code + +const functionOne = () => { + console.log("Function One"); // This will be printed first + + functionTwo(); + + console.log("Function One, Part two"); // This will be printed second +}; + +const functionTwo = () => { + setTimeout(() => console.log("Function two"), 2000); // This will be printed third + ``` #### Callback functions @@ -52,20 +66,20 @@ fetchUser("Shubham", (user) => { }); ``` -The two problems that we faced in callbacks are:- +There are two problems that we face in callbacks:- 1. Callback Hell: Asynchronous operations in JavaScript can be achieved through callbacks. Whenever there are multiple dependent Asynchronous operations it will result in a lot of nested callbacks. This will cause a 'pyramid of doom' like structure. 2. Inversion of control: When we give the control of callbacks being called to some other API, this may create a lot of issues. That API may be buggy, may not call our callback and create order as in the above example, may call the payment callback twice etc. #### Promises -//In JavaScript, a Promise is an object that represents the result of an asynchronous //operation. A Promise can be in one of three states: pending, fulfilled, or rejected. +In JavaScript, a Promise is an object that represents the result of an asynchronous operation. A Promise can be in one of three states: pending, fulfilled, or rejected. -//A Promise starts in the pending state, and it can either be fulfilled with a value or //rejected with a reason (error). Once a Promise is fulfilled or rejected, it is considered //settled, and it cannot be changed anymore. +A Promise starts in the pending state, and it can either be fulfilled with a value or rejected with a reason (error). Once a Promise is fulfilled or rejected, it is considered settled, and it cannot be changed anymore. -//Promises are used to handle asynchronous operations in a synchronous manner, making it //easier to write and reason about async code. Instead of using callback functions, you can //use the then and catch methods on a Promise to specify what should happen when the Promise //is fulfilled or rejected. +Promises are used to handle asynchronous operations in a synchronous manner, making it easier to write and reason about async code. Instead of using callback functions, you can use the then and catch methods on a Promise to specify what should happen when the Promise is fulfilled or rejected. -```js{ +```js // Let's say we have a shopping cart const cart = ['shoes','pants','shirt']; @@ -101,38 +115,3 @@ createOrder(cart) // 1. To avoid Inversion of Control [Not calling the fuction over another function] // 2. To avoid Call Back hell and have better control of our code ``` - -```js -const fetchUser = (username) => { - return new Promise((resolve, reject) => { - setTimeout(() => { - console.log("[Now we have the user]"); - - resolve({ username }); - }, 2000); - }); -}; - -const fetchUserPhotos = (username) => { - return new Promise((resolve, reject) => { - setTimeout(() => { - console.log(`Now we have the photos for ${username}`); - resolve(["Photo1", "Photo2"]); - }, 2000); - }); -}; - -const fetchPhotoDetails = (photo) => { - return new Promise((resolve, reject) => { - setTimeout(() => { - console.log(`[Now we have the photo details ${photo}]`); - resolve("details..."); - }, 2000); - }); -}; - -fetchUser("Shubham") - .then((user) => fetchUserPhotos(user.username)) - .then((photos) => fetchPhotoDetails(photos[0])) - .then((details) => console.log(`Your photo details are ${details}`)); -``` From 07781a2bd29ea45bf24bd1edd961b3509dd09386 Mon Sep 17 00:00:00 2001 From: ShubhamSKadam Date: Sun, 19 Nov 2023 12:49:14 +0530 Subject: [PATCH 25/25] update --- 7_Arrays_in_detail/Arrays.md | 40 ++++++++++++++++++------------------ 1 file changed, 20 insertions(+), 20 deletions(-) diff --git a/7_Arrays_in_detail/Arrays.md b/7_Arrays_in_detail/Arrays.md index fc5a2cd..9dc7f5a 100644 --- a/7_Arrays_in_detail/Arrays.md +++ b/7_Arrays_in_detail/Arrays.md @@ -6,7 +6,7 @@ let months = ["January", "February", "March", "April"]; for (let i = 0; i < months.length; i++) { - console.log(months[i]); + console.log(months[i]); } // January // February @@ -37,8 +37,8 @@ names.unshift("Samarth"); console.log(names); // [ 'Samarth', 'Bob', 'David', 'Mark' ] // Array Splice - It adds or removes values in any position of an array -names.splice(2, 0, "Divyanshi", "Ayushi"); -console.log(names); // [ 'Samarth', 'Bob', 'Divyanshi', 'Ayushi', 'David', 'Mark' ] +names.splice(2, 0, "Shruti", "Rishi"); +console.log(names); // [ 'Samarth', 'Bob', 'Shruti', 'Rishi', 'David', 'Mark' ] names.splice(2, 2); console.log(names); // [ 'Samarth', 'Bob', 'David', 'Mark' ] @@ -48,7 +48,7 @@ const noOneLikesSam = names.slice(1); console.log(noOneLikesSam); // [ 'Bob', 'David', 'Mark' ] ``` -#### forEach method +#### forEach method ```js const numbers = [2, 4, 6, 8]; @@ -71,13 +71,13 @@ console.log(sum); // 20 ```js const inventory = [ - { price: 7, name: "egg" }, - { price: 10, name: "lays" }, - { price: 12, name: "maggie" }, + { price: 7, name: "egg" }, + { price: 10, name: "lays" }, + { price: 12, name: "maggie" }, ]; // Array Map -const prices = inventory.map((item) => console.log(item.price));// displays only the prices +const prices = inventory.map((item) => console.log(item.price)); // displays only the prices const names = inventory.map((item) => console.log(item.name)); // diplays only the names ``` @@ -94,21 +94,21 @@ console.log(negativeNumbers); // Another real life example const employeesData = [ - { name: "Shubham", overtime: 5 }, - { name: "Samarth", overtime: 7 }, - { name: "Seema", overtime: 8 }, + { name: "Shubham", overtime: 5 }, + { name: "Samarth", overtime: 7 }, + { name: "Seema", overtime: 8 }, ]; const employeesToReward = employeesData.filter( - (employee) => employee.overtime >= 7 + (employee) => employee.overtime >= 7 ); const employeeNames = employeesToReward.map((employee) => employee.name); -employeeNames.forEach((user)=>{ - console.log(`Congratulations, ${user}`); // Congratulations, Samarth - // Congratulations, Seema -}) +employeeNames.forEach((user) => { + console.log(`Congratulations, ${user}`); // Congratulations, Samarth + // Congratulations, Seema +}); ``` #### Array Find @@ -138,9 +138,9 @@ console.log(city); // New Delhi const movies = ["Avengers", "Superman", "Batman"]; if (movies.includes("Avengers")) { - console.log("The movie is available on prime");// The movie is available on prime + console.log("The movie is available on prime"); // The movie is available on prime } else { - console.log("The movie is not available on prime."); + console.log("The movie is not available on prime."); } // Note Includes method is case sensitive @@ -152,9 +152,9 @@ if (movies.includes("Avengers")) { // Array sort => Alphabetically, // doesn't sort numbers // This sort method mutates the original array -const names = ["Shubham", "Aditya", "Divyanshi", "Samarth"]; +const names = ["Shubham", "Aditya", "Shruti", "Samarth"]; names.sort(); -console.log(names); // [ 'Aditya', 'Divyanshi', 'Samarth', 'Shubham' ] +console.log(names); // [ 'Aditya', 'Shruti', 'Samarth', 'Shubham' ] const numbers = [4, 12, 8, 5, 1];