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..37e8a07 --- /dev/null +++ b/10_DOM/index.html @@ -0,0 +1,17 @@ + + + + + + + DOM + + + + + + diff --git a/10_DOM/script.js b/10_DOM/script.js new file mode 100644 index 0000000..71c5786 --- /dev/null +++ b/10_DOM/script.js @@ -0,0 +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"); +}; 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..2d48209 --- /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 } diff --git a/12_Asynchronous_Concepts/12.md b/12_Asynchronous_Concepts/12.md new file mode 100644 index 0000000..7be7de3 --- /dev/null +++ b/12_Asynchronous_Concepts/12.md @@ -0,0 +1,117 @@ +#### 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"); +``` + +#### Introduction to Synchronous and Asynchronous + +```js +// Synchronous Code +const functionOne = () => { + console.log("Function One"); // This will be printed first + + functionTwo(); + + console.log("Function One, Part two"); // This will be printed third +}; + +const functionTwo = () => { + 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 + +```js +// Callback functions + +const fetchUser = (username, callback) => { + setTimeout(() => { + callback({ username }); + }, 2000); +}; + +fetchUser("Shubham", (user) => { + console.log(`Hello, ${user.username}`); // Hello, Shubham +}); +``` + +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. + +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 +``` diff --git a/12_Asynchronous_Concepts/script.js b/12_Asynchronous_Concepts/script.js new file mode 100644 index 0000000..08f287f --- /dev/null +++ b/12_Asynchronous_Concepts/script.js @@ -0,0 +1,49 @@ +// 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"); + +// 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(); + +// callbacks; + +const cart = ["Shoes", "Shirt", "Pant"]; + +const Promise = createOrder(cart); + +Promise.then((orderId) => { + processPayment(orderId); +}); diff --git a/12_Asynchronous_Concepts/script2.js b/12_Asynchronous_Concepts/script2.js new file mode 100644 index 0000000..b1f7d6a --- /dev/null +++ b/12_Asynchronous_Concepts/script2.js @@ -0,0 +1,45 @@ +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); + }); +}; + +// 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(); 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 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..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]; @@ -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/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 649aa1a..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,3 +38,113 @@ const property = "age"; console.log(person[property]); // 23 ``` +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 = { + 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 +``` + +`this` notation is useful when you need to access a property whose name is stored in a variable. + +#### 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' } + +``` + +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/8_Objects_in_detail/objects2.js b/8_Objects_in_detail/objects2.js new file mode 100644 index 0000000..9346c31 --- /dev/null +++ b/8_Objects_in_detail/objects2.js @@ -0,0 +1,20 @@ +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/9_Value_vs_Reference/script.js b/9_Value_vs_Reference/script.js new file mode 100644 index 0000000..bdd1779 --- /dev/null +++ b/9_Value_vs_Reference/script.js @@ -0,0 +1,82 @@ +// 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 ] + +// 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 } + +// 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 } } 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..83a2d9e --- /dev/null +++ b/9_Value_vs_Reference/value_vs_reference.md @@ -0,0 +1,93 @@ +#### Copy by Reference + +```js +const animals = ["dogs", "cats"]; + +const otherAnimals = animals; + +animals.push("pig"); + +console.log(animals); // [ 'dogs', 'cats', 'pig' ] +console.log(otherAnimals); // [ 'dogs', 'cats', 'pig' ] +``` + +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 +// Cloning Arrays +// 1st way : Spread Operator +const numbers = [1, 2, 3, 4]; +const copiedNumbers = 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 ] + +// 2nd way : Array.slice() +const numbers = [1, 2, 3, 4]; +const copiedNumbers = numbers; + +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 } +``` + + 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 +const person = { + name: "Shubham", + car: { + brand: "BMW", + color: "blue", + wheels: 4, + }, +}; + +const newPerson = JSON.stringify(person); + +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. 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 diff --git a/README.md b/README.md index 3a26eb5..f18baa8 100644 --- a/README.md +++ b/README.md @@ -1,13 +1,18 @@ -# Crash Course on JavaScript +# Crash Course on JavaScript ![Javascript](https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRY_6xmpk2NCVs1LezEwt8U8UWIzp4NX5AFCw&usqp=CAU) ## 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) +- #### [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)