├── 8. react ├── babel.png └── react.md ├── 7. javascript-dom ├── dom.png ├── 3. negative-testing.md ├── 4. client-server-architecture.md ├── 2. browser.md └── 1. dom.md ├── 4. web-app-architecture ├── web-app.png ├── web-server-vs-application-server.png ├── 2. express-js.md └── 1. web-app-architecture.md ├── 6. html-css ├── 4. css-frameworks.md ├── default-stylesheets.jpeg ├── 3. standard-design-practices.md ├── 2. responsive-web-design.md ├── 1. basics.md └── html-css.md ├── 3. asynchronous-javascript ├── 6. es6.md ├── 7. self-review.md ├── promise_states.png ├── Callback_Function.png ├── 2. asynchronous-programming.md ├── 4. callback-hell-promise-chaining.md ├── 3. promise.md ├── 1. callback-functions.md └── 5. project.md ├── 1. dev-basics ├── README.md ├── 4. markdown.md ├── 5. computer-networks.md ├── 1. development-setup.md ├── 3. git.md └── 2. cli.md ├── 10. searching └── searching.md ├── 9. redux └── redux.md ├── README.md ├── 5. databases ├── 2. optional-practice.md └── 1. databases.md └── 2. javascript ├── 4. js-debugging-and-review.md ├── 1. getting-started.md ├── 3. javascript-practice.md └── 2. javascript-basics.md /8. react/babel.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mountblue/javascript-full-stack-path/HEAD/8. react/babel.png -------------------------------------------------------------------------------- /7. javascript-dom/dom.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mountblue/javascript-full-stack-path/HEAD/7. javascript-dom/dom.png -------------------------------------------------------------------------------- /4. web-app-architecture/web-app.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mountblue/javascript-full-stack-path/HEAD/4. web-app-architecture/web-app.png -------------------------------------------------------------------------------- /6. html-css/4. css-frameworks.md: -------------------------------------------------------------------------------- 1 | # CSS Frameworks 2 | 3 | - Popular Frameworks 4 | - Common Terminology 5 | - How to use a CSS Framework 6 | -------------------------------------------------------------------------------- /3. asynchronous-javascript/6. es6.md: -------------------------------------------------------------------------------- 1 | # ES6 2 | 3 | [https://www.youtube.com/watch?v=NCwa_xi0Uuc](https://www.youtube.com/watch?v=NCwa_xi0Uuc) 4 | -------------------------------------------------------------------------------- /6. html-css/default-stylesheets.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mountblue/javascript-full-stack-path/HEAD/6. html-css/default-stylesheets.jpeg -------------------------------------------------------------------------------- /3. asynchronous-javascript/7. self-review.md: -------------------------------------------------------------------------------- 1 | # Self Review 2 | 3 | Write a technical paper on: 4 | * Callbacks 5 | * Promises 6 | * Code Control 7 | -------------------------------------------------------------------------------- /3. asynchronous-javascript/promise_states.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mountblue/javascript-full-stack-path/HEAD/3. asynchronous-javascript/promise_states.png -------------------------------------------------------------------------------- /3. asynchronous-javascript/Callback_Function.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mountblue/javascript-full-stack-path/HEAD/3. asynchronous-javascript/Callback_Function.png -------------------------------------------------------------------------------- /6. html-css/3. standard-design-practices.md: -------------------------------------------------------------------------------- 1 | # Standard Design Practices 2 | 3 | - Commonly used design elements 4 | - Providing feedback to the user 5 | - Professional practices 6 | -------------------------------------------------------------------------------- /1. dev-basics/README.md: -------------------------------------------------------------------------------- 1 | # Developer Basics 2 | 3 | Follow the order: 4 | 1. Development Setup 5 | 2. Command Line Interface - CLI 6 | 3. Git 7 | 4. Markdown 8 | 5. Computer Networks 9 | -------------------------------------------------------------------------------- /4. web-app-architecture/web-server-vs-application-server.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mountblue/javascript-full-stack-path/HEAD/4. web-app-architecture/web-server-vs-application-server.png -------------------------------------------------------------------------------- /10. searching/searching.md: -------------------------------------------------------------------------------- 1 | # Searching 2 | 3 | ## NPM 4 | 5 | Video - How to choose and use npm modules 6 | [https://www.youtube.com/watch?v=DuyxqG3L7A8](https://www.youtube.com/watch?v=DuyxqG3L7A8) 7 | 8 | ## Documentation 9 | -------------------------------------------------------------------------------- /1. dev-basics/4. markdown.md: -------------------------------------------------------------------------------- 1 | # Markdown 2 | 3 | Learn markdown from the following link 4 | 5 | [Github markdown guide](https://guides.github.com/features/mastering-markdown/) 6 | 7 | Use Markdown in every technical paper, Readme.md and LMS submissions 8 | -------------------------------------------------------------------------------- /1. dev-basics/5. computer-networks.md: -------------------------------------------------------------------------------- 1 | The following YouTube is a simple and clear explanation of computer networks without getting too much into the theory. 2 | 3 | [https://www.youtube.com/watch?v=aHJElrgj6UA](https://www.youtube.com/watch?v=aHJElrgj6UA) 4 | -------------------------------------------------------------------------------- /9. redux/redux.md: -------------------------------------------------------------------------------- 1 | # Redux 2 | 3 | ## Introduction to Redux 4 | 5 | [https://www.youtube.com/watch?v=poQXNp9ItL4](https://www.youtube.com/watch?v=poQXNp9ItL4) 6 | 7 | ## React-Redux Library 8 | 9 | [React-Redux Guide](https://www.valentinog.com/blog/redux/) 10 | -------------------------------------------------------------------------------- /7. javascript-dom/3. negative-testing.md: -------------------------------------------------------------------------------- 1 | # Negative Testing Web Apps 2 | 3 | Negative Testing - [https://web.archive.org/web/20210305071223/https://crossbrowsertesting.com/blog/manual-testing/negative-testing/](https://web.archive.org/web/20210305071223/https://crossbrowsertesting.com/blog/manual-testing/negative-testing/) 4 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # JavaScript Full Stack Path 2 | 3 | Sequence of topics (tentative): 4 | 5 | - Basics: 6 | - Development Setup 7 | - Command Line Interface - CLI 8 | - Git 9 | - Markdown 10 | - Computer Networks 11 | - JavaScript 12 | - Asynchronous JavaScript 13 | - Web App Architecture 14 | - Databases 15 | - HTML and CSS 16 | - JavaScript DOM 17 | - React 18 | - Redux 19 | - Searching 20 | 21 | -------------------------------------------------------------------------------- /7. javascript-dom/4. client-server-architecture.md: -------------------------------------------------------------------------------- 1 | # Client Server Architecture 2 | 3 | Articles 4 | - [https://www.pagecloud.com/blog/website-terminology](https://www.pagecloud.com/blog/website-terminology) 5 | - [https://engineering.videoblocks.com/web-architecture-101-a3224e126947](https://engineering.videoblocks.com/web-architecture-101-a3224e126947) 6 | 7 | Check the Slides on Slideshare for Client Server Architecture [https://www.slideshare.net/secret/wYOQgHZBO0B1qm](https://www.slideshare.net/secret/wYOQgHZBO0B1qm) 8 | 9 | Watch the video below for the recorded session. (55 minutes 59 seconds) 10 | 11 | [https://www.youtube.com/watch?v=h_7XxdbnkAg](https://www.youtube.com/watch?v=h_7XxdbnkAg) 12 | -------------------------------------------------------------------------------- /7. javascript-dom/2. browser.md: -------------------------------------------------------------------------------- 1 | # Browsers 2 | 3 | ## How does a Browser Work? 4 | 5 | How Browser Rendering Works 6 | 7 | Text: 8 | [https://blog.logrocket.com/how-browser-rendering-works-behind-the-scenes-6782b0e8fb10/](https://blog.logrocket.com/how-browser-rendering-works-behind-the-scenes-6782b0e8fb10/) 9 | 10 | Video: 11 | [https://www.youtube.com/watch?v=0IsQqJ7pwhw](https://www.youtube.com/watch?v=0IsQqJ7pwhw) 12 | 13 | 14 | ## Developer Tools 15 | 16 | Google Chrome Developer Tools Crash Course 17 | [https://www.youtube.com/watch?v=x4q86IjJFag](https://www.youtube.com/watch?v=x4q86IjJFag) 18 | 19 | ### Debugging Tips 20 | 21 | - [The 16 JavaScript debugging tips you probably didn’t know](https://raygun.com/learn/javascript-debugging-tips) 22 | - Debugging in the browser - [https://javascript.info/debugging-chrome](https://javascript.info/debugging-chrome) 23 | - Understand Client Side VS Server Side Rendering 24 | 25 | -------------------------------------------------------------------------------- /6. html-css/2. responsive-web-design.md: -------------------------------------------------------------------------------- 1 | # Responsive Web Design 2 | 3 | ## Live Coding Tutorial 4 | 5 | [https://www.youtube.com/watch?v=Wm6CUkswsNw](https://www.youtube.com/watch?v=Wm6CUkswsNw) 6 | 7 | ## Relative Units 8 | 9 | - [https://css-tricks.com/the-lengths-of-css/](https://css-tricks.com/the-lengths-of-css/) 10 | - [https://css-tricks.com/building-resizeable-components-relative-css-units/](https://css-tricks.com/building-resizeable-components-relative-css-units/) 11 | 12 | ## CSS Media Queries 13 | 14 | - [https://css-tricks.com/css-media-queries/](https://css-tricks.com/css-media-queries/) 15 | - [https://css-tricks.com/logic-in-media-queries/](https://css-tricks.com/logic-in-media-queries/) 16 | 17 | ## Responsive Drills 18 | 19 | [https://gitlab.com/mountblue/js/responsive-layout-drill](https://gitlab.com/mountblue/js/responsive-layout-drill) 20 | 21 | Create a Codepen collection with solutions and submit the collection URL 22 | 23 | ## Project - EasyBank Landing Page 24 | 25 | Link to project: [https://gitlab.com/mountblue/js/easybank-landing-page](https://gitlab.com/mountblue/js/easybank-landing-page) 26 | 27 | - Fork the repository 28 | - Clone it in your local machine 29 | - **Make regular commits to your project** 30 | 31 | ## Testing on your mobile 32 | 33 | You can use `ngrok` or `localtunnel` 34 | 35 | Video - [https://www.youtube.com/watch?v=DCxt9SAnkyc](https://www.youtube.com/watch?v=DCxt9SAnkyc) 36 | -------------------------------------------------------------------------------- /1. dev-basics/1. development-setup.md: -------------------------------------------------------------------------------- 1 | # Development Setup 2 | 3 | ## 1. Install Linux - preferably Ubuntu 20.04 or later 4 | 5 | You need a linux equivalent operating system loaded computer for this Bootcamp. If you do not have Linux, **STOP HERE** and install Ubuntu 20.04 or later on your development machine. 6 | 7 | ### NOTE 8 | - Macs are also acceptable as developer machines. 9 | - Any flavour of Linux is acceptable. 10 | - Windows is **NOT acceptable**. If you have Windows, install Ubuntu. 11 | 12 | ### Reference 13 | [https://github.com/mountblue/gearup/blob/master/dual_booting_ubuntu_windows.md](https://github.com/mountblue/gearup/blob/master/dual_booting_ubuntu_windows.md) 14 | 15 | ## 2. Setup Visual Studio Code 16 | 17 | Follow the instructions to install Visual Studio Code from [this website](https://code.visualstudio.com/docs/setup/linux) 18 | 19 | ### Plugins 20 | Install the following VSCode plugins 21 | 1. Ruby / RoR 22 | 2. Markdown all in one 23 | 24 | ## 3. Online tools 25 | 26 | We use a lot of tools like zoom, discord, gitlab etc. Use the form at the end of this target give me details on how to reach you. 27 | 28 | 1. Create a zoom account. Install Zoom on both your laptop and mobile. 29 | 2. Install Discord on both your laptop and mobile. 30 | 3. CREATE A NEW [gitlab account](https://gitlab.com/users/sign_up) using your mountblue.tech account. 31 | 32 | ## 4. Install git 33 | 34 | The following command should be enough to install git. 35 | 36 | ```bash 37 | $ sudo apt install git 38 | ``` 39 | 40 | For mac use 41 | ```bash 42 | $ brew install git 43 | ``` 44 | -------------------------------------------------------------------------------- /3. asynchronous-javascript/2. asynchronous-programming.md: -------------------------------------------------------------------------------- 1 | # Asynchronous Programming 2 | 3 | Read this 4 | 5 | [https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Asynchronous/Concepts](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Asynchronous/Concepts) 6 | 7 | ## Tutorials 8 | 9 | [https://github.com/workshopper/learnyounode](https://github.com/workshopper/learnyounode) 10 | 11 | Remaining Sections/Topics from [CodeAcademy](https://www.codecademy.com/learn/introduction-to-javascript) Promises, Async/Await, Request 12 | 13 | ## Best Practices: if else 14 | 15 | Bad Usage: 16 | 17 | ```javascript 18 | fs.readFile(filePath, "utf-8", (err, data) => { 19 | if(err) { 20 | console.error(err); 21 | } 22 | 23 | console.log(data); 24 | }); 25 | ``` 26 | 27 | Good Usage: 28 | 29 | ```javascript 30 | fs.readFile(filePath, "utf-8", (err, data) => { 31 | if(err) { 32 | console.error(err); 33 | } else { 34 | console.log(data); 35 | } 36 | }); 37 | ``` 38 | 39 | The reason why the bad usage is considered bad is because if we were to run any operations on the `data` variable on line 6 such as `data.length`, it would work when the operation is successful. 40 | 41 | But when it is not, the bad structure will not stop the `data.length` operation from running, and because it will be `undefined`, it will cause your code to crash. 42 | 43 | It can be prevented by using `return` inside the `if` but it is easier to just use the good usage example as you will not fall prey to forgetting the `return` when you use the good structure. 44 | 45 | ## Error First Callback Functions 46 | 47 | [Read this article](https://fredkschott.com/post/2014/03/understanding-error-first-callbacks-in-node-js/) 48 | 49 | ## Asynchronous Callbacks Control - Clarification Session 50 | 51 | [https://www.youtube.com/watch?v=mZ0FkdIBE2o](https://www.youtube.com/watch?v=mZ0FkdIBE2o) 52 | 53 | -------------------------------------------------------------------------------- /5. databases/2. optional-practice.md: -------------------------------------------------------------------------------- 1 | # SQL 2 | 3 | ## 1. Install and get familiar with PostgreSQL 4 | 5 | Follow the instructions given in this article 6 | [https://www.digitalocean.com/community/tutorials/how-to-install-postgresql-on-ubuntu-20-04-quickstart](https://www.digitalocean.com/community/tutorials/how-to-install-postgresql-on-ubuntu-20-04-quickstart) 7 | 8 | ## 2. Practice SQL 9 | 10 | ### 2a. SQLBolt 11 | 12 | Complete [SQLBolt](https://sqlbolt.com/) 3 times. 13 | 14 | ### 2b. PG Exercises 15 | 16 | Complete [PostgreSQL Exercises](https://pgexercises.com/) 3 times. (Recursive Queries are optional) 17 | 18 | ## 3. Data Project - SQL Version 19 | 20 | Solve the IPL data problem, but this time with SQL, using PostgreSQL database. 21 | 22 | #### 1. Create DB, permissions etc. 23 | Write a SQL script that creates a new user, and database. Make the user the owner of the db. 24 | 25 | #### 2. Clean up script 26 | Write another SQL script that cleans up the user, and database created in the previous step. 27 | 28 | #### 3. Load CSV 29 | Write a SQL script that loads CSV data into a table. 30 | 31 | #### 4. Solve the IPL problems 32 | In a SQL file write queries that will solve the problems of the IPL data set, but this time with SQL. You can copy paste the queries in a .sql file and submit. 33 | 34 | **Note:** the result in this case is not a graph but SQL Result Set. 35 | 36 | ### Submission 37 | As with previous projects ... 38 | 39 | 1. Create a repository - `data-project-database`. 40 | 2. All the code for this assignment should be in that repo. 41 | 3. Supporting files like .gitignore, README.md should also be included. 42 | 4. The README should have all the info for your mentor to run the scripts. 43 | 44 | ## 4. SQL Concepts - Technical Paper 45 | 46 | Write a technical paper in detail in markdown format 47 | 48 | Some concepts to understand for databases: 49 | * ACID 50 | * CAP Theorem 51 | * Joins 52 | * Aggregations, Filters in queries 53 | * Normalization 54 | * Indexes 55 | * Transactions 56 | * Locking mechanism 57 | * Database Isolation Levels 58 | * Triggers 59 | -------------------------------------------------------------------------------- /6. html-css/1. basics.md: -------------------------------------------------------------------------------- 1 | # HTML and CSS Basics 2 | 3 | ## Do any 1 Tutorial 4 | 5 | - [https://www.udacity.com/course/intro-to-html-and-css--ud001](https://www.udacity.com/course/intro-to-html-and-css--ud001) 6 | - [https://dash.generalassemb.ly/](https://dash.generalassemb.ly/) 7 | - [https://learn.shayhowe.com/](https://learn.shayhowe.com/) 8 | - [https://marksheet.io/](https://marksheet.io/) 9 | - [https://www.internetingishard.com/html-and-css/](https://www.internetingishard.com/html-and-css/) 10 | 11 | ## CSS Selectors 12 | 13 | - [https://www.educative.io/edpresso/what-are-css-selectors](https://www.educative.io/edpresso/what-are-css-selectors) 14 | - [https://css-tricks.com/how-css-selectors-work/](https://css-tricks.com/how-css-selectors-work/) 15 | 16 | ## Box Model 17 | 18 | [https://css-tricks.com/the-css-box-model/](https://css-tricks.com/the-css-box-model/) 19 | 20 | ## Flexbox 21 | 22 | Resources: 23 | - [CSS Flex Video](https://www.youtube.com/watch?v=JJSoEo8JSnc) 24 | - [https://css-tricks.com/snippets/css/a-guide-to-flexbox/](https://css-tricks.com/snippets/css/a-guide-to-flexbox/) 25 | 26 | Play the games to practice: 27 | - [https://flexboxfroggy.com/](https://flexboxfroggy.com/) 28 | - [http://www.flexboxdefense.com/](http://www.flexboxdefense.com/) 29 | 30 | ## Default Browser Styles 31 | 32 | This is a zine by Julia Evans. 33 | ![default stylesheets](./default-stylesheets.jpeg "default stylesheets") 34 | 35 | ## Layout Drills 36 | 37 | [https://gitlab.com/mountblue/js/css-layout-drills](https://gitlab.com/mountblue/js/css-layout-drills) 38 | 39 | Create a [codepen](https://codepen.io/) collection with solutions for all problems and submit the Codepen collection URL 40 | 41 | NOTE: Each problem can have multiple solutions. Also, ignore the `div` numbers, they have been used for illustrations only. 42 | 43 | ## Pricing Page Project 44 | 45 | **Instructions** 46 | - Fork this repository: 47 | [https://gitlab.com/mountblue/js/pricing-html-css](https://gitlab.com/mountblue/js/pricing-html-css) 48 | - Clone it in your local machine 49 | - **Make regular commits to your project** 50 | 51 | ### Optionally use reset.css 52 | -------------------------------------------------------------------------------- /3. asynchronous-javascript/4. callback-hell-promise-chaining.md: -------------------------------------------------------------------------------- 1 | # Callback-Hell and Chaining of Promises 2 | 3 | ## What is the difference between Callbacks and Promises? 4 | The main difference between Callback Functions and Promises is that we attach a callback to a Promise rather than passing it. So we still use callback functions with Promises, but in a different way (chaining). 5 | 6 | This is one of the greatest advantages of using Promises, but why? 7 | 8 | ## What is Chaining? 9 | Callback functions have been used alone for asynchronous operations in JavaScript for many years. But in some cases, using Promises can be a better option. 10 | 11 | If there are multiple async operations to be done and if we try to use good-old Callbacks for them, we’ll find ourselves quickly inside a situation called Callback hell: 12 | 13 | ```javascript 14 | firstRequest(function(response) { 15 | secondRequest(response, function(nextResponse) { 16 | thirdRequest(nextResponse, function(finalResponse) { 17 | console.log('Final response: ' + finalResponse); 18 | }, failureCallback); 19 | }, failureCallback); 20 | }, failureCallback); 21 | ``` 22 | However if we handle the same operation with Promises, since we can attach Callbacks rather than passing them, this time the same code above looks much cleaner and easier to read: 23 | 24 | ```javascript 25 | firstRequest() 26 | .then(function(response) { 27 | return secondRequest(response); 28 | }).then(function(nextResponse) { 29 | return thirdRequest(nextResponse); 30 | }).then(function(finalResponse) { 31 | console.log('Final response: ' + finalResponse); 32 | }).catch(failureCallback); 33 | ``` 34 | The code just above shows how multiple callbacks can be chained one after another. Chaining is one of the best features of Promises. 35 | 36 | ### Video 37 | [https://www.youtube.com/watch?v=OXpZfyVXeI8](https://www.youtube.com/watch?v=OXpZfyVXeI8) 38 | 39 | ## Recap 40 | 41 | Go through the following blog and related video to get an idea of asynchronous JavaScript 42 | 43 | [https://ui.dev/async-javascript-from-callbacks-to-promises-to-async-await/](https://ui.dev/async-javascript-from-callbacks-to-promises-to-async-await/) 44 | 45 | ### Video 46 | [https://www.youtube.com/watch?v=gB-OmN1egV8](https://www.youtube.com/watch?v=gB-OmN1egV8) 47 | 48 | ## Event Loop 49 | Read this 50 | 51 | [https://flaviocopes.com/javascript-event-loop/](https://flaviocopes.com/javascript-event-loop/) 52 | 53 | ### Video 54 | [https://www.youtube.com/watch?v=8aGhZQkoFbQ](https://www.youtube.com/watch?v=8aGhZQkoFbQ) 55 | 56 | 57 | -------------------------------------------------------------------------------- /4. web-app-architecture/2. express-js.md: -------------------------------------------------------------------------------- 1 | # Express JS 2 | 3 | - Hello World with ExpressJS - [https://expressjs.com/en/starter/hello-world.html](https://expressjs.com/en/starter/hello-world.html) 4 | - Video - ExpressJS Crash Course - [https://www.youtube.com/watch?v=L72fhGm1tfE](https://www.youtube.com/watch?v=L72fhGm1tfE) 5 | - Writing Middleware - [https://expressjs.com/en/guide/writing-middleware.html](https://expressjs.com/en/guide/writing-middleware.html) 6 | 7 | ## Project - IPL Project II 8 | 9 | Instructions: 10 | **For this part, create a new branch called `webapp` in your previously created IPL Project repository and make commits in it.** 11 | 12 | Use a static webserver to serve your output JSON files. ( Remember your CLI drills on how to start a static server? ) 13 | 14 | Build a simple client web app, where you make an HTTP GET request to get the JSON file and display the data as a visualization. The visualization should be done using this library [https://www.highcharts.com/](https://www.highcharts.com/) 15 | 16 | 17 | Directory structure: 18 | 19 | - src/ 20 | - server/ 21 | - ipl.js 22 | - index.js 23 | - **public**/ 24 | - output 25 | - matchesPerYear.json 26 | - ... 27 | - index.html 28 | - style.css 29 | - data/ 30 | - matches.csv 31 | - deliveries.csv 32 | - package.json 33 | - package-lock.json 34 | - .gitignore 35 | 36 | ### API Design Guidelines 37 | 38 | ### HTTP Drills II 39 | On a separate branch, convert your http-drill-1 project to use expressjs. 40 | 41 | ### Express Error Handlers 42 | 43 | Use google and do the following: 44 | 45 | 1. Understand what the default error handler is 46 | 2. Learn how to setup a custom error handler 47 | 3. Learn how to setup a 404 error handler 48 | 49 | ### Git Merge Drill 1 50 | 51 | **DO NOT ATTEMPT THIS BY YOURSELF** 52 | 53 | [Ping your mentor and ask about this](https://gitlab.com/mountblue/cohort-js-common/express-merge-conflicts) 54 | 55 | 56 | ## Authentication 57 | 58 | ### JWT- JSON Web Token 59 | 60 | - [Authentication and Authorization with JWTs in Express.js](https://stackabuse.com/authentication-and-authorization-with-jwts-in-express-js/) 61 | - [Technical Introduction to JSON Web Tokens](https://jwt.io/introduction/) 62 | - [JSON Web Tokens (JWTs) in Express.js](https://www.digitalocean.com/community/tutorials/nodejs-jwt-expressjs) 63 | - Video - [https://www.youtube.com/watch?v=7nafaH9SddU](https://www.youtube.com/watch?v=7nafaH9SddU) 64 | 65 | ## Loggers 66 | 67 | ### What is a logger? 68 | 69 | Why not console.log 70 | https://www.twilio.com/blog/guide-node-js-logging 71 | 72 | Log Levels 73 | https://blog.logrocket.com/node-js-logging-best-practices/ 74 | 75 | Implement: 76 | https://github.com/winstonjs/winston 77 | 78 | ### What is a log shipper? 79 | https://sematext.com/blog/logging-libraries-vs-log-shippers/ 80 | -------------------------------------------------------------------------------- /2. javascript/4. js-debugging-and-review.md: -------------------------------------------------------------------------------- 1 | # JavaScript Debugging and Review 2 | 3 | ## Debugging 4 | 5 | - How to read a JavaScript Stack Trace - [https://harrymoreno.com/2017/02/25/how-to-read-a-javascript-stack-trace.html](https://harrymoreno.com/2017/02/25/how-to-read-a-javascript-stack-trace.html) 6 | - What is the difference between `throw new Error` and `throw someObject`? - [https://stackoverflow.com/questions/9156176/what-is-the-difference-between-throw-new-error-and-throw-someobject](https://stackoverflow.com/questions/9156176/what-is-the-difference-between-throw-new-error-and-throw-someobject) 7 | - Using console methods - [https://fireship.io/courses/javascript/concepts-console/](https://fireship.io/courses/javascript/concepts-console/) 8 | 9 | 10 | ## Self Review 11 | 12 | Write a technical paper on each topic listed below. 13 | 14 | All technical papers should be: 15 | 1. in markdown format 16 | 2. hosted in a single folder on Gitlab. 17 | 3. Use your own words and your own examples. 18 | 4. This is for your own revision. Do not copy paste from internet or each other. 19 | 5. Less words is appreciated. Make sure it is to the point. 20 | 6. Focus more on code samples and codeblocks. 21 | 22 | Share link of the folder in your private Discord channel when you start. Also just drop a message when each technical paper is completed. 23 | 24 | ### Topics: 25 | - Loops 26 | - for 27 | - forEach 28 | - for .. in 29 | - for .. of 30 | - while 31 | - Mutable and Immutable Methods (in strings and arrays) 32 | - Pass by Reference and Pass by Value - add codeblocks 33 | - Array methods - add codeblocks and mention mutable/immutable 34 | - **Basics**: 35 | - Array.pop 36 | - Array.push 37 | - Array.concat 38 | - Array.slice 39 | - Array.splice 40 | - Array.join 41 | - Array.flat 42 | - **Finding**: 43 | - Array.find 44 | - Array.indexOf 45 | - Array.includes 46 | - Array.findIndex 47 | - **Higher Order Functions**: 48 | - Array.forEach 49 | - Array.filter 50 | - Array.map 51 | - Array.reduce 52 | - Array.sort 53 | - **Advanced**: 54 | - Array methods chaining 55 | - String methods - add codeblocks and mention mutable/immutable 56 | - Object methods and operations - add codeblocks and mention mutable/immutable 57 | - Hoisting 58 | - Scopes 59 | - Closures 60 | - Higher Order Functions 61 | - Best Practices 62 | - Debugging 63 | 64 | ## Miscellaneous 65 | 66 | - History of JavaScript 67 | - [https://ui.dev/ecmascript/](https://ui.dev/ecmascript/) 68 | - [https://auth0.com/blog/a-brief-history-of-javascript/](https://auth0.com/blog/a-brief-history-of-javascript/) 69 | - Imperative VS Declarative Programming 70 | - [https://ui.dev/imperative-vs-declarative-programming/](https://ui.dev/imperative-vs-declarative-programming/) 71 | - Clean Code 72 | - [https://github.com/ryanmcdermott/clean-code-javascript](https://github.com/ryanmcdermott/clean-code-javascript) 73 | 74 | -------------------------------------------------------------------------------- /3. asynchronous-javascript/3. promise.md: -------------------------------------------------------------------------------- 1 | # Promise 2 | 3 | ## What is a Promise? 4 | A promise in JavaScript is similar to a promise in real life. When we make a promise in real life, it is a guarantee that we are going to do something in the future. Because promises can only be made for the future. 5 | 6 | A promise has 2 possible outcomes: it will either be kept when the time comes, or it won’t. 7 | 8 | This is also the same for promises in JavaScript. When we define a promise in JavaScript, it will be resolved when the time comes, or it will get rejected. 9 | 10 | ## Promises in JavaScript 11 | 12 | First of all, a Promise is an object. There are 3 states of the Promise object: 13 | 14 | - **Pending**: is the initial state. 15 | - **Resolved**: indicates that the promised operation was successful. 16 | - **Rejected**: indicates that the promised operation was unsuccessful.​ 17 | 18 | ![promise states](./promise_states.png "promise states") 19 | 20 | For example, when we request data from the server by using a Promise, it will be in pending mode until we receive our data. 21 | 22 | If we achieve to get the information from the server, the Promise will be resolved successfully. But if we don’t get the information, then the Promise will be in the rejected state. 23 | 24 | ## Creating a simple promise 25 | 26 | 1. A promise is created using a constructor that takes a call back function with two arguments (line 1). 27 | 2. The code needed to perform the promised task is written. In this example, it is assumed that the code executes successfully (line 2). 28 | 3. If the task is successful, the promise is resolved. In this example, the optional parameter “The promised task was performed successfully” is passed (lines 4-5). 29 | 4. If the task is unsuccessful, then the promise is rejected. In this example, an optional parameter is passed (lines 6-7). 30 | 5. The then() method is called when the promise is resolved, ​and the catch() method is called if the promise is rejected or if there was an error during the code execution (lines 10-11). 31 | 32 | ```javascript 33 | let promise = new Promise((resolve, reject) => { 34 | // Code to perform the promised task 35 | let task_performed = true; 36 | if(task_performed) { 37 | resolve('The promised task was performed successfully.'); 38 | } else { 39 | reject('The promised task was not performed.'); 40 | } 41 | }); 42 | promise.then((fromRes) => console.log(fromRes)). 43 | catch((fromRej) => console.log(fromRej)); 44 | ``` 45 | 46 | ## Using Promise.all() 47 | 48 | The **Promise.all()** method returns a single promise that resolves when all of the passed-in promises have resolved. It rejects if one of the promises is rejected. 49 | 50 | ```javascript 51 | let promise1 = new Promise((resolve, reject) => { 52 | resolve(1); 53 | }); 54 | let promise2 = new Promise((resolve, reject) => { 55 | setTimeout(resolve, 1000,2); 56 | }); 57 | Promise.all([promise1, promise2]).then( () => { 58 | console.log("Both the promises have been resolved successfully."); 59 | }); 60 | ``` 61 | 62 | ## Using Promise.race() 63 | 64 | The **Promise.race()** method returns a promise that resolves or rejects as soon as one of the promises resolves or rejects. The **fromRes** method​ contains the value from the promise that is resolved first. 65 | 66 | ```javascript 67 | let promise1 = new Promise((resolve, reject) => { 68 | setTimeout(resolve(2), 100); 69 | }); 70 | let promise2 = new Promise((resolve, reject) => { 71 | resolve(1); 72 | }); 73 | Promise.race([promise1, promise2]).then((fromRes) => { 74 | console.log(fromRes); 75 | }); 76 | ``` 77 | -------------------------------------------------------------------------------- /8. react/react.md: -------------------------------------------------------------------------------- 1 | # React 2 | 3 | ## Prerequisites 4 | 5 | - JS Library vs Framework 6 | - Client side frameworks - [https://developer.mozilla.org/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks](https://developer.mozilla.org/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks) 7 | - Webpack - [https://ui.dev/webpack/](https://ui.dev/webpack/) 8 | - Polyfills - [https://ui.dev/compiling-polyfills/](https://ui.dev/compiling-polyfills/) 9 | - Babel - [https://babeljs.io/repl](https://babeljs.io/repl) 10 | 11 | ### Babel & Webpack with React 12 | 13 | Go through the following articles for a good understanding of the topic. You do not need to implement anything. 14 | 15 | - [JavaScript Transpilers: What They Are & Why We Need Them](https://scotch.io/tutorials/javascript-transpilers-what-they-are-why-we-need-them) 16 | - [Using Vite to create a new React app](https://flaviocopes.com/vite-react-app/) 17 | - [React Developer Tools 18 | ](https://react.dev/learn/react-developer-tools) 19 | 20 | ## ReactJS 21 | 22 | ### 1. React Crash course 23 | 24 | - [Programming with Mosh](https://youtu.be/SqcY0GlETPk?si=PZzD9Mo7SKKEU6OB) - This is a simple introduction to React 25 | - [Traversy Media](https://youtu.be/LDB4uaJ87e0?si=aDVqcrFVw0tzrUuZ) - This includes introduction and more stuff like routing etc. 26 | 27 | ### 2. React Mini Projects (Build any two) 28 | 29 | - [Video with 25 projects](https://youtu.be/5ZdHfJVAY-s?si=DgQvMSzLXYTGhrgq) 30 | - [React Official tutorial](https://react.dev/learn/tutorial-tic-tac-toe) 31 | 32 | ### 4. Read the following sections from official docs and practice the challenges at the end of each sub-section 33 | 34 | - [Describing the UI 35 | ](https://react.dev/learn/describing-the-ui) 36 | - [Adding Interactivity](https://react.dev/learn/adding-interactivity) 37 | - Also go through this [The Interactive Guide to Rendering in React 38 | ](https://ui.dev/why-react-renders) 39 | > This is a good reference for all the react hooks - [Codevolution playlist](https://www.youtube.com/playlist?list=PLC3y8-rFHvwisvxhZ135pogtX7_Oe3Q3A) 40 | 41 | ### 5. REST Countries project 42 | 43 | Points to focus on when building this project 44 | 45 | - Code quality - spell check, code convetions, code formatting - eslint and prettied enabled 46 | - Separating out different components 47 | - Building reusable components if feasible 48 | - Ensuring component state doesn't contain derived data 49 | - Controlled vs Un-controlled components 50 | - Repo https://gitlab.com/mountblue/js/rest-countries 51 | 52 | ### 6. Read the following sections from official docs and practice the challenges at the end of each sub-section 53 | 54 | - [Managing State 55 | ](https://react.dev/learn/managing-state) 56 | - [Escape Hatches 57 | ](https://react.dev/learn/escape-hatches) 58 | 59 | ### 7. Trello project 60 | 61 | Points to focus on when building this project 62 | 63 | - Code quality - spell check, code convetions, code formatting - eslint and prettied enabled 64 | - Separating out different components 65 | - Building reusable components if feasible 66 | - Ensuring component state doesn't contain derived data 67 | - Controlled vs Un-controlled components 68 | - Project description: https://rentry.co/nsqq2wos 69 | 70 | ### 8. useReducer 71 | 72 | Implement useReducer for Trello project in a different git branch. Understand the difference b/w useState vs useReducer vs useContext 73 | 74 | ### 9. Redux toolkit 75 | 76 | Implement redux toolkit for Trello project in a different git branch. Understand the difference b/w useReducer vs useState vs Redux. Points to focus on: 77 | 78 | - Should we move all the state to redux ? 79 | - What kind of state should we not move to redux ? 80 | 81 | ## React Router 82 | 83 | #### Blogs 84 | 85 | - https://ui.dev/react-router-tutorial 86 | - https://www.freecodecamp.org/news/how-to-use-react-router-version-6/ 87 | 88 | #### Video tutorials 89 | 90 | - https://youtu.be/59IXY5IDrBA?si=WL-JWMQ_O5RMg5I_ 91 | - https://youtu.be/Ul3y1LXxzdU?si=_xvwmQIk4asM2txz 92 | -------------------------------------------------------------------------------- /3. asynchronous-javascript/1. callback-functions.md: -------------------------------------------------------------------------------- 1 | # Callback functions 2 | 3 | ## Passing function as an argument 4 | 5 | Just like almost everything in JavaScript (except primitive data types), functions are an object type. So like any other object type, functions can be passed to other functions. 6 | 7 | The foo( ) function takes another function as a parameter and calls it inside. This is valid in JavaScript and we call it a “callback”. So a function that is passed to another function as a parameter is a callback function. 8 | 9 | ![callback function](./Callback_Function.png "callback function") 10 | 11 | ## An Example 12 | 13 | Have a look at the code given below. 14 | 15 | ```javascript 16 | function calculateSum(n, callback) { 17 | var i; 18 | var sum = 0; 19 | for (i = 1; i <= n; i++) { 20 | sum += i; 21 | } 22 | console.log(`Sum is: ${sum}`); 23 | callback(sum); 24 | } 25 | 26 | var n = 10; 27 | calculateSum(n, function(sum){ 28 | console.log(`Average is: ${sum/n}`); 29 | }); 30 | ``` 31 | 32 | This is how it’s working: 33 | 34 | - **Lines 1-9**: The calculateSum function receives a number n, and a callback function. It sums the numbers from 1 up to n, prints out the calculated sum and passes it to the callback function, as shown on Line 8. 35 | 36 | - **Lines 12-14**: When calling the calculateSum function, the callback function has also been defined inside the function call. It takes the sum passed to it by calculateSum and uses that sum to print out the average. 37 | 38 | > The callback function can also be defined separately and then passed to the function call. 39 | 40 | ## Why do we need Callback Functions? 41 | 42 | JavaScript runs code sequentially in top-down order. However, there are some cases that code runs (or must run) after something else happens and also not sequentially. This is called asynchronous programming. 43 | 44 | Callbacks make sure that a function is not going to run before a task is completed but will run right after the task has completed. It helps us develop asynchronous JavaScript code and keeps us safe from problems and errors. 45 | 46 | In JavaScript, the way to create a callback function is to pass it as a parameter to another function, and then to call it back right after something has happened or some task is completed. Let’s see how… 47 | 48 | ## How to create a Callback? 49 | 50 | Let's say we want to log a message to the console but it should be there after 3 seconds. 51 | 52 | ```javascript 53 | const message = function() { 54 | console.log("This message is shown after 3 seconds"); 55 | } 56 | 57 | setTimeout(message, 3000); 58 | ``` 59 | 60 | There is a built-in method in JavaScript called “setTimeout”, which calls a function or evaluates an expression after a given period of time (in milliseconds). So here, the “message” function is being called after 3 seconds have passed. (1 second = 1000 milliseconds) 61 | 62 | In other words, the message function is being called after something happened (after 3 seconds passed for this example), but not before. So the message function is an example of a callback function. 63 | 64 | ## What is an Anonymous Function? 65 | 66 | Alternatively, we can define a function directly inside another function, instead of calling it. It will look like this: 67 | 68 | ```javascript 69 | setTimeout(function() { 70 | console.log("This message is shown after 3 seconds"); 71 | }, 3000); 72 | ``` 73 | 74 | As we can see, the callback function here has no name and a function definition without a name in JavaScript is called an “anonymous function”. This does exactly the same task as the example above. 75 | 76 | ## Callback as an Arrow Function 77 | 78 | If you prefer, you can also write the same callback function as an ES6 arrow function, which is a newer type of function in JavaScript: 79 | 80 | ```javascript 81 | setTimeout(() => { 82 | console.log("This message is shown after 3 seconds"); 83 | }, 3000); 84 | ``` 85 | 86 | ## Video 87 | [https://www.youtube.com/watch?v=qtfi4-8dj9c](https://www.youtube.com/watch?v=qtfi4-8dj9c) 88 | -------------------------------------------------------------------------------- /3. asynchronous-javascript/5. project.md: -------------------------------------------------------------------------------- 1 | # IPL Project 2 | 3 | ## Best Practices: Imports 4 | 5 | When you import a module, always name the module the same as the file name or it's installed module name. That way it becomes easier to debug when the code becomes more complex. 6 | 7 | If you are using [destructuring](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment), this does not apply. 8 | 9 | Bad Usage: 10 | ```javascript 11 | const functions = require("./ipl"); 12 | 13 | functions.mostManOfTheMatch(); 14 | ``` 15 | 16 | Good Usage: 17 | ```javascript 18 | const ipl = require("./ipl"); 19 | 20 | ipl.mostManOfTheMatch(); 21 | ``` 22 | 23 | ## Best Practices: Semi-Colon Usage 24 | 25 | Javascript is not a very strict language. So it allows you to use semi-colons if you want. It also allows you to skip it if you want. However, it is always a good idea to stay consistent in that usage. 26 | 27 | So, 28 | 29 | If you are using `;`, use it everywhere. 30 | 31 | If you not are using `;`, do not use it everywhere. 32 | 33 | Bad Usage: 34 | ```javascript 35 | let factor = 2 36 | let numbers = [1, 2, 3, 4, 5, 6]; 37 | 38 | let computedNumbers = numbers.map((number) => { 39 | console.log(number); 40 | return (number * factor) 41 | }) 42 | ``` 43 | 44 | Good Usage: 45 | ```javascript 46 | let factor = 2; 47 | let numbers = [1, 2, 3, 4, 5, 6]; 48 | 49 | let computedNumbers = numbers.map((number) => { 50 | console.log(number); 51 | return (number * factor); 52 | }) 53 | ``` 54 | 55 | Alternative Good Usage: 56 | ```javascript 57 | let factor = 2 58 | let numbers = [1, 2, 3, 4, 5, 6] 59 | 60 | let computedNumbers = numbers.map((number) => { 61 | console.log(number) 62 | return (number * factor) 63 | }) 64 | ``` 65 | 66 | ## Best Practices: Objects and Arrays Readability 67 | 68 | In an object, ensure that every `key: value` pair is on a new line. This will increase the readability of your code. 69 | 70 | Bad: 71 | ```javascript 72 | const user = {name: "John Doe", age: 55, address: "Hello World Town"}; 73 | ``` 74 | 75 | Good: 76 | ```javascript 77 | const user = { 78 | name: "John Doe", 79 | age: 55, 80 | address: "Hello World Town" 81 | }; 82 | ``` 83 | 84 | Bad: 85 | ```javascript 86 | const users = [{name: "John Doe", age: 55, address: "Hello World Town"}, {name: "Jane Doe", age: 45, address: "Hello World Town"}, {name: "Jack Doe", age: 15, address: "Hello World Town"}]; 87 | ``` 88 | 89 | Bad: 90 | ```javascript 91 | const users = [ 92 | {name: "John Doe", age: 55, address: "Hello World Town"}, 93 | {name: "Jane Doe", age: 45, address: "Hello World Town"}, 94 | {name: "Jack Doe", age: 15, address: "Hello World Town"} 95 | ]; 96 | ``` 97 | 98 | Good: 99 | ```javascript 100 | const users = [ 101 | { 102 | name: "John Doe", 103 | age: 55, 104 | address: "Hello World Town" 105 | }, 106 | { 107 | name: "Jane Doe", 108 | age: 45, 109 | address: "Hello World Town" 110 | }, 111 | { 112 | name: "Jack Doe", 113 | age: 15, 114 | address: "Hello World Town" 115 | }, 116 | ]; 117 | ``` 118 | 119 | ## Best Practices: Comments 120 | 121 | Comments describe ***why*** certain code works the way it does and now what it does. 122 | 123 | For example, 124 | ```javascript 125 | // Convert the bowlers array of objects into a string 126 | const bowlersJSONData = JSON.stringify(bowlers);` 127 | ``` 128 | 129 | This is fairly obvious to anyone who is familiar with javascript and does not serve any purpose. Hence the comment should be removed. 130 | 131 | Similarly, comments that are there for your own understanding such as: 132 | ```javascript 133 | const fs = require("fs"); // Internal module 134 | const ipl = require("./ipl"); // Custom module 135 | const csvtojson = require("csvtojson"); // External module 136 | ``` 137 | 138 | serve no purpose to anyone else who reads your code and should be removed. *If you are having difficulty in remembering something about javascript, write it in a notebook for reference later and not in the code.* 139 | 140 | A good place to add a comment would be in a place like this: 141 | ```javascript 142 | const economicalBowlers = bowlers.sort((bowlerA, bowlerB) => { 143 | return bowlerA[1] - bowlerB[1]; 144 | }); 145 | ``` 146 | 147 | In this code, it is not obvious why we are referencing `[1]` in `bowlerA` and `bowlerB`. What value does it contain? ***It is not obvious.*** 148 | 149 | This is a good reason to write a descriptive comment such as: 150 | ```javascript 151 | const economicalBowlers = bowlers.sort((bowlerA, bowlerB) => { 152 | // [1] contains the economy of the bowler stored as a number 153 | return bowlerA[1] - bowlerB[1]; 154 | }); 155 | ``` 156 | 157 | So that anyone else who reads your code can use the comment to immediately understand *why* that code was written in that way. 158 | -------------------------------------------------------------------------------- /2. javascript/1. getting-started.md: -------------------------------------------------------------------------------- 1 | # Getting Started with NodeJS 2 | 3 | ### Node Version Manager (NVM) 4 | It is a tool used to manage multiple active Node.js versions. 5 | 6 | The Node.js platform, Node.js ​community of tools, and Node.js libraries are fast-moving targets – what might work under one Node.js version is not guaranteed to work for another version of Node.js. Hence, users need ways to switch between multiple versions of Node.js 7 | 8 | ### Why use NVM? 9 | NVM allows users to: 10 | 11 | - Locally download any of the remote Long Term Support (LTS) versions of Node.js with a simple command. 12 | - Easily switch between multiple versions of Node.js, right from the command line. 13 | - Set up aliases to switch between different downloaded versions of Node.js with ease. 14 | 15 | Learn more about nvm [here](https://github.com/nvm-sh/nvm). 16 | 17 | For Linux and Mac users only 18 | #### 1. Installing NVM 19 | Run the NVM installer using either of the following commands: 20 | 21 | ``` 22 | curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.35.3/install.sh | bash 23 | ``` 24 | or 25 | ``` 26 | wget -qO- https://raw.githubusercontent.com/nvm-sh/nvm/v0.35.3/install.sh | bash 27 | ``` 28 | #### 2. Verify Installation 29 | To verify that nvm has been installed, do: 30 | ``` 31 | command -v nvm 32 | ``` 33 | which should output `nvm` if the installation was successful. Please note that `which nvm` will not work, since nvm is a sourced shell function, not an executable binary. 34 | 35 | 36 | #### 3. Using NVM 37 | 38 | Once NVM is installed it allows users to install any version of Node.js through a simple command: 39 | 40 | ``` 41 | nvm install 42 | ``` 43 | **Recommended:** To install the latest LTS (Long Term Support) version of Node.js, use the following command: 44 | ``` 45 | nvm install --lts 46 | ``` 47 | To use any specific version of Node.js for your code, use the following command: 48 | 49 | ``` 50 | nvm use 51 | ``` 52 | 53 | ### What is Node.js? 54 | 55 | **Official Docs**: 56 | [https://nodejs.org/en/docs/](https://nodejs.org/en/docs/) 57 | 58 | Well in 1-line, Node.js® is a JavaScript runtime built on Chrome's V8 JavaScript engine. 59 | 60 | Huh? 61 | 62 | Historically, JavaScript could be executed only in a web browser. Things changed in 2009 when Node.js came into being. Using Node.js we can execute JavaScript outside the browser environment. 63 | 64 | Go through the videos below to understand more about how it works. 65 | [https://www.youtube.com/watch?v=uVwtVBpw7RQ](https://www.youtube.com/watch?v=uVwtVBpw7RQ) 66 | 67 | ### What is Node Package Manager (NPM) ? 68 | 69 | `npm`, short for Node Package Manager (well, not really), is two things: 70 | - it is an online repository for the publishing of open-source Node.js projects 71 | - and, it is a command-line utility for interacting with said repository that aids in package installation, version management, and dependency management. 72 | 73 | A majority of Node.js libraries and applications are published on npm, and many more are added every day. These applications can be searched for on [http://npmjs.org/](http://npmjs.org/). Once you have a package you want to install, it can be installed with a single CLI command. 74 | 75 | Let's say you're hard at work one day, developing the Next Great Application. You come across a problem, and you decide that it's time to use that cool library you keep hearing about - let's use Caolan McMahon's `async` as an example. Thankfully, npm is very simple to use: you only have to run `npm install async`, and the specified module will be installed in the current directory under `./node_modules/`. Once installed to your node_modules folder, you'll be able to use `require()` on them just like they were built-ins. 76 | 77 | Let's look at an example of a global install - let's say coffee-script. The npm command is simple: `npm install coffee-script -g`. This will typically install the program and put a symlink to it in `/usr/local/bin/`. This will then allow you to run the program from the console just like any other CLI tool. In this case, running coffee will now allow you to use the coffee-script REPL. 78 | 79 | Another important use of npm is dependency management. When you have a node project with a package.json file, you can run npm install from the project root and npm will install all the dependencies listed in the package.json. This makes installing a Node.js project from a git repo much easier! For example, `vows`, a Node.js testing framework, can be installed from git, and its single dependency, `eyes`, can be automatically handled: 80 | 81 | Example: 82 | ``` 83 | git clone https://github.com/cloudhead/vows.git 84 | cd vows 85 | 86 | npm install 87 | ``` 88 | After running those commands, you will see a node_modules folder containing all of the project dependencies specified in the package.json. 89 | 90 | NPM Crash Course - [https://www.youtube.com/watch?v=jHDhaSSKmB0](https://www.youtube.com/watch?v=jHDhaSSKmB0) 91 | 92 | ### Best Practices: Starting a Project 93 | 94 | Always have a .gitignore file and a README.md when starting a project. 95 | 96 | * Use relevant .gitignore templates from [https://github.com/github/gitignore](https://github.com/github/gitignore) 97 | * README.md file should have a brief project description and how to run, install and/or deploy the project. 98 | -------------------------------------------------------------------------------- /4. web-app-architecture/1. web-app-architecture.md: -------------------------------------------------------------------------------- 1 | # Web App Architecture 2 | 3 | ## 1. What is a Web App? 4 | 5 | A web application is a program that runs remotely and can be accessed through any web browser. It is a combination of client-side and server-side scripts that handle how data is stored, retrieved, and displayed to the user. 6 | 7 | People often confuse web applications and websites as being the same but actually, the two are quite different. 8 | 9 | A website focuses more on just displaying the content – usually the same content to all users. A web app, on the other hand, does more than just display the content; it also allows users to perform actions by interacting through web pages with the server. 10 | 11 | 12 | ![web app](./web-app.png "web app") 13 | 14 | ### Types of web applications 15 | The two main types of web applications are: 16 | 17 | - Dynamic: Require server-side processing to input your data and show you the relevant information. 18 | - Static: Do not require any server-side processing. 19 | 20 | ### Examples 21 | Some of the more popular examples of web applications include things like Google Docs, DropBox, and Spotify. 22 | 23 | ### 2. Web Server versus Application Server 24 | 25 | A **web server** accepts and fulfills requests from clients for static content (i.e., HTML pages, files, images, and videos) from a website. Web servers handle HTTP requests and responses only. 26 | 27 | An **application server** exposes business logic to the clients, which generates dynamic content. It is a software framework that transforms data to provide the specialized functionality offered by a business, service, or application. For example, application servers, like the Apache Tomcat, power the interactive parts of a website that can appear differently depending on the context of the request. 28 | 29 | The illustration below highlights the difference in their architecture: 30 | 31 | ![web server versus application server](./web-server-vs-application-server.png "web server versus application server") 32 | 33 | The columns below summarize the key differences between the two types of servers: 34 | 35 | | Web Server | Application Server | 36 | |---------------------------|-----------------------| 37 | | Deliver static content.| Delivers dynamic content.| 38 | |Content is delivered using the HTTP protocol only.| Provides business logic to application programs using several protocols (including HTTP).| 39 | |Serves only web-based applications.|Can serve web and enterprise-based applications.| 40 | |No support for multi-threading.| Uses multithreading to support multiple requests in parallel.| 41 | |Facilitates web traffic that is not very resource intensive.| Facilitates longer running processes that are very resource-intensive​.| 42 | 43 | ## 3. HTTP 44 | 45 | Read this article on Mozilla Developer Network. 46 | [https://developer.mozilla.org/en-US/docs/Web/HTTP/Overview](https://developer.mozilla.org/en-US/docs/Web/HTTP/Overview) 47 | 48 | ## 4. Choosing a HTTP Response Code 49 | 50 | 1. [Use this flowchart to decide what status code to use and when](https://www.codetinkerer.com/2015/12/04/choosing-an-http-status-code.html) 51 | 2. [Commonly used Response Codes with Discussion](https://www.bigbinary.com/conversation) 52 | 53 | ## 6. HTTP Drills I 54 | 55 | Go through the following link to learn the basics of the node `http` standard library. 56 | [https://flaviocopes.com/node-module-http/](https://flaviocopes.com/node-module-http/) 57 | 58 | Create a new project in Gitlab, the naming format is `-http-server`. Write a program which will start a static server, and which would satisfy the following requests: 59 | 60 | 61 | - **GET /html** - Should return the following HTML content. Note when opened in the browser it should display the HTML page and not the HTML code. 62 | ``` 63 | 64 | 65 | 66 | 67 | 68 |

Any fool can write code that a computer can understand. Good programmers write code that humans can understand.

69 |

- Martin Fowler

70 | 71 | 72 | 73 | ``` 74 | - **GET /json** - Should return the following JSON string 75 | ``` 76 | { 77 | "slideshow": { 78 | "author": "Yours Truly", 79 | "date": "date of publication", 80 | "slides": [ 81 | { 82 | "title": "Wake up to WonderWidgets!", 83 | "type": "all" 84 | }, 85 | { 86 | "items": [ 87 | "Why WonderWidgets are great", 88 | "Who buys WonderWidgets" 89 | ], 90 | "title": "Overview", 91 | "type": "all" 92 | } 93 | ], 94 | "title": "Sample Slide Show" 95 | } 96 | } 97 | ``` 98 | - **GET /uuid** - Should return a UUID4. For example: 99 | ``` 100 | { 101 | "uuid": "14d96bb1-5d53-472f-a96e-b3a1fa82addd" 102 | } 103 | ``` 104 | - **GET /status/{status_code}** - Should return a response with a status code as specified in the request. For example: 105 | - /status/100 - Return a response with 100 status code 106 | - /status/500 - Return a response with 500 status code 107 | 108 | Try it out for 100,200,300,400,500. 109 | 110 | - **GET /delay/{delay_in_seconds}** - Should return a success response but after the specified delay in the request. For example: If the request sent is GET /delay/3, then the server should wait for 3 seconds and only then send a response with 200 status code. 111 | -------------------------------------------------------------------------------- /6. html-css/html-css.md: -------------------------------------------------------------------------------- 1 | # HTML and CSS 2 | 3 | ## 1. Basics 4 | 5 | Start with [Learn to Code HTML and CSS by Shay Howe](https://learn.shayhowe.com/) 6 | 7 | In particular read the following sections and complete the exercises. 8 | 9 | HTMl & CSS 10 | 11 | * Lesson 1: Building your first web page 12 | * Lesson 2: Getting to know HTML 13 | * Lesson 3: Getting to know CSS 14 | * Lesson 4: Opening the Box Model 15 | * Lesson 5: Positioning content 16 | 17 | Advanced HTML & CSS 18 | 19 | * Lesson 3: Complex Selectors 20 | * Lesson 4: Responsive Web Design 21 | 22 | Resources for Web Development for any Topic: 23 | [Mozilla Web Docs](https://developer.mozilla.org/en-US/) 24 | 25 | CSS Reference: 26 | [A Visual Reference to CSS](https://cssreference.io/) 27 | 28 | ### Optional Resources 29 | 30 | Do any 1, Refer others 31 | 32 | [https://www.udacity.com/course/intro-to-html-and-css--ud001](https://www.udacity.com/course/intro-to-html-and-css--ud001) 33 | 34 | [https://dash.generalassemb.ly/](https://dash.generalassemb.ly/) 35 | 36 | [https://learn.shayhowe.com/](https://learn.shayhowe.com/) 37 | 38 | [https://marksheet.io/](https://marksheet.io/) 39 | 40 | [https://www.internetingishard.com/html-and-css/](https://www.internetingishard.com/html-and-css/) 41 | 42 | ## 2. CSS Selectors 43 | 44 | [https://www.educative.io/edpresso/what-are-css-selectors](https://www.educative.io/edpresso/what-are-css-selectors) 45 | 46 | [https://css-tricks.com/how-css-selectors-work/](https://css-tricks.com/how-css-selectors-work/) 47 | 48 | ## 3. Box Model 49 | 50 | [https://css-tricks.com/the-css-box-model/](https://css-tricks.com/the-css-box-model/) 51 | 52 | ## 4. Flexbox 53 | 54 | Resources: 55 | - [CSS Flex Video](https://www.youtube.com/watch?v=JJSoEo8JSnc) 56 | - [https://css-tricks.com/snippets/css/a-guide-to-flexbox/](https://css-tricks.com/snippets/css/a-guide-to-flexbox/) 57 | 58 | Play the games to practice: 59 | - [https://flexboxfroggy.com/](https://flexboxfroggy.com/) 60 | - [http://www.flexboxdefense.com/](http://www.flexboxdefense.com/) 61 | 62 | 63 | ## 5. Grid 64 | 65 | Resources: 66 | - [CSS Grid Video](https://www.youtube.com/watch?v=jV8B24rSN5o) 67 | 68 | Play the game to practice: 69 | - [CSS Grid Garden - Game](https://cssgridgarden.com/) 70 | 71 | ## 6. CSS Units 72 | 73 | - [https://css-tricks.com/the-lengths-of-css/](https://css-tricks.com/the-lengths-of-css/) 74 | - [https://css-tricks.com/building-resizeable-components-relative-css-units/](https://css-tricks.com/building-resizeable-components-relative-css-units/) 75 | 76 | ## 7. CSS Specificity 77 | 78 | ## 8. Layout Drills 79 | 80 | [https://gitlab.com/mountblue/js/css-layout-drills](https://gitlab.com/mountblue/js/css-layout-drills) 81 | 82 | Create a [codepen](https://codepen.io/) collection with solutions for all problems and submit the Codepen collection URL 83 | 84 | NOTE: Each problem can have multiple solutions. Also, ignore the `div` numbers, they have been used for illustrations only. 85 | 86 | ## 9. CSS Media Queries 87 | 88 | - [https://css-tricks.com/css-media-queries/](https://css-tricks.com/css-media-queries/) 89 | - [https://css-tricks.com/logic-in-media-queries/](https://css-tricks.com/logic-in-media-queries/) 90 | 91 | ## 10. Responsive Drills 92 | 93 | [https://gitlab.com/mountblue/js/responsive-layout-drill](https://gitlab.com/mountblue/js/responsive-layout-drill) 94 | 95 | Create a Codepen collection with solutions and submit the collection URL 96 | 97 | ## 11. Code Walkthrough of an Entire Project 98 | 99 | [https://www.youtube.com/watch?v=Wm6CUkswsNw](https://www.youtube.com/watch?v=Wm6CUkswsNw) 100 | 101 | ## 12. Project I: Green Tree Initiative 102 | 103 | * Project Adobe XD wireframes - [Wireframes](https://xd.adobe.com/spec/a75faa97-2d9f-401c-6140-8fac4a6601aa-d16e/grid/) 104 | * Project assets - [Assets](https://drive.google.com/drive/folders/1raP7YpOF4knQnX7UWOYJYoTU4KSGJAyy?usp=share_link) 105 | 106 | Build the two pages - home page and donation page. 107 | 108 | Get the layout and positioning right first before jumping into details. Link the pages among themselves for navigation. 109 | 110 | ### Hosting 111 | 112 | Host your website on Netlify. 113 | 114 | ### Some pointers: 115 | 116 | * Please work *mobile-first*. 117 | * Mostly use flexbox or grid. 118 | * Add README.md and .gitignore files to your repository. 119 | * Make a common styles.css. Include it on each HTML page. Put the style classes here. They can be gradually reused. 120 | * Structural CSS should be different for each page. 121 | * Work page by page, section by section, element by element. Break things down to the smallest step. Ask yourself what you don't know and figure it out. 122 | * Try to work with high energy and complete things. 123 | 124 | ### CSS Specific: 125 | 126 | * Always make the mobile resolution working first, then tablet, then webpage. 127 | * Separate out classes for structure and style. 128 | * Get the structure - layout and positioning right first before jumping into styling details. 129 | * Use structural CSS (like flex and grid) in a way to avoid too much responsive logic. 130 | * Link the pages among themselves for navigation. 131 | * Use Flexbox and Grid as much as possible. Minimise use of positioning - relative or absolute. 132 | * Use rem for font-size. Don't use em, px, vh or vw. 133 | * Understand "in-the-flow" and "out-of-flow". 134 | * Anything specific width, height, top, left, right, bottom, positioning: (absolute, fixed or float) can break the flow. Use when necessary e.g. overlapping elements. 135 | * Try to avoid using width as much as possible. Use percentages for sections inside containers. 136 | * Try to limit use of height wherever necessary. 137 | 138 | ### Submission 139 | 140 | This section requires you to submit the following URLs: 141 | 1. URL of your hosted webpages 142 | 2. URL of the GitLab repo of this project. 143 | 144 | ## 13. Technical Paper on HTML/CSS 145 | 146 | Write a technical paper. 147 | 148 | Concepts: 149 | 150 | * Box Model 151 | * Inline versus Block Elements. Examples. 152 | * Positioning: Relative/Absolute 153 | * Common CSS structural classes 154 | * Common CSS syling classes 155 | * CSS Specificity 156 | * CSS Responsive Queries 157 | * Flexbox/Grid 158 | * Common header meta tags 159 | * Any other topic you think is important. 160 | 161 | Add references at the end. 162 | 163 | ## 14. Optional Project I: Portfolio 164 | 165 | ### Goal 166 | 167 | Build your portfolio website using your knowledge of HTML and CSS. The display should work in all resolutions. 168 | 169 | Use your knowledge of responsive media queries, CSS flex, and CSS grid for handling multi-column layouts. 170 | 171 | ### Hosting 172 | 173 | Host your website on Netlify. 174 | 175 | ### Submission 176 | 177 | This section requires you to submit the following URLs ... 178 | 1. URL of your hosted webpages 179 | 2. URL of the GitLab repo of this project. 180 | 181 | ## 15. Optional Project II: Themed E-Commerce Website 182 | 183 | ### Goal 184 | 185 | Recreate the following website: https://shop.polymer-project.org/, but with a theme of your own. Example: a shoe store, clothing store, electronics store, etc. 186 | 187 | **NOTE:** This project is on HTML/CSS only, do not attempt to add functionality with JS. That part will come later. You should only use JS if it needed for widgets of frameworks like bootstrap. 188 | 189 | ### Project Description 190 | 191 | The website should have 5 pages: 192 | 193 | 1. Home Page 194 | 2. Item listing page 195 | 3. Single Item Page 196 | 4. Cart Page (hard code the items in the cart) 197 | 5. Checkout Page 198 | 199 | Some pointers: 200 | 201 | * Please work *mobile-first*. 202 | * Use of a CSS framework like Bootstrap is encouraged but not required. 203 | * Add README.md and .gitignore files to your repository. 204 | * Make a common styles.css. Include it on each HTML page. Put the style classes here. They can be gradually reused. 205 | * Work page by page, section by section, element by element. Break things down to the smallest step. Ask yourself what you don't know and figure it out. 206 | * Try to work with high energy and complete things. 207 | 208 | ### Hosting 209 | 210 | Host your website on Netlify. 211 | 212 | ### Submission 213 | 214 | This section requires you to submit the following URLs ... 215 | 1. URL of your hosted webpages 216 | 2. URL of the GitLab repo of this project. 217 | -------------------------------------------------------------------------------- /5. databases/1. databases.md: -------------------------------------------------------------------------------- 1 | # Databases 2 | 3 | ## 1. Introduction 4 | 5 | ### Types of Databases 6 | 7 | - Flat File Databases - [https://www.youtube.com/watch?v=vAA1VVExV5Q](https://www.youtube.com/watch?v=vAA1VVExV5Q) 8 | - What is a database - [https://www.youtube.com/watch?v=Tk1t3WKK-ZY](https://www.youtube.com/watch?v=Tk1t3WKK-ZY) 9 | 10 | ### Setting up Database in Local Machine 11 | 12 | Setting up MySQL 8 13 | 14 | [Installing on Ubuntu](https://linuxize.com/post/how-to-install-mysql-on-ubuntu-18-04/) 15 | 16 | [Installing on Mac](https://dev.mysql.com/doc/mysql-osx-excerpt/5.7/en/osx-installation-pkg.html) 17 | 18 | [Installing on Windows](https://www.liquidweb.com/kb/install-mysql-windows/) 19 | 20 | Optional : MySQL Workbench 21 | 22 | ## 2. Relational Databases & SQL 23 | 24 | Let's get started with the syntax of SQL and how to manipulate data in the database. You can start going through the SQL lessons in SQLBolt. 25 | 26 | Even if you are already familiar with SQL, we recommend that you go through the following lessons in SQLBolt - [https://sqlbolt.com/](https://sqlbolt.com/) 27 | 28 | - Fetching data with SELECT 29 | - Queries with constraints using WHERE 30 | - Filtering and sorting 31 | - JOINS 32 | - NULL values 33 | - Creating tables with CREATE 34 | - Adding data to a table with INSERT 35 | - Changing existing data in a table with UPDATE 36 | - Removing data from a table with DELETE 37 | 38 | ### NULL Values 39 | 40 | NULL values can be extremely tricky to deal with. Go through the following article to understand what they mean and how different queries affect NULL values. 41 | 42 | ### SQL Syntax Differences 43 | 44 | SQL, like most programming and scripting languages, has a standard definition for how it should work. 45 | 46 | From Wikipedia, 47 | > SQL became a standard of the American National Standards Institute (ANSI) in 1986 and of the International Organization for Standardization (ISO) in 1987. Since then the standard has been revised to include a larger set of features. Despite the existence of standards, most SQL code requires at least some changes before being ported to different database systems. 48 | 49 | The reason why there is a need to make certain changes to SQL code when moving between different relational database systems is that most vendor's database implementation is different. And with those differences also comes a different interpretation of the standards and how they should work. 50 | 51 | Another reason is that the SQL standard is vast and often covering just the mandatory standard features in a compliant way is difficult. 52 | 53 | Because of these differences, some relational database systems are known to be more standards compliant` than others. 54 | 55 | ### Comparison of RDBMS (Relational Database Management System) 56 | 57 | Because of the differences in standard compliance with different relational database system vendors, we need to understand what the most popular systems in use are, what their advantages and disadvantages are and when to use these systems. 58 | 59 | ### Database Design and Data Normalization 60 | 61 | [https://www.youtube.com/watch?v=tR_rOJPiEXc](https://www.youtube.com/watch?v=tR_rOJPiEXc) 62 | 63 | ### Database Design Drills 64 | 65 | Normalize Each Of The Following Tables 66 | 67 | For each task, create a separate `.sql` file with the create statements for the tables in a GitLab repository and submit the repo. 68 | 69 | **DO NOT SUBMIT mysqldump files**. You have to create the tables in the SQL files and submit them directly. 70 | 71 | #### Task 1: BRANCH 72 | 73 | - Branch# 74 | - Branch_Addr 75 | - ISBN 76 | - Title 77 | - Author 78 | - Publisher 79 | - Num_copies 80 | 81 | #### Task 2: CLIENT 82 | 83 | - Client# 84 | - Name 85 | - Location 86 | - Manager# 87 | - Manager_name 88 | - Manager_location 89 | - Contract# 90 | - Estimated_cost 91 | - Completion_date 92 | - Staff# 93 | - Staff_name 94 | - Staff_location 95 | 96 | #### Task 3: PATIENT 97 | 98 | - Patient# 99 | - Name 100 | - DOB 101 | - Address 102 | - Prescription# 103 | - Drug 104 | - Date 105 | - Dosage 106 | - Doctor 107 | - Secretary 108 | 109 | #### Task 4 :DOCTOR 110 | 111 | - Doctor# 112 | - DoctorName 113 | - Secretary 114 | - Patient# 115 | - PatientName 116 | - PatientDOB 117 | - PatientAddress 118 | - Prescription# 119 | - Drug 120 | - Date 121 | - Dosage 122 | 123 | ## 3. Using SQL with NodeJS 124 | 125 | ### Which npm package to choose to connect to the database server? 126 | 127 | We choose npm packages to use in our projects based on the following criteria: 128 | 129 | 1. `Weekly downloads` - The higher the number of downloads, the more we can rely on it since we know that more used packages will often have more solutions available when we search on google. 130 | 2. `Last publish` date - The sooner the better because it means that it is still in active development 131 | 3. `Documentation` - Good documentation will have a quick start guide, API documentation with parameters and return values as well as sample code. 132 | 133 | Along with this, for database packages we also take the following into consideration. Assuming we are using the MySQL 5.7 database for our project: 134 | 135 | 1. Is there an official package available? If so, then we can choose that package because we know that it will be supported and that the documentation will be good. 136 | 2. We should not choose a package that will only work with higher versions of our database server. For example, choosing a package that will only work with MySQL 8.0 will cause a lot of headaches. 137 | 3. We should not choose a package that will work with another database only. For example, choosing a package that only works with Postgresql will not work correctly when we are tying to work with MySQL. 138 | 4. If the package supports multiple database servers, make sure that it supports the database and the version of the database server we are going to be using. 139 | 5. If you want to write raw SQL queries, ensure that the library allows you to do that and is not primarily an ORM. 140 | 141 | ### ENV Variables and Connection Configuration 142 | 143 | An environment refers to the place where you run your project. Javascript often uses an environmental variable to differentiate what environment it is executing in. The name of the env variable that differentiates this is `NODE_ENV`. 144 | 145 | Common environments that you will be exposed to are as follows: 146 | 147 | * Development environment 148 | 149 | This usually refers to the machine on which you are writing code and building functionality for your projects. 150 | 151 | `NODE_ENV` usually refers to `development` or `dev` or `undefined` when working in this environment. 152 | 153 | * Production environment 154 | 155 | This usually refers to the machine or cloud virtual machine on which you deploy your project for users or customers to interact with and work on. 156 | 157 | `NODE_ENV` usually refers to `production` when working in this environment. 158 | 159 | Setting this value will often result in a lot of libraries and modules running optimizations on their code. These optimizations include things such as preventing all debug statements from executing, reducing the size of the build file, and so on. The purpose of these optimizations is to improve the speed of loading and execution of your code. 160 | 161 | * Staging environment 162 | 163 | This usually refers to the machine on which you deploy your project for internal testing of functionality to occur before the current set of changes is deployed to production. 164 | 165 | `NODE_ENV` usually refers to `staging` when working in this environment. 166 | 167 | Usually, there are no optimizations that occur when the value is set to this so that errors can be easily traced if they occur. 168 | 169 | * Testing environment 170 | 171 | This usually refers to the machine on which you run automated tests on your project to ensure that all your existing functionality still works and that the current set of changes has not broken anything. A good example of automated testing is the test cases that run on HackerRank when you complete a problem on that platform. 172 | 173 | `NODE_ENV` usually refers to `testing` when working in this environment. 174 | 175 | Often there are no optimizations that occur when the value is set to this so that errors can be easily traced if they occur. The testing environment can be run on your local machine before pushing to a git repository. It can also be setup in an automated testing environment via a CI/CD pipeline if it has been set up for the project. 176 | 177 | #### Setting Environmental Variables 178 | 179 | Learn how to set environmental variables by reading [this article](https://linuxize.com/post/how-to-set-and-list-environment-variables-in-linux/) 180 | 181 | #### How To Manage Configuration For Different Environments? 182 | 183 | Because we have different possible environments, we have to configure our code to connect to different database in each of these environments. 184 | 185 | The reason behind this is that we cannot expect our code on production to connect to the database that we have installed on our local machine. 186 | 187 | Similarly, when running tests, we would not want tests to run on live data from customers directly on production. 188 | 189 | In order to manage this difference in connection configuration for each of these environments, there are two ways we can go about doing it. 190 | 191 | In the first way, we can create a `config.js` file. We would then read the value of the database connection string directly from the env variable. 192 | 193 | Alternately, we could take the value of `NODE_ENV` into consideration and then use some logic to decide which database to connect to. The caveat here is that we **must never hard-code secrets** such as database passwords, etc into our `config.js` file. That is what env variables are for. 194 | 195 | However, we can hard-code fallback or default values such as a default port number to connect to since the database port number hardly ever changes or a default database name, etc. **But never hard-code secrets!** 196 | 197 | The second way to manage this would be to use a library to manage all of our configuration based on a `.env` file. This file would have different values on different environments so we would not have to worry about writing logic to handle different environments. 198 | 199 | You can learn how to do both of these methods by following the instructions mentioned in the article below. 200 | 201 | ## 4. Intermediate Topics 202 | 203 | - SQL Injection 204 | - Pools and pooling 205 | 206 | ## 5. ORM 207 | 208 | ### What is an ORM? 209 | 210 | [What is an ORM and Why You Should Use it](https://blog.bitsrc.io/what-is-an-orm-and-why-you-should-use-it-b2b6f75f5e2a) 211 | 212 | [Popular ORMs for NodeJS](https://www.dunebook.com/best-node-js-orms/) 213 | 214 | ### Advantages & Disadvantages of an ORM 215 | 216 | #### Advantages 217 | 218 | - Gives you a standard and consistent way to write SQL queries without worrying about code style. 219 | 220 | - Improves the speed of development. Your code also becomes easier to update, maintain, and reuse since you can write queries using native javascript objects. 221 | 222 | - Gives you the ability to protect your queries from SQL injection attacks. 223 | 224 | - You can write correct and optimized SQL code without worrying about the SQL language and how the queries have to be structured. 225 | 226 | - ORM Models follow the DRY principle which means that you only have to write your model once. It then becomes easier to update and maintain all your code because of this one module. 227 | 228 | - Most ORM Models use OOP, which means that you can extend and inherit from models and extend functionality easily. 229 | 230 | - Some ORMs let you switch between database vendors easily so porting between two different database systems becomes seamless. 231 | 232 | 233 | #### Disadvantages 234 | 235 | - ORMs have their own syntax so learning that takes time. 236 | 237 | - Small misconfigurations in how you use the ORM can lead to massive performance issues. 238 | 239 | - Performance is reasonable for commonly run and simpler queries. When you have to do things like performing joins on multiple tables, use derived tables, or run complex aggregations, it is better to do so with raw SQL queries. 240 | 241 | - Documentation for some ORMs is difficult to navigate even if they are the most commonly used libraries. 242 | 243 | ### Sequelize ORM 244 | 245 | [https://www.npmjs.com/package/sequelize](https://www.npmjs.com/package/sequelize) 246 | -------------------------------------------------------------------------------- /2. javascript/3. javascript-practice.md: -------------------------------------------------------------------------------- 1 | # Javascript Practice 2 | 3 | ## Best Practices 4 | 5 | ### 1. Case 6 | 7 | Read: [Case Styles: Camel, Pascal, Snake, and Kebab Case](https://betterprogramming.pub/string-case-styles-camel-pascal-snake-and-kebab-case-981407998841) 8 | 9 | Read: [What is camelCase, PascalCase, kebab-case and snake_case? 10 | ](https://winnercrespo.com/naming-conventions/) 11 | 12 | There is no accepted best practice on which case is the best to use. You may use any style you like to name your variables and functions, however it is important to remain **consistent in using that style**. Mixing styles is generally considered bad practice and must be avoided. 13 | 14 | Bad Inconsistent Style: 15 | ```javascript 16 | let name = "John"; 17 | let Age = 25; 18 | let is_married = false; 19 | let salaryDetails = { 20 | company_name: "MountBlue", 21 | CompanyAddress: "Bangalore", 22 | amount: 10000, 23 | }; 24 | 25 | function PrintDetails() { 26 | console.log(name, Age); 27 | console.log(salaryDetails); 28 | console.log(is_married ? "Married" : "Single"); 29 | } 30 | ``` 31 | 32 | 33 | Good Consistent style: 34 | ```javascript 35 | let name = "John"; 36 | let age = 25; 37 | let isMarried = false; 38 | let salaryDetails = { 39 | companyName: "MountBlue", 40 | companyAddress: "Bangalore", 41 | amount: 10000, 42 | }; 43 | 44 | function printDetails() { 45 | console.log(name, age); 46 | console.log(salaryDetails); 47 | console.log(isMarried ? "Married" : "Single"); 48 | } 49 | ``` 50 | 51 | Here `camelCase` has been used, but you may use whatever style you prefer `such_as_snake_case` or `PascalCase`, **as long as you remain consistent with your usage of that case**. 52 | 53 | Do not use `thISWayOFNaMiNg`. 54 | 55 | ### 2. Naming Loop Variables 56 | 57 | Keeping your variable names as descriptive as possible includes naming variables in loops as well. 58 | 59 | Bad Naming: 60 | ```javascript 61 | for(let i = 0; i < numbers.length; i++) { 62 | console.log(numbers[i]); 63 | } 64 | ``` 65 | 66 | Good naming: 67 | ```javascript 68 | for(let index = 0; index < numbers.length; index++) { 69 | console.log(numbers[index]); 70 | } 71 | ``` 72 | 73 | This applies to naming them when using higher order array methods as well: 74 | 75 | 76 | Bad Naming: 77 | ```javascript 78 | const squares = numbers.map((number, i) => { 79 | console.log(i); 80 | return number * number; 81 | }) 82 | ``` 83 | 84 | Good naming: 85 | ```javascript 86 | const squares = numbers.map((number, index) => { 87 | console.log(index); 88 | return number * number; 89 | }) 90 | ``` 91 | 92 | Similarly, when working with matrices: 93 | 94 | 95 | Bad Naming: 96 | ```javascript 97 | for(let i = 0; i < matrix.length; i++) { 98 | for(let j = 0; j < matrix[i].length; j++) { 99 | console.log(matrix[i][j]); 100 | } 101 | } 102 | ``` 103 | 104 | Good naming: 105 | ```javascript 106 | for(let rowIndex = 0; rowIndex < matrix.length; rowIndex++) { 107 | for(let columnIndex = 0; columnIndex < matrix[rowIndex].length; columnIndex++) { 108 | console.log(matrix[rowIndex][columnIndex]); 109 | } 110 | } 111 | ``` 112 | 113 | Though it is often better to be explicit with it as well: 114 | 115 | Explicit and good naming: 116 | ```javascript 117 | for(let rowIndex = 0; rowIndex < matrix.length; rowIndex++) { 118 | let row = matrix[rowIndex]; 119 | 120 | for(let columnIndex = 0; columnIndex < row.length; columnIndex++) { 121 | console.log(row[columnIndex]); 122 | } 123 | } 124 | ``` 125 | 126 | ### 3. Improving Readability 127 | 128 | Improving your code readability is key to making it easier to work with your code for yourself and for everyone who works with your code. 129 | 130 | An easy way to do that would be to add new lines between declaration and operations parts of your code. 131 | 132 | Poor Readability: 133 | ```javascript 134 | const fs = require("fs"); 135 | let numbers = [1,2,3,4,5]; 136 | let pi = 3.14; 137 | let squares = numbers.map(number => number * number); 138 | console.log(squares); 139 | ``` 140 | 141 | Good Readability 142 | ```javascript 143 | const fs = require("fs"); 144 | 145 | let numbers = [1,2,3,4,5]; 146 | let pi = 3.14; 147 | 148 | let squares = numbers.map(number => number * number); 149 | console.log(squares); 150 | ``` 151 | 152 | An example without declaration: 153 | 154 | Bad Readability: 155 | ```javascript 156 | function problem1(inventory, id){ 157 | if(!inventory || !id) return []; 158 | for(let cars of inventory){ 159 | if(cars.id===id){ 160 | return cars; 161 | } 162 | 163 | }return []; 164 | } 165 | 166 | module.exports=problem1; 167 | ``` 168 | 169 | Good Readability: 170 | ```javascript 171 | function problem1(inventory, id){ 172 | if(inventory == undefined || id == undefined) { 173 | return []; 174 | } else { 175 | for(let cars of inventory){ 176 | if(cars.id === id){ 177 | return cars; 178 | } 179 | } 180 | 181 | return []; 182 | } 183 | } 184 | 185 | module.exports = problem1; 186 | ``` 187 | 188 | ### 4. Starting NodeJS Projects 189 | 190 | Best Practices When Starting NodeJS Projects 191 | [https://www.youtube.com/watch?v=X_UQbPnvSx4](https://www.youtube.com/watch?v=X_UQbPnvSx4) 192 | 193 | ## JS Drill: Arrays 194 | 195 | ```js 196 | const items = [1, 2, 3, 4, 5, 5]; // use this array to test your code. 197 | /* 198 | Complete the following functions. 199 | These functions only need to work with arrays. 200 | A few of these functions mimic the behavior of the `Built` in JavaScript Array Methods. 201 | The idea here is to recreate the functions from scratch BUT if you'd like, 202 | feel free to Re-use any of your functions you build within your other functions. 203 | **DONT** Use for example. .forEach() to recreate each, and .map() to recreate map etc. 204 | You CAN use concat, push, pop, etc. but do not use the exact method that you are replicating 205 | 206 | Name your files like so: 207 | each.js 208 | testEach.js 209 | map.js 210 | testMap.js 211 | */ 212 | 213 | function each(elements, cb) { 214 | // Do NOT use forEach to complete this function. 215 | // Iterates over a list of elements, yielding each in turn to the `cb` function. 216 | // This only needs to work with arrays. 217 | // You should also pass the index into `cb` as the second argument 218 | // based off http://underscorejs.org/#each 219 | } 220 | 221 | function map(elements, cb) { 222 | // Do NOT use .map, to complete this function. 223 | // How map works: Map calls a provided callback function once for each element in an array, in order, and functionructs a new array from the res . 224 | // Produces a new array of values by mapping each value in list through a transformation function (iteratee). 225 | // Return the new array. 226 | } 227 | 228 | function reduce(elements, cb, startingValue) { 229 | // Do NOT use .reduce to complete this function. 230 | // How reduce works: A reduce function combines all elements into a single value going from left to right. 231 | // Elements will be passed one by one into `cb` along with the `startingValue`. 232 | // `startingValue` should be the first argument passed to `cb` and the array element should be the second argument. 233 | // `startingValue` is the starting value. If `startingValue` is undefined then make `elements[0]` the initial value. 234 | } 235 | 236 | function find(elements, cb) { 237 | // Do NOT use .includes, to complete this function. 238 | // Look through each value in `elements` and pass each element to `cb`. 239 | // If `cb` returns `true` then return that element. 240 | // Return `undefined` if no elements pass the truth test. 241 | } 242 | 243 | function filter(elements, cb) { 244 | // Do NOT use .filter, to complete this function. 245 | // Similar to `find` but you will return an array of all elements that passed the truth test 246 | // Return an empty array if no elements pass the truth test 247 | } 248 | 249 | const nestedArray = [1, [2], [[3]], [[[4]]]]; // use this to test 'flatten' 250 | 251 | function flatten(elements) { 252 | // Flattens a nested array (the nesting can be to any depth). 253 | // Hint: You can solve this using recursion. 254 | // Example: flatten([1, [2], [3, [[4]]]]); => [1, 2, 3, 4]; 255 | } 256 | ``` 257 | 258 | ## JS Drill: Objects 259 | 260 | ```js 261 | const testObject = { name: 'Bruce Wayne', age: 36, location: 'Gotham' }; // use this object to test your functions 262 | 263 | // Complete the following underscore functions. 264 | // Reference http://underscorejs.org/ for examples. 265 | // Check and use MDN as well 266 | 267 | /* 268 | Create a function for each problem in a file called 269 | keys.js 270 | values.js 271 | pairs.js 272 | and so on in the root of the project. 273 | 274 | Ensure that the functions in each file is exported and tested in its own file called 275 | testKeys.js 276 | testValues.js 277 | testPairs.js 278 | and so on in a folder called test. 279 | 280 | Create a new git repo on gitlab for this project, ensure that you commit after you complete each problem in the project. 281 | Ensure that the repo is a public repo. 282 | 283 | When you are done, send the gitlab url to your mentor 284 | */ 285 | 286 | function keys(obj) { 287 | // Retrieve all the names of the object's properties. 288 | // Return the keys as strings in an array. 289 | // Based on http://underscorejs.org/#keys 290 | } 291 | 292 | function values(obj) { 293 | // Return all of the values of the object's own properties. 294 | // Ignore functions 295 | // http://underscorejs.org/#values 296 | } 297 | 298 | function mapObject(obj, cb) { 299 | // Like map for arrays, but for objects. Transform the value of each property in turn by passing it to the callback function. 300 | // http://underscorejs.org/#mapObject 301 | } 302 | 303 | function pairs(obj) { 304 | // Convert an object into a list of [key, value] pairs. 305 | // http://underscorejs.org/#pairs 306 | } 307 | 308 | /* STRETCH PROBLEMS */ 309 | 310 | function invert(obj) { 311 | // Returns a copy of the object where the keys have become the values and the values the keys. 312 | // Assume that all of the object's values will be unique and string serializable. 313 | // http://underscorejs.org/#invert 314 | } 315 | 316 | function defaults(obj, defaultProps) { 317 | // Fill in undefined properties that match properties on the `defaultProps` parameter object. 318 | // Return `obj`. 319 | // http://underscorejs.org/#defaults 320 | } 321 | ``` 322 | 323 | ## Best Practices When Starting NodeJS Projects 324 | [Watch this video](https://www.youtube.com/watch?v=X_UQbPnvSx4) 325 | 326 | ## Choosing npm modules 327 | [Watch this video](https://www.youtube.com/watch?v=DuyxqG3L7A8) 328 | 329 | ## IPL Data Project I 330 | 331 | **Download the data from:** [https://www.kaggle.com/manasgarg/ipl](https://www.kaggle.com/manasgarg/ipl) 332 | 333 | There should be 2 files: 334 | - deliveries.csv 335 | - matches.csv 336 | 337 | In this data assignment you will transform raw data of IPL to calculate the following stats: 338 | 1. Number of matches played per year for all the years in IPL. 339 | 2. Number of matches won per team per year in IPL. 340 | 3. Extra runs conceded per team in the year 2016 341 | 4. Top 10 economical bowlers in the year 2015 342 | 5. Find the number of times each team won the toss and also won the match 343 | 6. Find a player who has won the highest number of *Player of the Match* awards for each season 344 | 7. Find the strike rate of a batsman for each season 345 | 8. Find the highest number of times one player has been dismissed by another player 346 | 9. Find the bowler with the best economy in super overs 347 | 348 | Implement the functions, **one for each task**. 349 | Use the results of the functions to dump JSON files in the output folder 350 | 351 | ### Instructions: 352 | - Create a new repo with name js-ipl-data-project in Gitlab subgroup, before starting implementation of the solution 353 | - Make sure to follow proper Git practices 354 | - Before submission, make sure that all the points in the below checklist are covered: 355 | - Git commits 356 | - Directory structure 357 | - package.json - dependencies, devDependencies 358 | - .gitignore file 359 | - Proper/Intuitive Variable names 360 | - Separate module for functions 361 | 362 | ### Directory structure: 363 | 364 | - src/ 365 | - server/ 366 | - 1-matches-per-year.js 367 | - 2-matches-won-per-team-per-year.js 368 | - public/ 369 | - output 370 | - matchesPerYear.json 371 | - ... 372 | - data/ 373 | - matches.csv 374 | - deliveries.csv 375 | - package.json 376 | - package-lock.json 377 | - .gitignore 378 | -------------------------------------------------------------------------------- /1. dev-basics/3. git.md: -------------------------------------------------------------------------------- 1 | # Git 2 | 3 | Git Crash Course - [https://www.youtube.com/watch?v=RGOj5yH7evk](https://www.youtube.com/watch?v=RGOj5yH7evk) 4 | 1 hour 8 minutes 30 seconds 5 | 6 | ## What is version control? 7 | 8 | Version control is a management system that allows you to record and track changes in your source code and files so that you can recall certain versions later. It’s like a Google Doc for programming, where you can collaborate with multiple people working on the same code and see the source code’s history. 9 | 10 | Ultimately, using a version control system allows teams to streamline their development process, which improves their overall efficiency. 11 | 12 | ### Why is it useful? 13 | **Tracking:** Say you are working on a web application, and one day, you find that your code changes have broken parts of the website. Instead of going through the trouble of finding the bug, you can revert your changes and see what lines of code are causing the problem. 14 | 15 | **Teamwork:** Without a version control system, it’s challenging to work on the same source code at once. By using something like Git, you can more easily merge changes, which makes it significantly easier to collaborate on projects. 16 | 17 | **Branches:** Say you are working on the footer and header of your website without using a version control system. You’ve finished the header, but not the footer, which means that the project isn’t ready to be public. With a version control system, you can create branches for different aspects of the project you are working on and merge them into​ the main source code when you are done. 18 | 19 | 20 | ### Why should I learn version control? 21 | Due to how useful version control is, it’s almost always a requirement for any developer or engineering job. As you become more accustomed to using a version control system, you will realize how powerful and easy it is to use. 22 | 23 | Popular version control systems: 24 | 25 | - Github 26 | - GitLab 27 | - Beanstalk 28 | - PerForce 29 | 30 | ## What is git? 31 | 32 | Git is a free, open-source distributed version control system. It keeps track of projects and files as they change over time with the help of different contributors. 33 | 34 | Version control is a system that records changes to a file, or set of files, over time so that you can recall specific versions later. 35 | 36 | Git helps keep track of changes made to a code. If at any point during coding you hit a fatal error and don’t know what’s causing it, Git allows you to revert back to a stable state. It also helps you see what changes have been made to the code over time. 37 | 38 | ### Repository 39 | A repository (commonly referred to as repo) is a collection of source code. A repository has commits to the project or a set of references to the commits (i.e., heads). 40 | 41 | ### Commits 42 | A commit logs a change or series of changes that you have made to a file in the repository. A commit has a unique SHA1 hash which is used to keep track of files changed in the past. A series of commits comprises the Git history. 43 | 44 | ### Branches 45 | A branch is essentially a unique set of code changes with a unique name. Each repository can have one or more branches. The main branch — the branch where all the changes eventually get merged into - is called the master. This is the official working version of your project and the one that you will see when you visit the project repository at github.com/yourname/projectname. 46 | 47 | ### Working directory, staging area, and local repo 48 | Every local repository has three different virtual zones. These are: 49 | 50 | - Working directory 51 | - Staging area 52 | - Commit area 53 | 54 | The working directory is where new files are created, old files are deleted, or where changes are made to already existing files. 55 | 56 | Once changes are made, they are added to the staging area. The staging area is also sometimes called the index. 57 | 58 | Once the changes are complete​, the staging area will contain one or more files that need to be committed. Creating a commit will cause Git to take the new code from the staging area and make the commit to the main repository​. This commit is then moved to the commit area. 59 | 60 | 61 | ## Create a Gitlab and Github Account 62 | 63 | ### Gitlab 64 | 65 | We will use Gitlab internally for our work. Create a Gitlab account using your **official** email address. 66 | 67 | ### Github 68 | 69 | GitHub is a website where millions of developers gather every day to collaborate on open-source software. It’s also the place that hosts billions of lines of code, and also a place where users of software go to report issues they might have. 70 | 71 | In short, it’s a platform for software developers, and it’s built around Git. 72 | 73 | As a developer, you can’t avoid using GitHub daily, either to host your code or to make use of other people’s code. This post explains you some key concepts of GitHub, and how to use some of its features that improve your workflow, and how to integrate other applications into your process. 74 | 75 | #### If you do not have a Github account, create one using your personal email address. 76 | 77 | ## How to install git? 78 | 79 | ### Check If Git is Installed 80 | First, you will want to check to see if you have Git command line tools installed on your computer. If you have been making repositories of your own code, then you likely have Git installed on your local machine. Some operating systems also come with Git installed, so it is worth checking before you install. 81 | 82 | You can check whether Git is installed and what version you are using by opening up a terminal window in Linux or Mac, or a command prompt window in Windows, and typing the following command: 83 | 84 | ``` 85 | git --version 86 | ``` 87 | However, if Git is not installed, you will receive an error similar to the following: 88 | 89 | ``` 90 | -bash: git: command not found 91 | 92 | 'git' is not recognized as an internal or external command, operable program or batch file. 93 | ``` 94 | In this case, you should install Git into your machine. Let’s go through installation for several of the major operating systems. 95 | 96 | ### Installing Git on Linux 97 | By far the easiest way of getting Git installed and ready to use is by using your version of Linux’s default repositories. Let’s go through how to install Git on your local Linux machine using this method. 98 | 99 | Installing Git on Ubuntu 18.04 or Debian 10 100 | You can use the apt package management tools to update your local package index. Afterwards, you can download and install the program: 101 | 102 | ``` 103 | sudo apt update 104 | sudo apt install git 105 | ``` 106 | 107 | For more information, read this 108 | 109 | [https://www.digitalocean.com/community/tutorials/how-to-contribute-to-open-source-getting-started-with-git](https://www.digitalocean.com/community/tutorials/how-to-contribute-to-open-source-getting-started-with-git) 110 | 111 | ## Setting up Git 112 | 113 | Now that you have Git installed, you need to do a few things so that the commit messages that will be generated for you will contain your correct information. 114 | 115 | The easiest way of doing this is through the git config command. Specifically, we need to provide our name and email address because Git embeds this information into each commit we do. We can go ahead and add this information by typing: 116 | ``` 117 | git config --global user.name "Your Name" 118 | git config --global user.email "youremail@domain.com" 119 | ``` 120 | We can see all of the configuration items that have been set by typing: 121 | 122 | ``` 123 | git config --list 124 | ``` 125 | #### git configuration file 126 | ``` 127 | user.name=Your Name 128 | user.email=youremail@domain.com 129 | ``` 130 | As you can see, this has a slightly different format. The information is stored in your Git configuration file, which you can optionally edit by hand with a text editor, like nano for example: 131 | ``` 132 | nano ~/.gitconfig 133 | ``` 134 | #### ~/.gitconfig contents 135 | ``` 136 | [user] 137 | name = Your Name 138 | email = youremail@domain.com 139 | ``` 140 | Once you’re done editing your file, you can exit nano by typing the `Ctrl` and `x` keys, and when prompted to save the file press `y`. 141 | 142 | There are many other options that you can set, but these are the two essential ones needed to prevent warnings in the future. 143 | 144 | ## Git Branches 145 | 146 | Video - 33 minutes 20 seconds - [https://www.youtube.com/watch?v=e2IbNHi4uCI](https://www.youtube.com/watch?v=e2IbNHi4uCI) 147 | 148 | ## Github 149 | 150 | Git and GitHub for Beginners - Crash Course - [https://www.youtube.com/watch?v=RGOj5yH7evk&t=176s](https://www.youtube.com/watch?v=RGOj5yH7evk&t=176s) 151 | 152 | ## Optional: Learn Enough git to be dangerous 153 | [Learn enough Git to be dangerous](https://www.learnenough.com/git-tutorial) 154 | 155 | ## Practice Link 156 | [Complete this game](https://learngitbranching.js.org/) at least 3 times. 157 | 158 | Main: 159 | * First 4 sections 160 | * Leave the advanced part 161 | 162 | Remote: 163 | * Both section 164 | 165 | ## Sample Review Questions 166 | 167 | * Initialize Git repository 168 | * Add a file a.txt 169 | * Make a commit. 170 | * Create a branch called leaf 171 | * Add a file b.txt 172 | * Create a second commit 173 | * Merge leaf into master 174 | 175 | Checking understanding: 176 | 177 | * What is staging area? 178 | * Where is the HEAD right now? 179 | 180 | ## Git Standard Practices 181 | 182 | ### 1. Using .gitignore 183 | 184 | [https://www.freecodecamp.org/news/gitignore-what-is-it-and-how-to-add-to-repo/](https://www.freecodecamp.org/news/gitignore-what-is-it-and-how-to-add-to-repo/) 185 | 186 | ### 2. Good Commit Messages 187 | 188 | [Git Commit Messages](https://chris.beams.io/posts/git-commit/) 189 | 190 | ### 3.Making Effective Commits on Git 191 | 192 | #### Small Commits 193 | 194 | Make small commits. Let's say you got a task. Instead of doing a 1 commit with 100 lines of code, make sure you break down your task into micro-tasks and then commit for each microtask. This creates your work history and at the same time makes it easier for you to go back to a point where you wrote code that works. 195 | 196 | For example, you wrote a function that is working. But you wanted to improve it further. So while improving you realized what you wrote, in the beginning, is actually better. Now in this case, if you don't have a commit history, you won't get the code you wrote in the beginning. 197 | 198 | #### Commit Often 199 | 200 | Keep committing after every micro-task, don't commit at the end of the day. You will lose a lot of work history. If you use Pomodoro, then make a habit of committing after every Pomodoro. 201 | 202 | #### Commit Working Code 203 | 204 | Make sure you always commit working code. Never commit something that breaks the codebase. What I mean by this is for example you wrote a function/method for your task that is not being used elsewhere you can commit it. Because it won't break the working application. Alternatively, let's say you are using a method 205 | of a service file in controller, committed controller code, and didn't commit service file code. In this case when the controller action is used the application throws an error, which means code breaks. 206 | 207 | Committing working code doesn't mean you have to commit a working feature. It just means whatever you are committing isn't breaking anything. 208 | 209 | #### Diff your code 210 | 211 | Before committing anything use your ide's diff tool or the integrated Git Version Control. Both VS Code and IntelliJ IDEA has their own diff tools. Make sure you don't commit debug logs, comments, or anything you wrote for your own convenience or testing changes. 212 | 213 | [Learn VS Code's Version Control](https://www.youtube.com/watch?v=AKNYgP0yEOY) 214 | 215 | [Learn IntelliJ's Version Control](https://www.youtube.com/watch?v=MaQnpCaiop0) 216 | 217 | [Diff in IntelliJ](https://www.jetbrains.com/help/idea/comparing-files-and-folders.html) 218 | 219 | #### Always Test your code 220 | 221 | You already know you need to commit working code. But how do you make sure about that? For this, once you make changes test your changes thoroughly. Apart from testing your own changes, make sure changes you made to code didn't break some other feature. The best way to do is to trace the usage of your changes in other places using simple find feature of your ide, and then test that feature changes as well. 222 | 223 | #### Avoid Committing passwords & secrets 224 | 225 | One common mistake beginner developers do is committing API Keys, secrets, and passwords in the repository. Never commit them, this will create a security breach and some hackers misuse them to exploit your server resources. Never ever commit passwords, API keys, Secrets, or Bcrypt salts in the codebase. 226 | 227 | ### 4. Undoing Changes 228 | 229 | #### What If You 230 | 231 | - committed the wrong message? 232 | - skipped file in the last commit? 233 | - accidentally committed on master? 234 | - accidentally committed to the wrong branch? 235 | - want to undo the last 5 commits? 236 | - want to undo changes to a file? 237 | 238 | Answers to all these questions are well explained in 239 | [this good resource](https://ohshitgit.com/). Please go through it and have it as a reference whenever you encounter such cases 240 | -------------------------------------------------------------------------------- /1. dev-basics/2. cli.md: -------------------------------------------------------------------------------- 1 | # Command Line Interface 2 | 3 | Computers understand the language of zeros and ones known as binary language. In the early days of computing, instructions were provided using binary language, which is difficult for all of us to read and write. Therefore, in an operating system, there is a special program called the shell. The shell accepts human-readable commands and translates them into something the kernel can read and process. 4 | 5 | ## What Is a Shell? 6 | 7 | - The shell is a user program or it is an environment provided for user interaction. 8 | - It is a command language interpreter that executes commands read from the standard input device such as a keyboard or from a file. 9 | - The shell gets started when you log in or open a console (terminal). 10 | - Quick and dirty way to execute utilities. 11 | - The shell is not part of the system kernel but uses the system kernel to execute programs, create files, etc. 12 | - Several shells are available for Linux including: 13 | - BASH ( Bourne-Again SHell ) - The most common shell in Linux. It's Open Source. 14 | - CSH (C SHell) - The C shell's syntax and usage are very similar to the C programming language. 15 | - KSH (Korn SHell) - Created by David Korn at AT & T Bell Labs. The Korn Shell also was the base for the POSIX Shell standard specifications. 16 | - TCSH - It is an enhanced but completely compatible version of the Berkeley UNIX C shell (CSH). 17 | 18 | Please note that each shell does the same job, but each understands different command syntax and provides different built-in functions. Under MS-DOS, the shell name is COMMAND.COM which is also used for the same purpose, but it is by far not as powerful as our Linux Shells are! 19 | 20 | ### Shell Prompt 21 | 22 | There are various ways to get shell access: 23 | 24 | - **Terminal** - Linux desktop provides a GUI based login system. Once logged in you can gain access to a shell by running X Terminal (XTerm), Gnome Terminal (GTerm), or KDE Terminal (KTerm) application. 25 | - **Connect via secure shell (SSH)** - You will get a shell prompt as soon as you log in into a remote server or workstation. 26 | - **Use the console** - A few Linux system also provides a text-based login system. Generally, you get a shell prompt as soon as you log in to the system. 27 | 28 | ### How do I find out my current shell name? 29 | 30 | To find all of the available shells in your system, type the following command: 31 | 32 | ``` 33 | cat /etc/shells 34 | ``` 35 | In case the */etc/shells* file has more than one shell listed under it, then it means that more than one shell is supported by your platform. 36 | 37 | ### Command Line Interface (CLI) 38 | 39 | The shell provides an interface to Linux where you can type or enter commands using the keyboard. It is known as the command-line interface (CLI). To find out your current shell-type following command. 40 | 41 | ``` 42 | echo $SHELL 43 | ps $$ 44 | ps -p $$ 45 | ``` 46 | The following sample output indicate that I am using bash shell: 47 | 48 | ``` 49 | PID TTY TIME CMD 50 | 13931 pts/4 00:00:00 bash 51 | ``` 52 | 53 | ## Unix Philosophy 54 | 55 | The Unix philosophy is a philosophical approach to developing software based on the experience of leading developers of the Unix operating system. The following philosophical approaches also apply to Linux operating systems. 56 | 57 | - *Do one thing and do it well* - Write programs that do one thing and do it well. Write programs to work together. Write programs to handle text streams, because that is a universal interface. 58 | - *Everything is file* - Ease of use and security is offered by treating hardware as a file. 59 | - *Small is beautiful.* 60 | - *Store data and configuration in flat text files* - Text file is a universal interface. Easy to create, backup, and move to another system. 61 | - *Use shell scripts to increase leverage and portability* - Use a shell script to automate common tasks across various UNIX / Linux installations. 62 | - *Chain programs together to complete complex task* - Use shell pipes and filters to chain small utilities that perform one task at a time. 63 | - *Choose portability over efficiency.* 64 | - *Keep it Simple, Stupid (KISS).* 65 | 66 | To know more, read this [Unix philosophy 67 | ](https://en.wikipedia.org/wiki/Unix_philosophy) 68 | 69 | 70 | ### Directory Structure and File Hierarchy 71 | 72 | If you’re coming from Windows, the Linux file system structure can seem particularly alien. The C:\ drive and drive letters are gone, replaced by a / and cryptic-sounding directories, most of which have three-letter names. 73 | 74 | The Filesystem Hierarchy Standard (FHS) defines the structure of file systems on Linux and other UNIX-like operating systems. However, Linux file systems also contain some directories that aren’t yet defined by the standard. 75 | 76 | ### / – The Root Directory 77 | Everything on your Linux system is located under the / directory, known as the root directory. You can think of the / directory as being similar to the C:\ directory on Windows – but this isn’t strictly true, as Linux doesn’t have drive letters. While another partition would be located at D:\ on Windows, this other partition would appear in another folder under / on Linux. 78 | 79 | ### /bin – Essential User Binaries 80 | 81 | The /bin directory contains the essential user binaries (programs) that must be present when the system is mounted in single-user mode. Applications such as Firefox are stored in /usr/bin, while important system programs and utilities such as the bash shell are located in /bin. The /usr directory may be stored on another partition – placing these files in the /bin directory ensures the system will have these important utilities even if no other file systems are mounted. The /sbin directory is similar – it contains essential system administration binaries. 82 | 83 | ### /etc – Configuration Files 84 | The /etc directory contains configuration files, which can generally be edited by hand in a text editor. Note that the /etc/ directory contains system-wide configuration files – user-specific configuration files are located in each user’s home directory. 85 | 86 | ### /home – Home Folders 87 | The /home directory contains a home folder for each user. For example, if your user name is bob, you have a home folder located at /home/bob. This home folder contains the user’s data files and user-specific configuration files. Each user only has to write access to their own home folder and must obtain elevated permissions (become the root user) to modify other files on the system. 88 | 89 | ### /opt – Optional Packages 90 | The /opt directory contains subdirectories for optional software packages. It’s commonly used by proprietary software that doesn’t obey the standard file system hierarchy – for example, a proprietary program might dump its files in /opt/application when you install it. 91 | 92 | 93 | ### /root – Root Home Directory 94 | The /root directory is the home directory of the root user. Instead of being located at /home/root, it’s located at /root. This is distinct from /, which is the system root directory. 95 | 96 | 97 | ### /sbin – System Administration Binaries 98 | The /sbin directory is similar to the /bin directory. It contains essential binaries that are generally intended to be run by the root user for system administration. 99 | 100 | ### /tmp – Temporary Files 101 | Applications store temporary files in the /tmp directory. These files are generally deleted whenever your system is restarted and may be deleted at any time by utilities such as tmpwatch. 102 | 103 | ### /usr – User Binaries & Read-Only Data 104 | The /usr directory contains applications and files used by users, as opposed to applications and files used by the system. For example, non-essential applications are located inside the /usr/bin directory instead of the /bin directory and non-essential system administration binaries are located in the /usr/sbin directory instead of the /sbin directory. Libraries for each are located inside the /usr/lib directory. The /usr directory also contains other directories – for example, architecture-independent files like graphics are located in /usr/share. 105 | 106 | The /usr/local directory is where locally compiled applications install to by default – this prevents them from mucking up the rest of the system. 107 | 108 | ### /var – Variable Data Files 109 | The /var directory is the writable counterpart to the /usr directory, which must be read-only in normal operation. Log files and everything else that would normally be written to /usr during normal operation are written to the /var directory. For example, you’ll find log files in /var/log. 110 | 111 | 112 | ## Command Line Basics Crash Course 113 | 114 | Video - [https://www.youtube.com/watch?v=cBokz0LTizk](https://www.youtube.com/watch?v=cBokz0LTizk) 115 | 116 | Given above is a quick super-fast course in using the command line. It is intended to be done rapidly in about a day, and not meant to teach you advanced shell usage. 117 | 118 | ## Practice Drill 1 119 | 120 | - Create the following directory structure. (Create empty files where necessary) 121 | ``` 122 | hello 123 | ├── five 124 | │ └── six 125 | │ ├── c.txt 126 | │ └── seven 127 | │ └── error.log 128 | └── one 129 | ├── a.txt 130 | ├── b.txt 131 | └── two 132 | ├── d.txt 133 | └── three 134 | ├── e.txt 135 | └── four 136 | └── access.log 137 | ``` 138 | - Delete all the files having the `.log` extension 139 | - Add the following content to `a.txt` 140 | ``` 141 | Unix is a family of multitasking, multiuser computer operating systems that derive from the original AT&T Unix, development starting in the 1970s at the Bell Labs research center by Ken Thompson, Dennis Ritchie, and others 142 | ``` 143 | - Delete the directory named `five` 144 | - Rename the `one` directory to `uno` 145 | - Move `a.txt` to the `two` directory 146 | 147 | ### Submission 148 | 149 | Copy and paste the command for each section into a text file with explanation. At the end the exercise upload this file. 150 | 151 | ## File Permissions 152 | 153 | Overview - [https://www.youtube.com/watch?v=D-VqgvBMV7g](https://www.youtube.com/watch?v=D-VqgvBMV7g) 154 | Binary to Decimal Conversion for File Permissions - [https://www.youtube.com/watch?v=BmVmJi5dR9c](https://www.youtube.com/watch?v=BmVmJi5dR9c) 155 | 156 | ## Pipes and Redirection 157 | 158 | Video 1 - [https://www.youtube.com/watch?v=Bzd7XfApxLI](https://www.youtube.com/watch?v=Bzd7XfApxLI) 159 | Video 2 - [https://www.youtube.com/watch?v=VgbnndezHbw](https://www.youtube.com/watch?v=VgbnndezHbw) 160 | 161 | ## Practice Drill 2 162 | 163 | ### Pipes 164 | 165 | 1. Download the contents of "Harry Potter and the Goblet of fire" using the command line from [here](https://raw.githubusercontent.com/bobdeng/owlreader/master/ERead/assets/books/Harry%20Potter%20and%20the%20Goblet%20of%20Fire.txt) 166 | 2. Print the first three lines in the book 167 | 3. Print the last 10 lines in the book 168 | 4. How many times do the following words occur in the book? 169 | * Harry 170 | * Ron 171 | * Hermione 172 | * Dumbledore 173 | 5. Print lines from 100 through 200 in the book 174 | 6. How many unique words are present in the book? 175 | 176 | ___________ 177 | 178 | ### Processes, ports 179 | 180 | 1. List your browser's process ids (pid) and parent process ids(ppid) 181 | 2. Stop the browser application from the command line 182 | 3. List the top 3 processes by CPU usage. 183 | 4. List the top 3 processes by memory usage. 184 | 5. Start a Python HTTP server on port 8000 185 | 6. Open another tab. Stop the process you started in the previous step 186 | 7. Start a Python HTTP server on port 90 187 | 8. Display all active connections and the corresponding TCP / UDP ports. 188 | 9. Find the pid of the process that is listening on port 5432 189 | 190 | ____________ 191 | 192 | ### Managing software 193 | 194 | Use `apt` (Ubuntu) or `homebrew` (Mac) to: 195 | 196 | 197 | 1. Install `htop`, `vim` and `nginx` 198 | 2. Uninstall `nginx` 199 | _____________ 200 | 201 | ## Misc 202 | 203 | 1. What's your local IP address? 204 | 2. Find the IP address of `google.com` 205 | 3. How to check if Internet is working using CLI? 206 | 4. Where is the `node` command located? What about `code`? 207 | 208 | ### Submission 209 | 210 | Copy and paste the command for each section into a text file with explanation. At the end the exercise upload this file. 211 | 212 | ## How Linux Works 213 | 214 | Go through the link here: [https://neilkakkar.com/unix.html](https://neilkakkar.com/unix.html) 215 | 216 | Philosophy: 217 | - Processes 218 | - Files 219 | 220 | Files and the File System: 221 | - iNodes 222 | - File Permissions 223 | - File Linking 224 | - File Structure 225 | 226 | Processes: 227 | - Attributes 228 | - Lifecycle 229 | - File redirection 230 | 231 | Layers in Unix: 232 | - The Kernel 233 | - Unix Utilities 234 | 235 | How the shell works: 236 | - The Pipe 237 | - Everything about PATHs 238 | - Writing Shell scripts 239 | 240 | Package Managers 241 | 242 | Brief History of Unix 243 | 244 | ## CLI Command (for Review): 245 | 246 | ### Bread and Butter Commands - all important: 247 | * man - Super Important 248 | * cd ( Understand flags - dot ., double dot .., tilda~, dash -) 249 | * mkdir 250 | * mv 251 | * cp with recursive flag 252 | * ls with different flags 253 | * pwd 254 | * rm 255 | * chmod - Super important 256 | * chown - Super important 257 | * sudo 258 | * apt 259 | * touch 260 | * cat 261 | * less 262 | * more 263 | * tail 264 | * rsync 265 | * grep 266 | * find - Super Important 267 | * sort 268 | * date 269 | * tree (needs to be installed additionally) 270 | * wc 271 | 272 | ### OS/Process Related Commands: 273 | * ps 274 | * top 275 | * df 276 | * uname 277 | * free 278 | * lspci 279 | * kill (with flags) 280 | 281 | ### Network Related Commands: 282 | * ping 283 | * ifconfig 284 | * ssh 285 | 286 | ### Bash Related Commands: 287 | * xargs 288 | * printenv 289 | * nano 290 | * awk 291 | * sed 292 | * Pipe operator | 293 | 294 | ## Actions that you should be able to perform: 295 | 296 | * Create/Read/Update/Delete/Move files and folders from command line 297 | * Check disk status 298 | * Check status of processes, able to extract process ids ( hint: use pipe operator to combine ps, xargs and awk) 299 | * Getting the most senior parent process 300 | * Change file permissions. Able to explain and manipulate the numerical file permissions. (chmod and chown) 301 | * Able to extract last x lines from files, get word count for a particular word, find a particular word. (basics of sed or awk would do) 302 | * Basics of sed and awk. 303 | * learn what is the difference between absolute and relative paths 304 | * Practice using absolute and relative paths 305 | * Learn how to use the find command 306 | * Learn ls with the 5 most commonly used flags used such as: 307 | -- View hidden files 308 | -- Sort by time 309 | -- Reverse sort 310 | -- Human readable file sizes 311 | -- Combining flags to get hidden files, sorted by time in reverse with human readable file sizes. 312 | * Find out what are terminal control codes such as Ctrl + D, Ctrl + C, Ctrl + Z etc and use them 313 | * Find out the difference between Ctrl + C and Ctrl + Z 314 | * Find out how to use Ctrl + R to reverse search 315 | * Find out how to use tab autocompletion 316 | * Find out how to use the arrow keys to navigate history 317 | 318 | ## Sample Review Questions: 319 | 320 | 1. Go into your home directory 321 | 2. Create a directory d1 322 | 3. Create a file a.txt inside it 323 | 4. Check permission of a.txt. What are the permissions in decimal format? 324 | 5. What are three elements in the permission? Do you understand conversion of decimal to binary? 325 | 6. Change the permissions of a.txt to 755? 326 | 7. Add a directory d2 327 | 8. Add b.txt inside d2 328 | 9. Change permissions of d2 (and everything inside) to 755 329 | 10. Start the Firefox browser. 330 | 11. List all processes in your computer 331 | 12. Find pid of Firefox Browser. Difference between parent process and child process. (hint: you need to learn pipes) 332 | 13. Kill the process (hint: pipes, awk, xargs, kill) 333 | 14. What is your user in Linux? 334 | 15. What is your group in Linux? 335 | 16. What is your computer architecture? (hint: uname command, learn the flags) 336 | 17. What is your audio driver? (hint: lspci, learn pipes and grep) 337 | 18. Go to home folder. Use find command to find all occurrences of "java" text anywhere in any filename or directory name in your system? 338 | 19. List everything in the home directory to get all files (including hidden), sorted by time in reverse with human readable file sizes. 339 | 20. Get last x lines for Harry Potter. Get word counts for particular words. 340 | 341 | ### Questions: 342 | 1. What is the difference between service and application? 343 | 2. What are these wildcards ~, ., .., * and ?? 344 | 3. What are the different flags for kill? Why do we use kill -9 in general? 345 | 4. Are you clear about file permissions? Explain them? chmod and chown commands? 346 | 5. Usage of Ctrl+R to search previously run commands, arrow keys, tab autocompletion. 347 | -------------------------------------------------------------------------------- /2. javascript/2. javascript-basics.md: -------------------------------------------------------------------------------- 1 | # JavaScript Basics 2 | 3 | ## 1. Introduction 4 | [CodeAcademy Tutorial](https://www.codecademy.com/learn/introduction-to-javascript) 5 | 6 | You can also watch a popular JavaScript basics crash course video on Youtube. 7 | 8 | ## 2. Modules 9 | 10 | [Read this article](https://www.freecodecamp.org/news/node-module-exports-explained-with-javascript-export-function-examples/) 11 | 12 | Video - [https://www.youtube.com/watch?v=hyYbs3SANRo](https://www.youtube.com/watch?v=hyYbs3SANRo) 13 | 14 | ## 3. Best Practices: Indentation 15 | 16 | Ensure that your code indentation is good. Submitting code that looks like the example given is unprofessional and makes it difficult to read for you as well as anyone who has to work with your code. 17 | 18 | Bad indentation: 19 | ```javascript 20 | function problem1(inventory,passid){ 21 | 22 | if(Array.isArray(inventory)){ 23 | 24 | return inventory;} 25 | 26 | else{ 27 | return []; 28 | } 29 | } 30 | 31 | module.exports=problem1; 32 | ``` 33 | 34 | 35 | Good indentation: 36 | ```javascript 37 | function problem1(inventory, passid) { 38 | if(Array.isArray(inventory) && passid<50) { 39 | return inventory; 40 | } else { 41 | return []; 42 | } 43 | } 44 | 45 | module.exports = problem1; 46 | ``` 47 | 48 | An easy way to indent your code is to press Ctrl + Shift + I in VSCode. 49 | 50 | If you are on a Mac, try Cmd + Shift + I 51 | 52 | ## 4. Best Practices: Variable Naming 53 | 54 | Ensure that your variable names are descriptive. Variables names looks like the examples below are unprofessional and makes it difficult to read for you as well as anyone who has to work with your code. 55 | 56 | Bad Naming: 57 | ```javascript 58 | const a = [1, 2, 3, 4, 5]; 59 | const a1 = [1, 4, 9, 16, 25]; 60 | ``` 61 | 62 | Good naming: 63 | ```javascript 64 | const numbers = [1, 2, 3, 4, 5]; 65 | const squares = [1, 4, 9, 16, 25]; 66 | ``` 67 | 68 | This also applies to functions 69 | 70 | 71 | Bad Naming: 72 | ```javascript 73 | const numbers = [1, 2, 3, 4, 5]; 74 | 75 | function calc(n) { 76 | return n * n; 77 | } 78 | 79 | const squares = numbers.map(calc); 80 | ``` 81 | 82 | Good naming: 83 | ```javascript 84 | const numbers = [1, 2, 3, 4, 5]; 85 | 86 | function squareNumber(number) { 87 | return number * number; 88 | } 89 | 90 | const squares = numbers.map(squareNumber); 91 | ``` 92 | 93 | Naming is tricky for every engineer. But that does not mean you don't do it. It means you think about what to name it **while** you are writing code, not after you have finished. 94 | 95 | ### 4. Best Practices: if else 96 | 97 | Keeping your code as readable as possible will ensure that you don't run into issues later on. One way to ensure this with `if else if` is to always use `{}` with the statements. 98 | 99 | Bad Usage: 100 | ```javascript 101 | let sum = 10; 102 | 103 | if(value %2 == 0) 104 | sum += value; 105 | else if(value == 0) 106 | sum += 1; 107 | else 108 | sum += -1; 109 | ``` 110 | 111 | Good usage: 112 | ```javascript 113 | let sum = 10; 114 | 115 | if(value %2 == 0) { 116 | sum += value; 117 | } else if(value == 0) { 118 | sum += 1; 119 | } else { 120 | sum += -1; 121 | } 122 | ``` 123 | 124 | This ensures that there is never any confusion about which code runs and when. 125 | 126 | It also ensures that there will be no chance of code not getting executed because it was placed on an adjacent line and is missed by the interpreter. 127 | 128 | ## 6. JS Drill: Cars 129 | 130 | To help us use arrays with real world problems we are going to simulate a used car dealer that has 50 cars in their inventory. 131 | The car dealer has all of their inventory housed in the array seen below. Scroll down past the data to find out how you can help the car dealer. 132 | 133 | PROJECT RESTRICTION: You can't use map, reduce, or filter to solve these problems. Only use native JavaScript for loops. No other types of loops are allowed. 134 | 135 | Example for loop: 136 | ----------------- 137 | ```js 138 | arr = [1,2,3,4]; 139 | for (i = 0; i < arr.length; i++) { 140 | arr[i]; // 1,2,3,4 141 | } 142 | ``` 143 | 144 | Create a function for each problem in a file called 145 | 146 | problem1.js 147 | problem2.js 148 | problem3.js 149 | and so on in the root of the project. 150 | 151 | Ensure that the functions in each file is exported and tested in its own file called 152 | 153 | testProblem1.js 154 | testProblem2.js 155 | testProblem3.js 156 | and so on in a folder called `test`. 157 | 158 | Each function must take at least one argument. The first argument must always be the inventory. 159 | 160 | Example: 161 | ```js 162 | const result = problem1(inventory); 163 | ``` 164 | 165 | If you want to pass more arguments, that is up to you. 166 | 167 | Create a new git repo on gitlab for this project, ensure that you commit after you complete each problem in the project. 168 | Ensure that the repo is a public repo. 169 | 170 | ```js 171 | 172 | let inventory = [{"id":1,"car_make":"Lincoln","car_model":"Navigator","car_year":2009}, 173 | {"id":2,"car_make":"Mazda","car_model":"Miata MX-5","car_year":2001}, 174 | {"id":3,"car_make":"Land Rover","car_model":"Defender Ice Edition","car_year":2010}, 175 | {"id":4,"car_make":"Honda","car_model":"Accord","car_year":1983}, 176 | {"id":5,"car_make":"Mitsubishi","car_model":"Galant","car_year":1990}, 177 | {"id":6,"car_make":"Audi","car_model":"riolet","car_year":1995}, 178 | {"id":7,"car_make":"Smart","car_model":"Fortwo","car_year":2009}, 179 | {"id":8,"car_make":"Audi","car_model":"4000CS Quattro","car_year":1987}, 180 | {"id":9,"car_make":"Ford","car_model":"Windstar","car_year":1996}, 181 | {"id":10,"car_make":"Mercedes-Benz","car_model":"E-Class","car_year":2000}, 182 | {"id":11,"car_make":"Infiniti","car_model":"G35","car_year":2004}, 183 | {"id":12,"car_make":"Lotus","car_model":"Esprit","car_year":2004}, 184 | {"id":13,"car_make":"Chevrolet","car_model":"Cavalier","car_year":1997}, 185 | {"id":14,"car_make":"Dodge","car_model":"Ram Van 1500","car_year":1999}, 186 | {"id":15,"car_make":"Dodge","car_model":"Intrepid","car_year":2000}, 187 | {"id":16,"car_make":"Mitsubishi","car_model":"Montero Sport","car_year":2001}, 188 | {"id":17,"car_make":"Buick","car_model":"Skylark","car_year":1987}, 189 | {"id":18,"car_make":"Geo","car_model":"Prizm","car_year":1995}, 190 | {"id":19,"car_make":"Oldsmobile","car_model":"Bravada","car_year":1994}, 191 | {"id":20,"car_make":"Mazda","car_model":"Familia","car_year":1985}, 192 | {"id":21,"car_make":"Chevrolet","car_model":"Express 1500","car_year":2003}, 193 | {"id":22,"car_make":"Jeep","car_model":"Wrangler","car_year":1997}, 194 | {"id":23,"car_make":"Eagle","car_model":"Talon","car_year":1992}, 195 | {"id":24,"car_make":"Toyota","car_model":"MR2","car_year":2003}, 196 | {"id":25,"car_make":"BMW","car_model":"525","car_year":2005}, 197 | {"id":26,"car_make":"Cadillac","car_model":"Escalade","car_year":2005}, 198 | {"id":27,"car_make":"Infiniti","car_model":"Q","car_year":2000}, 199 | {"id":28,"car_make":"Suzuki","car_model":"Aerio","car_year":2005}, 200 | {"id":29,"car_make":"Mercury","car_model":"Topaz","car_year":1993}, 201 | {"id":30,"car_make":"BMW","car_model":"6 Series","car_year":2010}, 202 | {"id":31,"car_make":"Pontiac","car_model":"GTO","car_year":1964}, 203 | {"id":32,"car_make":"Dodge","car_model":"Ram Van 3500","car_year":1999}, 204 | {"id":33,"car_make":"Jeep","car_model":"Wrangler","car_year":2011}, 205 | {"id":34,"car_make":"Ford","car_model":"Escort","car_year":1991}, 206 | {"id":35,"car_make":"Chrysler","car_model":"300M","car_year":2000}, 207 | {"id":36,"car_make":"Volvo","car_model":"XC70","car_year":2003}, 208 | {"id":37,"car_make":"Oldsmobile","car_model":"LSS","car_year":1997}, 209 | {"id":38,"car_make":"Toyota","car_model":"Camry","car_year":1992}, 210 | {"id":39,"car_make":"Ford","car_model":"Econoline E250","car_year":1998}, 211 | {"id":40,"car_make":"Lotus","car_model":"Evora","car_year":2012}, 212 | {"id":41,"car_make":"Ford","car_model":"Mustang","car_year":1965}, 213 | {"id":42,"car_make":"GMC","car_model":"Yukon","car_year":1996}, 214 | {"id":43,"car_make":"Mercedes-Benz","car_model":"R-Class","car_year":2009}, 215 | {"id":44,"car_make":"Audi","car_model":"Q7","car_year":2012}, 216 | {"id":45,"car_make":"Audi","car_model":"TT","car_year":2008}, 217 | {"id":46,"car_make":"Oldsmobile","car_model":"Ciera","car_year":1995}, 218 | {"id":47,"car_make":"Volkswagen","car_model":"Jetta","car_year":2007}, 219 | {"id":48,"car_make":"Dodge","car_model":"Magnum","car_year":2008}, 220 | {"id":49,"car_make":"Chrysler","car_model":"Sebring","car_year":1996}, 221 | {"id":50,"car_make":"Lincoln","car_model":"Town Car","car_year":1999}]; 222 | 223 | // ==== Problem #1 ==== 224 | // The dealer can't recall the information for a car with an id of 33 on his lot. Help the dealer find out which car has an id of 33 by calling a function that will return the data for that car. Then log the car's year, make, and model in the console log in the format of: 225 | "Car 33 is a *car year goes here* *car make goes here* *car model goes here*" 226 | 227 | // ==== Problem #2 ==== 228 | // The dealer needs the information on the last car in their inventory. Execute a function to find what the make and model of the last car in the inventory is? Log the make and model into the console in the format of: 229 | "Last car is a *car make goes here* *car model goes here*" 230 | 231 | // ==== Problem #3 ==== 232 | // The marketing team wants the car models listed alphabetically on the website. Execute a function to Sort all the car model names into alphabetical order and log the results in the console as it was returned. 233 | 234 | // ==== Problem #4 ==== 235 | // The accounting team needs all the years from every car on the lot. Execute a function that will return an array from the dealer data containing only the car years and log the result in the console as it was returned. 236 | 237 | // ==== Problem #5 ==== 238 | // The car lot manager needs to find out how many cars are older than the year 2000. Using the array you just obtained from the previous problem, find out how many cars were made before the year 2000 and return the array of older cars and log its length. 239 | 240 | // ==== Problem #6 ==== 241 | // A buyer is interested in seeing only BMW and Audi cars within the inventory. Execute a function and return an array that only contains BMW and Audi cars. Once you have the BMWAndAudi array, use JSON.stringify() to show the results of the array in the console. 242 | ``` 243 | 244 | ## 7. Higher Order Array Functions 245 | 246 | Watch the videos and then practice 247 | 248 | - [https://www.youtube.com/watch?v=zdp0zrpKzIE](https://www.youtube.com/watch?v=zdp0zrpKzIE) 249 | - [https://www.youtube.com/watch?v=rRgD1yVwIvE](https://www.youtube.com/watch?v=rRgD1yVwIvE) 250 | 251 | ## 8. Best Practices: Higher Order Functions 252 | 253 | When writing higher order functions, it is tempting to write all the functionality in one line of code. The problem with this approach is that it makes the code much harder to read and much harder to debug. 254 | 255 | To make your code better, always use arrow functions with a `{}` block. That way, it becomes more readable and it makes things easier to work with for yourself and for other people who will be working with your code. 256 | 257 | Bad Usage: 258 | ```javascript 259 | const arr = [1, 2, 3, 4, 5]; 260 | 261 | const numbers = arr.filter(number => number > 5).map(number => number * number).reduce((acc, number) => acc + number); 262 | ``` 263 | 264 | Bad Usage: 265 | ```javascript 266 | const arr = [1, 2, 3, 4, 5]; 267 | 268 | const numbers = arr.filter(number => number > 5) 269 | .map(number => number * number) 270 | .reduce((acc, number) => acc + number); 271 | ``` 272 | 273 | Good Usage: 274 | ```javascript 275 | const arr = [1, 2, 3, 4, 5]; 276 | 277 | const numbers = arr.filter((number) => { 278 | return number > 5; 279 | }) 280 | .map((number) => { 281 | return number * number; 282 | }) 283 | .reduce((acc, number) => { 284 | acc = acc + number; 285 | 286 | return acc; 287 | }) 288 | ``` 289 | 290 | Here it becomes much more clear where all the functionality is happening and it has become much easier to work with. Making changes also becomes much easier since we would anyway have to have added the `{}` block. 291 | 292 | This practice must also be followed when there is only 1 higher order function used. This will ensure that you do not fall into the bad practice of writing single line functions. 293 | 294 | Bad Usage: 295 | ```javascript 296 | const arr = [1, 2, 3, 4, 5]; 297 | 298 | const numbers = arr.filter(number => number > 5); 299 | ``` 300 | 301 | Good Usage: 302 | ```javascript 303 | const arr = [1, 2, 3, 4, 5]; 304 | 305 | const numbers = arr.filter((number) => { 306 | return number > 5; 307 | }); 308 | ``` 309 | 310 | ## 9. JS Drill: Cars 2 311 | 312 | To help us use arrays with real world problems we are going to simulate a used car dealer that has 50 cars in their inventory. 313 | The car dealer has all of their inventory housed in the array seen below. Scroll down past the data to find out how you can help the car dealer. 314 | 315 | PROJECT RESTRICTION: Use map, filter, reduce 316 | 317 | Create a function for each problem in a file called 318 | 319 | problem1.js 320 | problem2.js 321 | problem3.js 322 | and so on in the root of the project. 323 | 324 | Ensure that the functions in each file is exported and tested in its own file called 325 | 326 | testProblem1.js 327 | testProblem2.js 328 | testProblem3.js 329 | and so on in a folder called `test`. 330 | 331 | Each function must take at least one argument. The first argument must always be the inventory. 332 | 333 | Example: 334 | ```js 335 | const result = problem1(inventory); 336 | ``` 337 | 338 | If you want to pass more arguments, that is up to you. 339 | 340 | Create a new git repo on gitlab for this project, ensure that you commit after you complete each problem in the project. 341 | Ensure that the repo is a public repo. 342 | 343 | ```js 344 | 345 | let inventory = [{"id":1,"car_make":"Lincoln","car_model":"Navigator","car_year":2009}, 346 | {"id":2,"car_make":"Mazda","car_model":"Miata MX-5","car_year":2001}, 347 | {"id":3,"car_make":"Land Rover","car_model":"Defender Ice Edition","car_year":2010}, 348 | {"id":4,"car_make":"Honda","car_model":"Accord","car_year":1983}, 349 | {"id":5,"car_make":"Mitsubishi","car_model":"Galant","car_year":1990}, 350 | {"id":6,"car_make":"Audi","car_model":"riolet","car_year":1995}, 351 | {"id":7,"car_make":"Smart","car_model":"Fortwo","car_year":2009}, 352 | {"id":8,"car_make":"Audi","car_model":"4000CS Quattro","car_year":1987}, 353 | {"id":9,"car_make":"Ford","car_model":"Windstar","car_year":1996}, 354 | {"id":10,"car_make":"Mercedes-Benz","car_model":"E-Class","car_year":2000}, 355 | {"id":11,"car_make":"Infiniti","car_model":"G35","car_year":2004}, 356 | {"id":12,"car_make":"Lotus","car_model":"Esprit","car_year":2004}, 357 | {"id":13,"car_make":"Chevrolet","car_model":"Cavalier","car_year":1997}, 358 | {"id":14,"car_make":"Dodge","car_model":"Ram Van 1500","car_year":1999}, 359 | {"id":15,"car_make":"Dodge","car_model":"Intrepid","car_year":2000}, 360 | {"id":16,"car_make":"Mitsubishi","car_model":"Montero Sport","car_year":2001}, 361 | {"id":17,"car_make":"Buick","car_model":"Skylark","car_year":1987}, 362 | {"id":18,"car_make":"Geo","car_model":"Prizm","car_year":1995}, 363 | {"id":19,"car_make":"Oldsmobile","car_model":"Bravada","car_year":1994}, 364 | {"id":20,"car_make":"Mazda","car_model":"Familia","car_year":1985}, 365 | {"id":21,"car_make":"Chevrolet","car_model":"Express 1500","car_year":2003}, 366 | {"id":22,"car_make":"Jeep","car_model":"Wrangler","car_year":1997}, 367 | {"id":23,"car_make":"Eagle","car_model":"Talon","car_year":1992}, 368 | {"id":24,"car_make":"Toyota","car_model":"MR2","car_year":2003}, 369 | {"id":25,"car_make":"BMW","car_model":"525","car_year":2005}, 370 | {"id":26,"car_make":"Cadillac","car_model":"Escalade","car_year":2005}, 371 | {"id":27,"car_make":"Infiniti","car_model":"Q","car_year":2000}, 372 | {"id":28,"car_make":"Suzuki","car_model":"Aerio","car_year":2005}, 373 | {"id":29,"car_make":"Mercury","car_model":"Topaz","car_year":1993}, 374 | {"id":30,"car_make":"BMW","car_model":"6 Series","car_year":2010}, 375 | {"id":31,"car_make":"Pontiac","car_model":"GTO","car_year":1964}, 376 | {"id":32,"car_make":"Dodge","car_model":"Ram Van 3500","car_year":1999}, 377 | {"id":33,"car_make":"Jeep","car_model":"Wrangler","car_year":2011}, 378 | {"id":34,"car_make":"Ford","car_model":"Escort","car_year":1991}, 379 | {"id":35,"car_make":"Chrysler","car_model":"300M","car_year":2000}, 380 | {"id":36,"car_make":"Volvo","car_model":"XC70","car_year":2003}, 381 | {"id":37,"car_make":"Oldsmobile","car_model":"LSS","car_year":1997}, 382 | {"id":38,"car_make":"Toyota","car_model":"Camry","car_year":1992}, 383 | {"id":39,"car_make":"Ford","car_model":"Econoline E250","car_year":1998}, 384 | {"id":40,"car_make":"Lotus","car_model":"Evora","car_year":2012}, 385 | {"id":41,"car_make":"Ford","car_model":"Mustang","car_year":1965}, 386 | {"id":42,"car_make":"GMC","car_model":"Yukon","car_year":1996}, 387 | {"id":43,"car_make":"Mercedes-Benz","car_model":"R-Class","car_year":2009}, 388 | {"id":44,"car_make":"Audi","car_model":"Q7","car_year":2012}, 389 | {"id":45,"car_make":"Audi","car_model":"TT","car_year":2008}, 390 | {"id":46,"car_make":"Oldsmobile","car_model":"Ciera","car_year":1995}, 391 | {"id":47,"car_make":"Volkswagen","car_model":"Jetta","car_year":2007}, 392 | {"id":48,"car_make":"Dodge","car_model":"Magnum","car_year":2008}, 393 | {"id":49,"car_make":"Chrysler","car_model":"Sebring","car_year":1996}, 394 | {"id":50,"car_make":"Lincoln","car_model":"Town Car","car_year":1999}]; 395 | 396 | // ==== Problem #1 ==== 397 | // The dealer can't recall the information for a car with an id of 33 on his lot. Help the dealer find out which car has an id of 33 by calling a function that will return the data for that car. Then log the car's year, make, and model in the console log in the format of: 398 | "Car 33 is a *car year goes here* *car make goes here* *car model goes here*" 399 | 400 | // ==== Problem #2 ==== 401 | // The dealer needs the information on the last car in their inventory. Execute a function to find what the make and model of the last car in the inventory is? Log the make and model into the console in the format of: 402 | "Last car is a *car make goes here* *car model goes here*" 403 | 404 | // ==== Problem #3 ==== 405 | // The marketing team wants the car models listed alphabetically on the website. Execute a function to Sort all the car model names into alphabetical order and log the results in the console as it was returned. 406 | 407 | // ==== Problem #4 ==== 408 | // The accounting team needs all the years from every car on the lot. Execute a function that will return an array from the dealer data containing only the car years and log the result in the console as it was returned. 409 | 410 | // ==== Problem #5 ==== 411 | // The car lot manager needs to find out how many cars are older than the year 2000. Using the array you just obtained from the previous problem, find out how many cars were made before the year 2000 and return the array of older cars and log its length. 412 | 413 | // ==== Problem #6 ==== 414 | // A buyer is interested in seeing only BMW and Audi cars within the inventory. Execute a function and return an array that only contains BMW and Audi cars. Once you have the BMWAndAudi array, use JSON.stringify() to show the results of the array in the console. 415 | ``` 416 | 417 | ## 10. Scopes and Closures 418 | - [JavaScript Scope and Closures](https://css-tricks.com/javascript-scope-closures/) 419 | 420 | - [The Ultimate Guide to Hoisting, Scopes, and Closures in JavaScript](https://ui.dev/ultimate-guide-to-execution-contexts-hoisting-scopes-and-closures-in-javascript/) 421 | -------------------------------------------------------------------------------- /7. javascript-dom/1. dom.md: -------------------------------------------------------------------------------- 1 | # DOM 2 | 3 | ## 1. What is DOM? 4 | 5 | - Programming interface for HTML 6 | - A representation of HTML that can be accessed using Javascript 7 | 8 | #### How does it get created? 9 | 10 | - When a web page is loaded, the browser creates the DOM for that specific page 11 | - This allows for the creation of dynamic web pages where users can interact with the page 12 | 13 | #### DOM under the hood 14 | The structure of the DOM uses something called a tree, where the topmost node is the ***document*** object. 15 | 16 | ![dom](./dom.png "dom") 17 | 18 | #### Using the *document* object 19 | 20 | - the ***document*** object represents the web page that has been loaded 21 | - it acts as the “starting point” for access to the DOM. 22 | 23 | #### The things we can do with the ***document*** object 24 | - Finding Elements 25 | - Creating new elements 26 | - Updating elements 27 | - Changing properties of an elements 28 | - Listening to events like click, hover, etc 29 | 30 | ### Element Selection in DOM 31 | 32 | #### How to select elements in DOM 33 | 34 | To access the DOM, we make use of the document object. 35 | 36 | This object has properties and functions that we use to access our HTML elements which we can manipulate with JavaScript by using some available methods discussed below. 37 | 38 | #### Available Methods: 39 | - **getElementById:** 40 | 41 | **getElementById** accepts a string which is the name of an ***id*** in the DOM and it finds the first matching id. 42 | 43 | ``` 44 | document.getElementById("div1"); 45 | ``` 46 | We get back a special object called an **HTMLElement**. 47 | 48 | The exact kind of object we get back will depend on what we select (for instance, it will be an **HTMLDIVElement** if we refer to the above image) 49 | 50 | - **getElementsByTagName** 51 | 52 | **getElementsByTagName** accepts a string which is the ***HTML tags*** (like div, p, a, li, ul etc) in the DOM. 53 | 54 | It returns a list of all of the elements that match the string passed to the function 55 | ``` 56 | document.getElementByTagName("p"); 57 | ``` 58 | This function returns an **HTMLCollection** to us! 59 | 60 | It looks a lot like an array, and you can access it at a specific index or use a for loop 61 | 62 | However, you can not use common methods like ***push***, ***pop***, ***indexOf*** or ***includes*** 63 | 64 | - **getElementsByClassName** 65 | 66 | **getElementsByClassName** accepts a string which is the name of an element in the DOM. 67 | 68 | It returns a list of all of the elements that have a class attribute, which matches the string passed to the function 69 | 70 | ``` 71 | document.getElementsByClassName("p2"); 72 | ``` 73 | 74 | Just like *getElementsByTagName*, we get back a special kind of array called an HTMLCollection. 75 | 76 | Read more about [HTMLCollection](https://developer.mozilla.org/en-US/docs/Web/API/HTMLCollection) 77 | 78 | - **querySelector** 79 | 80 | **querySelector** accepts a string that is a valid CSS selector (I hope you remember them!!!). 81 | It returns the **first element** that matches the CSS selector passed to the function 82 | 83 | ```html 84 | document.querySelector("#div1"); 85 | 86 | document.querySelector("p.p2"); 87 | ``` 88 | 89 | Just like *getElementById*, this function returns a special HTMLElement object to us. 90 | 91 | 92 | 93 | 94 | - **querySelectorAll** 95 | 96 | 97 | **querySelectorAll** accepts a string that is a valid CSS selector. 98 | It returns **all the elements** that matches the CSS selector passed to the function. 99 | ``` 100 | document.querySelectorAll("div"); 101 | 102 | document.querySelectorAll("ul .nav-links"); 103 | ``` 104 | 105 | This function returns a **NodeList** to us! 106 | 107 | It looks a lot like an array, and you can access it at a specific index or use a for loop 108 | 109 | However, you can not use common methods like ***push***, ***pop***, ***indexOf*** or ***includes*** 110 | 111 | It’s almost identical to an HTMLCollection except it can include special kinds of nodes. 112 | 113 | Read more about [NodeList](https://developer.mozilla.org/en-US/docs/Web/API/NodeList) 114 | 115 | 116 | [Difference b/w NodeList & HTMLCollection](https://dev.to/jharteaga/difference-between-htmlcollection-and-nodelist-25bp) 117 | 118 | #### Crash Course 119 | 120 | Check out the below playlist. 121 | [https://www.youtube.com/watch?list=PLillGF-RfqbYE6Ik_EuXA2iZFcE082B3s&v=0ik6X4DJKCc](https://www.youtube.com/watch?list=PLillGF-RfqbYE6Ik_EuXA2iZFcE082B3s&v=0ik6X4DJKCc) 122 | 123 | ## 2. DOM Manipulation 124 | 125 | ### Modifying Elements in the DOM 126 | 127 | #### Accessing Text 128 | 129 | The easiest way to access the text of an element is to use ***innerText*** 130 | 131 | ```html 132 |
133 |
Hello World!
134 |
135 | ``` 136 | ```js 137 | const greeting = document.getElementById("greeting") 138 | 139 | console.log(greeting.innerText) // "Hello World!" 140 | ``` 141 | 142 | #### Modifying Text 143 | 144 | If you need to change any text, you can assign a new value to the innerHTML: 145 | ```js 146 | const greeting = document.getElementById("greeting") 147 | 148 | greeting.innerText = "It's changed !!!" 149 | ``` 150 | 151 | #### Using textContent 152 | 153 | Another common way to access and modify text is to use the ***textContent*** property 154 | ```js 155 | const greeting = document.getElementById("greeting") 156 | 157 | greeting.textContent = "It's changed !!!" 158 | ``` 159 |
160 | 161 | **So what’s the difference?** 162 | 163 | There are quite a few small differences: 164 | 165 | - innerText is aware of the rendered appearance of text, while textContent is not. 166 | - textContent gets the content of all elements, including ` 450 | 451 | 452 | ``` 453 | 454 | Take a look at some parent, child, and sibling element relationships. 455 | 456 | We will be focusing specifically on the `
` element. 457 | 458 | #### Accessing a parent element 459 | If you want to access the parent element of another element, you can use the ***parentElement*** method. 460 | ```js 461 | const foundDiv = document.querySelector("div") 462 | 463 | foundDiv.parentElement //
464 | ``` 465 | #### Accessing the children of an element 466 | If you want to access the child elements of another element, you can use the ****children**** method. 467 | ```js 468 | foundDiv.children //HTMLCollection(2) [p, ul] 469 | foundDiv.firstElementChild //

Here is a paragraph inside a div!

470 | foundDiv.lastElementChild //
    471 | ``` 472 | 473 | #### Accessing the siblings of an element 474 | If you want to access the previous sibling or next sibling element of another element, you can use the ***previousElementSibling*** or ***nextElementSibling*** method. 475 | ```js 476 | foundDiv.previousElementSibling //

    Here is a main heading!

    477 | foundDiv.nextElementSibling //
    Here is the second div!
    478 | ``` 479 | 480 | #### Text Nodes 481 | 482 | You may come across other methods for finding things in the DOM, we have shown you the most common ones, but as you learn more you may come across something called a ***text node*** 483 | 484 | More about [Text Node](https://stackoverflow.com/questions/17195868/what-is-a-text-node-its-uses-document-createtextnode) 485 | 486 | ### Nodes VS Elements 487 | - With some of these finder methods, you will see that you don’t always get back an HTML element, you sometimes get back what is called a text node 488 | - Everything in the DOM is a **node**, some nodes are not actually HTML elements, but text or even comments! 489 | - With most of the common traversal methods, you will not need to worry about text nodes 490 | - You will be using other methods less frequently, but know that they exist if you need to see elements near/above/below the element you find. 491 | 492 | Know more about [NodeTypes](https://developer.mozilla.org/en-US/docs/Web/API/Node/nodeType) 493 | 494 | Video - [https://www.youtube.com/watch?v=mPd2aJXCZ2g](https://www.youtube.com/watch?v=mPd2aJXCZ2g) 495 | 496 | ## 3. Javascript Events 497 | 498 | #### What is an event??? 499 | DOM events are “actions” that occur as a result of something the user or the browser does. 500 | 501 | We can use JavaScript to execute code when these kinds of “events” happen. 502 | 503 | #### What Kinds Of Events Do We Have??? 504 | - clicking on something 505 | - hovering over something with the mouse 506 | - pressing certain keys 507 | - when the DOM has loaded 508 | - when a form is submitted 509 | 510 | We write code that listens for events - and react accordingly! 511 | 512 | This is commonly called [Event Driven Programming](https://www.valentinog.com/blog/event/) 513 | 514 | #### How do we do it??? 515 | We have three options: 516 | 517 | - Attach the name of the function to the element in HTML 518 | - Attach the name of the function to an element in JavaScript 519 | - Use the addEventListener method 520 | 521 | **Attaching The Name Of The Function** 522 | ```html 523 |

    Hello World

    524 | ``` 525 | ```js 526 | function runClickHandler(){ 527 | console.log("You just clicked the h1 element!"; 528 | }) 529 | ``` 530 |
    531 | 532 | **Adding in Javascript** 533 | ```js 534 | const h1 = document.querySelector("h1"); 535 | 536 | h1.onclick = function(){ 537 | console.log("You just clicked the h1 element!"; 538 | } 539 | ``` 540 |
    541 | 542 | **Using addEventListener** 543 | ```js 544 | const h1 = document.querySelector("h1"); 545 | 546 | h1.addEventListener("click", function(){ 547 | console.log("You just clicked the h1 element!"; 548 | }) 549 | ``` 550 | 551 | #### Which One Should We Use??? 552 | We’re going to go with addEventListener - here’s why: 553 | 554 | - It gives us the most flexibility around our event listeners 555 | - It avoids writing any inline code in our HTML and keeps our HTML and JS separate 556 | - This is commonly called “Separation of Concerns” 557 | 558 | #### Important: Waiting For The Dom To Load!!! 559 | If you are trying to access properties in the DOM, before the web page has loaded - it won’t work! This becomes an issue if you put ` 625 | 626 | 627 | ``` 628 | ```js 629 | // listen for the keypress everywhere 630 | document.addEventListener("keypress", function(event) { 631 | if (event.key === "a") { 632 | alert("you just pressed the 'a' key!"); 633 | } 634 | }); 635 | ``` 636 | 637 | ### Adding Multiple Event Listeners 638 | It’s very common that you will want to add multiple event listeners on elements 639 | 640 | Let’s see an example: 641 | ```html 642 | 643 |

    See your friend list!

    644 |
      645 |
    • Thor
    • 646 |
    • Iron-man
    • 647 |
    • Captain America
    • 648 |
    649 | 650 | 651 | ``` 652 | ```js 653 | const buttons = document.querySelectorAll("button"); 654 | 655 | for (let button of buttons) { 656 | button.addEventListener("click", function(event) { 657 | event.target.parentElement.remove(); 658 | }); 659 | } 660 | ``` 661 | Everything seems to be working! 662 | 663 | **What happens when we want to add new elements?** 664 | ```html 665 | 666 |

    See your friend list!

    667 |
      ...
    668 |
    669 | 670 | 671 | 672 |
    673 | 674 | 675 | ``` 676 | ```js 677 | const form = document.querySelector("form"); 678 | const friendList = document.querySelector("#friend-list"); 679 | 680 | const buttons = document.querySelectorAll("li button"); 681 | 682 | for (let button of buttons) { 683 | button.addEventListener("click", function(event) { 684 | event.target.parentElement.remove(); 685 | }); 686 | } 687 | 688 | form.addEventListener("submit", function(event) { 689 | event.preventDefault(); 690 | const newFriendInput = document.querySelector("#first-name"); 691 | const newLi = document.createElement("li"); 692 | const newButton = document.createElement("button"); 693 | newLi.innerText = newFriendInput.value; 694 | newButton.innerText = "Remove"; 695 | 696 | newLi.append(newButton); 697 | friendList.append(newLi); 698 | form.reset(); 699 | }); 700 | ``` 701 |
    702 | 703 | **It doesn’t work!!!** 704 | 705 | The issue here is that our event listener only works for elements **currently** on the page 706 | 707 | There are two ways we can fix this: 708 | 709 | - Adding the event listener when we create elements 710 | - Event Delegation 711 | 712 | Let’s start with adding an event listener when we create 713 | 714 | **Adding the listener when we create** 715 | ```js 716 | const form = document.querySelector("form"); 717 | const friendList = document.querySelector("#friend-list"); 718 | 719 | form.addEventListener("submit", function(event) { 720 | event.preventDefault(); 721 | const newFriendInput = document.querySelector("#first-name"); 722 | const newLi = document.createElement("li"); 723 | const newButton = document.createElement("button"); 724 | newLi.innerText = newFriendInput.value; 725 | newButton.innerText = "Remove"; 726 | 727 | newButton.addEventListener("click", function(event) { 728 | event.target.parentElement.remove(); 729 | }); 730 | 731 | newLi.append(newButton); 732 | friendList.append(newLi); 733 | form.reset(); 734 | }); 735 | ``` 736 | This will work, but it’s not the most efficient approach 737 | 738 | We’re adding an event listener for every single button inside of each `
  • ` 739 | 740 | This means if we had 1,000,000 friends, we’d have 1,000,000 listeners! 741 | 742 | We can fix this using **event delegation** 743 | 744 | #### Event Delegation 745 | The idea behind event delegation is that we make a parent element the “delegate” 746 | 747 | In our case, the parent element is the `
      ` element 748 | 749 | We attach a single event listener on the parent or delegate element and then if the event happens inside a certain child element, we can access that child element using event.target 750 | 751 | **How to do better using event delegation** 752 | ```js 753 | friendList.addEventListener("click", function(event) { 754 | if (event.target.tagName === "BUTTON") { 755 | event.target.parentElement.remove(); 756 | } 757 | }); 758 | ``` 759 | Exact same behavior with only one event listener! 760 | 761 | #### Event Bubbling And Capturing 762 | The process of an event moving from the place it is clicked to its target is called **capturing** 763 | 764 | When an event happens on an element, it first runs the handlers on it, then on its parent, then all the way up on other ancestors. 765 | 766 | This is called **bubbling**. 767 | 768 | Read more on [Event Bubbling and Capturing](https://medium.com/@vsvaibhav2016/event-bubbling-and-event-capturing-in-javascript-6ff38bec30e) 769 | 770 | ### Removing Event Listeners 771 | Sometimes after you add an event listener, you will want to remove it. 772 | 773 | Some examples of this include: 774 | 775 | - A game is over and no more events should be registered 776 | - You can no longer drag and drop something into a part of the page 777 | - You do not want the user submitting any more information 778 | 779 |
      780 | 781 | **How it works** 782 | 783 | We can use the removeEventListener function to remove any event listeners 784 | 785 | This **can not** be called on multiple elements 786 | ```js 787 | let buttons = document.getElementsByTagName("button"); 788 | 789 | buttons.removeEventListener("click", function(){ 790 | alert("You just clicked a button"); 791 | }); 792 | ``` 793 | The code above will not work!!! 794 | 795 | Maybe we can just add it to an element individually like this: 796 | ```js 797 | for(let button of buttons){ 798 | button.removeEventListener("click", function(){ 799 | alert('You just clicked on a button!'); 800 | }); 801 | } 802 | ``` 803 | 804 | But this won’t work either!!! :P 805 | 806 | **Removing Event Listeners Correctly** 807 | 808 | removeEventListener needs a reference to the name of the function to remove 809 | ```js 810 | function alertData(){ 811 | alert("You just clicked a button"); 812 | } 813 | 814 | for(let button of buttons){ 815 | button.removeEventListener("click", alertData); 816 | } 817 | ``` 818 | **Note:** anonymous functions will not work here! 819 | 820 | ### Data attributes 821 | When creating elements and HTML pages, it’s very common that you might want to add some metadata or additional information about elements 822 | 823 | These are not things that the user should see, but accessible information in CSS and JavaScript 824 | 825 | Instead of placing this in ***id*** or ***class***, we can create custom attributes called **data attributes** 826 | 827 | These attributes start with data- and then anything you would like. You can read them easily in CSS and JavaScript 828 | 829 | **Example:** 830 | ```html 831 | 832 | 833 | 834 |
        835 |
      • Tesla 836 |
      • Honda 837 |
      • Ford 838 |
      • Toyota 839 |
      840 | 841 | 842 | 843 | ``` 844 | ```js 845 | const ul = document.querySelector("ul"); 846 | 847 | ul.addEventListener("click", function(event) { 848 | const selectedElement = event.target; 849 | console.log("see all data attributes", selectedElement.dataset); 850 | console.log( 851 | "see one data attribute", 852 | selectedElement.getAttribute("data-model") 853 | ); 854 | }); 855 | ``` 856 |
      857 | 858 | Read more about [Data attributes](https://css-tricks.com/a-complete-guide-to-data-attributes/) 859 | 860 | ## 4. Web Storage APIs 861 | 862 | The **Web Storage API** provides mechanisms by which browsers can store key/value pairs, in a much more intuitive fashion than using cookies. 863 | 864 | Video - [https://www.youtube.com/watch?v=MOd5cTJ6kaA](https://www.youtube.com/watch?v=MOd5cTJ6kaA) 865 | 866 | ### Introduction 867 | - [https://flaviocopes.com/web-platform/](https://flaviocopes.com/web-platform/) 868 | ### Web storage 869 | - [https://flaviocopes.com/web-storage-api/](https://flaviocopes.com/web-storage-api/) 870 | - [https://javascript.info/data-storage](https://javascript.info/data-storage) 871 | ### Cookies vs localStorage vs sessionStorage 872 | - [https://www.youtube.com/watch?v=AwicscsvGLg](https://www.youtube.com/watch?v=AwicscsvGLg) 873 | 874 | ## 5. Important Concepts to Understand 875 | - Why using alert and prompt is bad practice 876 | - Difference in Node and Elements in HTML - [https://stackoverflow.com/questions/9979172/difference-between-node-object-and-element-object](https://stackoverflow.com/questions/9979172/difference-between-node-object-and-element-object) 877 | - Event lifecycle in JS DOM (Bubbling and Capture) - [https://medium.com/prod-io/javascript-understanding-dom-event-life-cycle-49e1cf62b2ea](https://medium.com/prod-io/javascript-understanding-dom-event-life-cycle-49e1cf62b2ea) 878 | --------------------------------------------------------------------------------