diff --git a/1. dev-basics/1. development-setup.md b/1. dev-basics/1. development-setup.md new file mode 100644 index 0000000..111fb87 --- /dev/null +++ b/1. dev-basics/1. development-setup.md @@ -0,0 +1,43 @@ +# Development Setup + +## 1. Install Linux - preferably Ubuntu 20.04 or later + +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. + +### NOTE +- Macs are also acceptable as developer machines. +- Any flavour of Linux is acceptable. +- Windows is **NOT acceptable**. If you have Windows, install Ubuntu. + +### Reference +[https://github.com/mountblue/gearup/blob/master/dual_booting_ubuntu_windows.md](https://github.com/mountblue/gearup/blob/master/dual_booting_ubuntu_windows.md) + +## 2. Setup Visual Studio Code + +Follow the instructions to install Visual Studio Code from [this website](https://code.visualstudio.com/docs/setup/linux) + +### Plugins +Install the following VSCode plugins +1. Ruby / RoR +2. Markdown all in one + +## 3. Online tools + +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. + +1. Create a zoom account. Install Zoom on both your laptop and mobile. +2. Install Discord on both your laptop and mobile. +3. CREATE A NEW [gitlab account](https://gitlab.com/users/sign_up) using your mountblue.tech account. + +## 4. Install git + +The following command should be enough to install git. + +```bash +$ sudo apt install git +``` + +For mac use +```bash +$ brew install git +``` diff --git a/1. dev-basics/2. cli.md b/1. dev-basics/2. cli.md new file mode 100644 index 0000000..b96643f --- /dev/null +++ b/1. dev-basics/2. cli.md @@ -0,0 +1,346 @@ +# Command Line Interface + +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. + +## What Is a Shell? + +- The shell is a user program or it is an environment provided for user interaction. +- It is a command language interpreter that executes commands read from the standard input device such as a keyboard or from a file. +- The shell gets started when you log in or open a console (terminal). +- Quick and dirty way to execute utilities. +- The shell is not part of the system kernel but uses the system kernel to execute programs, create files, etc. +- Several shells are available for Linux including: +- BASH ( Bourne-Again SHell ) - The most common shell in Linux. It's Open Source. +- CSH (C SHell) - The C shell's syntax and usage are very similar to the C programming language. +- 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. +- TCSH - It is an enhanced but completely compatible version of the Berkeley UNIX C shell (CSH). + +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! + +### Shell Prompt + +There are various ways to get shell access: + +- **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. +- **Connect via secure shell (SSH)** - You will get a shell prompt as soon as you log in into a remote server or workstation. +- **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. + +### How do I find out my current shell name? + +To find all of the available shells in your system, type the following command: + +``` +cat /etc/shells +``` +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. + +### Command Line Interface (CLI) + +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. + +``` +echo $SHELL +ps $$ +ps -p $$ +``` +The following sample output indicate that I am using bash shell: + +``` +PID TTY TIME CMD +13931 pts/4 00:00:00 bash +``` + +## Unix Philosophy + +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. + +- *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. +- *Everything is file* - Ease of use and security is offered by treating hardware as a file. +- *Small is beautiful.* +- *Store data and configuration in flat text files* - Text file is a universal interface. Easy to create, backup, and move to another system. +- *Use shell scripts to increase leverage and portability* - Use a shell script to automate common tasks across various UNIX / Linux installations. +- *Chain programs together to complete complex task* - Use shell pipes and filters to chain small utilities that perform one task at a time. +- *Choose portability over efficiency.* +- *Keep it Simple, Stupid (KISS).* + +To know more, read this [Unix philosophy +](https://en.wikipedia.org/wiki/Unix_philosophy) + + +### Directory Structure and File Hierarchy + +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. + +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. + +### / – The Root Directory +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. + +### /bin – Essential User Binaries + +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. + +### /etc – Configuration Files +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. + +### /home – Home Folders +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. + +### /opt – Optional Packages +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. + + +### /root – Root Home Directory +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. + + +### /sbin – System Administration Binaries +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. + +### /tmp – Temporary Files +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. + +### /usr – User Binaries & Read-Only Data +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. + +The /usr/local directory is where locally compiled applications install to by default – this prevents them from mucking up the rest of the system. + +### /var – Variable Data Files +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. + + +## Command Line Basics Crash Course + +Video - [https://www.youtube.com/watch?v=cBokz0LTizk](https://www.youtube.com/watch?v=cBokz0LTizk) + +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. + +## Practice Drill 1 + +- Create the following directory structure. (Create empty files where necessary) +``` +hello +├── five +│ └── six +│ ├── c.txt +│ └── seven +│ └── error.log +└── one + ├── a.txt + ├── b.txt + └── two + ├── d.txt + └── three + ├── e.txt + └── four + └── access.log +``` +- Delete all the files having the `.log` extension +- Add the following content to `a.txt` +``` +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 +``` +- Delete the directory named `five` +- Rename the `one` directory to `uno` +- Move `a.txt` to the `two` directory + +### Submission + +Copy and paste the command for each section into a text file with explanation. At the end the exercise upload this file. + +## File Permissions + +Overview - [https://www.youtube.com/watch?v=D-VqgvBMV7g](https://www.youtube.com/watch?v=D-VqgvBMV7g) +Binary to Decimal Conversion for File Permissions - [https://www.youtube.com/watch?v=BmVmJi5dR9c](https://www.youtube.com/watch?v=BmVmJi5dR9c) + +## Pipes and Redirection + +Video 1 - [https://www.youtube.com/watch?v=Bzd7XfApxLI](https://www.youtube.com/watch?v=Bzd7XfApxLI) +Video 2 - [https://www.youtube.com/watch?v=VgbnndezHbw](https://www.youtube.com/watch?v=VgbnndezHbw) + +## Practice Drill 2 + +### Pipes + +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) +2. Print the first three lines in the book +3. Print the last 10 lines in the book +4. How many times do the following words occur in the book? + * Harry + * Ron + * Hermione + * Dumbledore +5. Print lines from 100 through 200 in the book +6. How many unique words are present in the book? + +___________ + +### Processes, ports + +1. List your browser's process ids (pid) and parent process ids(ppid) +2. Stop the browser application from the command line +3. List the top 3 processes by CPU usage. +4. List the top 3 processes by memory usage. +5. Start a Python HTTP server on port 8000 +6. Open another tab. Stop the process you started in the previous step +7. Start a Python HTTP server on port 90 +8. Display all active connections and the corresponding TCP / UDP ports. +9. Find the pid of the process that is listening on port 5432 + +____________ + +### Managing software + +Use `apt` (Ubuntu) or `homebrew` (Mac) to: + + +1. Install `htop`, `vim` and `nginx` +2. Uninstall `nginx` +_____________ + +## Misc + +1. What's your local IP address? +2. Find the IP address of `google.com` +3. How to check if Internet is working using CLI? +4. Where is the `node` command located? What about `code`? + +### Submission + +Copy and paste the command for each section into a text file with explanation. At the end the exercise upload this file. + +## How Linux Works + +Go through the link here: [https://neilkakkar.com/unix.html](https://neilkakkar.com/unix.html) + +Philosophy: +- Processes +- Files + +Files and the File System: +- iNodes +- File Permissions +- File Linking +- File Structure + +Processes: +- Attributes +- Lifecycle +- File redirection + +Layers in Unix: +- The Kernel +- Unix Utilities + +How the shell works: +- The Pipe +- Everything about PATHs +- Writing Shell scripts + +Package Managers + +Brief History of Unix + +## CLI Command (for Review): + +### Bread and Butter Commands - all important: +* man - Super Important +* cd ( Understand flags - dot ., double dot .., tilda~, dash -) +* mkdir +* mv +* cp with recursive flag +* ls with different flags +* pwd +* rm +* chmod - Super important +* chown - Super important +* sudo +* apt +* touch +* cat +* less +* more +* tail +* rsync +* grep +* find - Super Important +* sort +* date +* tree (needs to be installed additionally) +* wc + +### OS/Process Related Commands: +* ps +* top +* df +* uname +* free +* lspci +* kill (with flags) + +### Network Related Commands: +* ping +* ifconfig +* ssh + +### Bash Related Commands: +* xargs +* printenv +* nano +* awk +* sed +* Pipe operator | + +## Actions that you should be able to perform: + +* Create/Read/Update/Delete/Move files and folders from command line +* Check disk status +* Check status of processes, able to extract process ids ( hint: use pipe operator to combine ps, xargs and awk) +* Getting the most senior parent process +* Change file permissions. Able to explain and manipulate the numerical file permissions. (chmod and chown) +* 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) +* Basics of sed and awk. +* learn what is the difference between absolute and relative paths +* Practice using absolute and relative paths +* Learn how to use the find command +* Learn ls with the 5 most commonly used flags used such as: + -- View hidden files + -- Sort by time + -- Reverse sort + -- Human readable file sizes + -- Combining flags to get hidden files, sorted by time in reverse with human readable file sizes. +* Find out what are terminal control codes such as Ctrl + D, Ctrl + C, Ctrl + Z etc and use them +* Find out the difference between Ctrl + C and Ctrl + Z +* Find out how to use Ctrl + R to reverse search +* Find out how to use tab autocompletion +* Find out how to use the arrow keys to navigate history + +## Sample Review Questions: + +1. Go into your home directory +2. Create a directory d1 +3. Create a file a.txt inside it +4. Check permission of a.txt. What are the permissions in decimal format? +5. What are three elements in the permission? Do you understand conversion of decimal to binary? +6. Change the permissions of a.txt to 755? +7. Add a directory d2 +8. Add b.txt inside d2 +9. Change permissions of d2 (and everything inside) to 755 +10. Start the Firefox browser. +11. List all processes in your computer +12. Find pid of Firefox Browser. Difference between parent process and child process. (hint: you need to learn pipes) +13. Kill the process (hint: pipes, awk, xargs, kill) +14. What is your user in Linux? +15. What is your group in Linux? +16. What is your computer architecture? (hint: uname command, learn the flags) +17. What is your audio driver? (hint: lspci, learn pipes and grep) +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? +19. List everything in the home directory to get all files (including hidden), sorted by time in reverse with human readable file sizes. +20. Get last x lines for Harry Potter. Get word counts for particular words. + +### Questions: +1. What is the difference between service and application? +2. What are these wildcards ~, ., .., * and ?? +3. What are the different flags for kill? Why do we use kill -9 in general? +4. Are you clear about file permissions? Explain them? chmod and chown commands? +5. Usage of Ctrl+R to search previously run commands, arrow keys, tab autocompletion. diff --git a/1. dev-basics/3. git.md b/1. dev-basics/3. git.md new file mode 100644 index 0000000..6060e18 --- /dev/null +++ b/1. dev-basics/3. git.md @@ -0,0 +1,239 @@ +# Git + +Git Crash Course - [https://www.youtube.com/watch?v=RGOj5yH7evk](https://www.youtube.com/watch?v=RGOj5yH7evk) +1 hour 8 minutes 30 seconds + +## What is version control? + +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. + +Ultimately, using a version control system allows teams to streamline their development process, which improves their overall efficiency. + +### Why is it useful? +**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. + +**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. + +**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. + + +### Why should I learn version control? +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. + +Popular version control systems: + +- Github +- GitLab +- Beanstalk +- PerForce + +## What is git? + +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. + +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. + +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. + +### Repository +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). + +### Commits +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. + +### Branches +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. + +### Working directory, staging area, and local repo +Every local repository has three different virtual zones. These are: + +- Working directory +- Staging area +- Commit area + +The working directory is where new files are created, old files are deleted, or where changes are made to already existing files. + +Once changes are made, they are added to the staging area. The staging area is also sometimes called the index. + +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. + + +## Create a Gitlab and Github Account + +### Gitlab + +We will use Gitlab internally for our work. Create a Gitlab account using your **official** email address. + +### Github + +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. + +In short, it’s a platform for software developers, and it’s built around Git. + +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. + +#### If you do not have a Github account, create one using your personal email address. + +## How to install git? + +### Check If Git is Installed +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. + +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: + +``` +git --version +``` +However, if Git is not installed, you will receive an error similar to the following: + +``` +-bash: git: command not found + +'git' is not recognized as an internal or external command, operable program or batch file. +``` +In this case, you should install Git into your machine. Let’s go through installation for several of the major operating systems. + +### Installing Git on Linux +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. + +Installing Git on Ubuntu 18.04 or Debian 10 +You can use the apt package management tools to update your local package index. Afterwards, you can download and install the program: + +``` +sudo apt update +sudo apt install git +``` + +For more information, read this + +[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) + +## Setting up Git + +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. + +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: +``` +git config --global user.name "Your Name" +git config --global user.email "youremail@domain.com" +``` +We can see all of the configuration items that have been set by typing: + +``` +git config --list +``` +#### git configuration file +``` +user.name=Your Name +user.email=youremail@domain.com +``` +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: +``` +nano ~/.gitconfig +``` +#### ~/.gitconfig contents +``` +[user] + name = Your Name + email = youremail@domain.com +``` +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`. + +There are many other options that you can set, but these are the two essential ones needed to prevent warnings in the future. + +## Git Branches + +Video - 33 minutes 20 seconds - [https://www.youtube.com/watch?v=e2IbNHi4uCI](https://www.youtube.com/watch?v=e2IbNHi4uCI) + +## Github + +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) + +## Optional: Learn Enough git to be dangerous +[Learn enough Git to be dangerous](https://www.learnenough.com/git-tutorial) + +## Practice Link +[Complete this game](https://learngitbranching.js.org/) at least 3 times. + +Main: +* First 4 sections +* Leave the advanced part + +Remote: +* Both section + +## Sample Review Questions + +* Initialize Git repository +* Add a file a.txt +* Make a commit. +* Create a branch called leaf +* Add a file b.txt +* Create a second commit +* Merge leaf into master + +Checking understanding: + +* What is staging area? +* Where is the HEAD right now? + +## Git Standard Practices + +### 1. Using .gitignore + +[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/) + +### 2. Good Commit Messages + +[Git Commit Messages](https://chris.beams.io/posts/git-commit/) + +### 3.Making Effective Commits on Git + +#### Small Commits + +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. + +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. + +#### Commit Often + +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. + +#### Commit Working Code + +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 +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. + +Committing working code doesn't mean you have to commit a working feature. It just means whatever you are committing isn't breaking anything. + +#### Diff your code + +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. + +[Learn VS Code's Version Control](https://www.youtube.com/watch?v=AKNYgP0yEOY) + +[Learn IntelliJ's Version Control](https://www.youtube.com/watch?v=MaQnpCaiop0) + +[Diff in IntelliJ](https://www.jetbrains.com/help/idea/comparing-files-and-folders.html) + +#### Always Test your code + +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. + +#### Avoid Committing passwords & secrets + +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. + +### 4. Undoing Changes + +#### What If You + +- committed the wrong message? +- skipped file in the last commit? +- accidentally committed on master? +- accidentally committed to the wrong branch? +- want to undo the last 5 commits? +- want to undo changes to a file? + +Answers to all these questions are well explained in +[this good resource](https://ohshitgit.com/). Please go through it and have it as a reference whenever you encounter such cases diff --git a/1. dev-basics/4. markdown.md b/1. dev-basics/4. markdown.md new file mode 100644 index 0000000..6cd173a --- /dev/null +++ b/1. dev-basics/4. markdown.md @@ -0,0 +1,7 @@ +# Markdown + +Learn markdown from the following link + +[Github markdown guide](https://guides.github.com/features/mastering-markdown/) + +Use Markdown in every technical paper, Readme.md and LMS submissions diff --git a/1. dev-basics/5. computer-networks.md b/1. dev-basics/5. computer-networks.md new file mode 100644 index 0000000..7dfd89b --- /dev/null +++ b/1. dev-basics/5. computer-networks.md @@ -0,0 +1,3 @@ +The following YouTube is a simple and clear explanation of computer networks without getting too much into the theory. + +[https://www.youtube.com/watch?v=aHJElrgj6UA](https://www.youtube.com/watch?v=aHJElrgj6UA) diff --git a/1. dev-basics/README.md b/1. dev-basics/README.md new file mode 100644 index 0000000..4a09499 --- /dev/null +++ b/1. dev-basics/README.md @@ -0,0 +1,8 @@ +# Developer Basics + +Follow the order: +1. Development Setup +2. Command Line Interface - CLI +3. Git +4. Markdown +5. Computer Networks diff --git a/10. searching/searching.md b/10. searching/searching.md new file mode 100644 index 0000000..67f7df4 --- /dev/null +++ b/10. searching/searching.md @@ -0,0 +1,8 @@ +# Searching + +## NPM + +Video - How to choose and use npm modules +[https://www.youtube.com/watch?v=DuyxqG3L7A8](https://www.youtube.com/watch?v=DuyxqG3L7A8) + +## Documentation diff --git a/2. javascript/1. getting-started.md b/2. javascript/1. getting-started.md new file mode 100644 index 0000000..195e256 --- /dev/null +++ b/2. javascript/1. getting-started.md @@ -0,0 +1,97 @@ +# Getting Started with NodeJS + +### Node Version Manager (NVM) +It is a tool used to manage multiple active Node.js versions. + +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 + +### Why use NVM? +NVM allows users to: + +- Locally download any of the remote Long Term Support (LTS) versions of Node.js with a simple command. +- Easily switch between multiple versions of Node.js, right from the command line. +- Set up aliases to switch between different downloaded versions of Node.js with ease. + +Learn more about nvm [here](https://github.com/nvm-sh/nvm). + +For Linux and Mac users only +#### 1. Installing NVM +Run the NVM installer using either of the following commands: + +``` +curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.35.3/install.sh | bash +``` +or +``` +wget -qO- https://raw.githubusercontent.com/nvm-sh/nvm/v0.35.3/install.sh | bash +``` +#### 2. Verify Installation +To verify that nvm has been installed, do: +``` +command -v nvm +``` +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. + + +#### 3. Using NVM + +Once NVM is installed it allows users to install any version of Node.js through a simple command: + +``` +nvm install +``` +**Recommended:** To install the latest LTS (Long Term Support) version of Node.js, use the following command: +``` +nvm install --lts +``` +To use any specific version of Node.js for your code, use the following command: + +``` +nvm use +``` + +### What is Node.js? + +**Official Docs**: +[https://nodejs.org/en/docs/](https://nodejs.org/en/docs/) + +Well in 1-line, Node.js® is a JavaScript runtime built on Chrome's V8 JavaScript engine. + +Huh? + +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. + +Go through the videos below to understand more about how it works. +[https://www.youtube.com/watch?v=uVwtVBpw7RQ](https://www.youtube.com/watch?v=uVwtVBpw7RQ) + +### What is Node Package Manager (NPM) ? + +`npm`, short for Node Package Manager (well, not really), is two things: +- it is an online repository for the publishing of open-source Node.js projects +- and, it is a command-line utility for interacting with said repository that aids in package installation, version management, and dependency management. + +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. + +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. + +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. + +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: + +Example: +``` +git clone https://github.com/cloudhead/vows.git +cd vows + +npm install +``` +After running those commands, you will see a node_modules folder containing all of the project dependencies specified in the package.json. + +NPM Crash Course - [https://www.youtube.com/watch?v=jHDhaSSKmB0](https://www.youtube.com/watch?v=jHDhaSSKmB0) + +### Best Practices: Starting a Project + +Always have a .gitignore file and a README.md when starting a project. + +* Use relevant .gitignore templates from [https://github.com/github/gitignore](https://github.com/github/gitignore) +* README.md file should have a brief project description and how to run, install and/or deploy the project. diff --git a/2. javascript/2. javascript-basics.md b/2. javascript/2. javascript-basics.md new file mode 100644 index 0000000..3f0f2d0 --- /dev/null +++ b/2. javascript/2. javascript-basics.md @@ -0,0 +1,420 @@ +# JavaScript Basics + +## 1. Introduction +[CodeAcademy Tutorial](https://www.codecademy.com/learn/introduction-to-javascript) + +You can also watch a popular JavaScript basics crash course video on Youtube. + +## 2. Modules + +[Read this article](https://www.freecodecamp.org/news/node-module-exports-explained-with-javascript-export-function-examples/) + +Video - [https://www.youtube.com/watch?v=hyYbs3SANRo](https://www.youtube.com/watch?v=hyYbs3SANRo) + +## 3. Best Practices: Indentation + +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. + +Bad indentation: +```javascript + function problem1(inventory,passid){ + +if(Array.isArray(inventory)){ + +return inventory;} + +else{ + return []; +} +} + +module.exports=problem1; +``` + + +Good indentation: +```javascript +function problem1(inventory, passid) { + if(Array.isArray(inventory) && passid<50) { + return inventory; + } else { + return []; + } +} + +module.exports = problem1; +``` + +An easy way to indent your code is to press Ctrl + Shift + I in VSCode. + +If you are on a Mac, try Cmd + Shift + I + +## 4. Best Practices: Variable Naming + +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. + +Bad Naming: +```javascript +const a = [1, 2, 3, 4, 5]; +const a1 = [1, 4, 9, 16, 25]; +``` + +Good naming: +```javascript +const numbers = [1, 2, 3, 4, 5]; +const squares = [1, 4, 9, 16, 25]; +``` + +This also applies to functions + + +Bad Naming: +```javascript +const numbers = [1, 2, 3, 4, 5]; + +function calc(n) { + return n * n; +} + +const squares = numbers.map(calc); +``` + +Good naming: +```javascript +const numbers = [1, 2, 3, 4, 5]; + +function squareNumber(number) { + return number * number; +} + +const squares = numbers.map(squareNumber); +``` + +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. + +### 4. Best Practices: if else + +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. + +Bad Usage: +```javascript +let sum = 10; + +if(value %2 == 0) + sum += value; +else if(value == 0) + sum += 1; +else + sum += -1; +``` + +Good usage: +```javascript +let sum = 10; + +if(value %2 == 0) { + sum += value; +} else if(value == 0) { + sum += 1; +} else { + sum += -1; +} +``` + +This ensures that there is never any confusion about which code runs and when. + +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. + +## 6. JS Drill: Cars + +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. +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. + +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. + +Example for loop: +----------------- +```js +arr = [1,2,3,4]; +for (i = 0; i < arr.length; i++) { + arr[i]; // 1,2,3,4 +} +``` + +Create a function for each problem in a file called + + problem1.js + problem2.js + problem3.js +and so on in the root of the project. + +Ensure that the functions in each file is exported and tested in its own file called + + testProblem1.js + testProblem2.js + testProblem3.js +and so on in a folder called `test`. + +Each function must take at least one argument. The first argument must always be the inventory. + +Example: +```js +const result = problem1(inventory); +``` + +If you want to pass more arguments, that is up to you. + +Create a new git repo on gitlab for this project, ensure that you commit after you complete each problem in the project. +Ensure that the repo is a public repo. + +```js + +let inventory = [{"id":1,"car_make":"Lincoln","car_model":"Navigator","car_year":2009}, +{"id":2,"car_make":"Mazda","car_model":"Miata MX-5","car_year":2001}, +{"id":3,"car_make":"Land Rover","car_model":"Defender Ice Edition","car_year":2010}, +{"id":4,"car_make":"Honda","car_model":"Accord","car_year":1983}, +{"id":5,"car_make":"Mitsubishi","car_model":"Galant","car_year":1990}, +{"id":6,"car_make":"Audi","car_model":"riolet","car_year":1995}, +{"id":7,"car_make":"Smart","car_model":"Fortwo","car_year":2009}, +{"id":8,"car_make":"Audi","car_model":"4000CS Quattro","car_year":1987}, +{"id":9,"car_make":"Ford","car_model":"Windstar","car_year":1996}, +{"id":10,"car_make":"Mercedes-Benz","car_model":"E-Class","car_year":2000}, +{"id":11,"car_make":"Infiniti","car_model":"G35","car_year":2004}, +{"id":12,"car_make":"Lotus","car_model":"Esprit","car_year":2004}, +{"id":13,"car_make":"Chevrolet","car_model":"Cavalier","car_year":1997}, +{"id":14,"car_make":"Dodge","car_model":"Ram Van 1500","car_year":1999}, +{"id":15,"car_make":"Dodge","car_model":"Intrepid","car_year":2000}, +{"id":16,"car_make":"Mitsubishi","car_model":"Montero Sport","car_year":2001}, +{"id":17,"car_make":"Buick","car_model":"Skylark","car_year":1987}, +{"id":18,"car_make":"Geo","car_model":"Prizm","car_year":1995}, +{"id":19,"car_make":"Oldsmobile","car_model":"Bravada","car_year":1994}, +{"id":20,"car_make":"Mazda","car_model":"Familia","car_year":1985}, +{"id":21,"car_make":"Chevrolet","car_model":"Express 1500","car_year":2003}, +{"id":22,"car_make":"Jeep","car_model":"Wrangler","car_year":1997}, +{"id":23,"car_make":"Eagle","car_model":"Talon","car_year":1992}, +{"id":24,"car_make":"Toyota","car_model":"MR2","car_year":2003}, +{"id":25,"car_make":"BMW","car_model":"525","car_year":2005}, +{"id":26,"car_make":"Cadillac","car_model":"Escalade","car_year":2005}, +{"id":27,"car_make":"Infiniti","car_model":"Q","car_year":2000}, +{"id":28,"car_make":"Suzuki","car_model":"Aerio","car_year":2005}, +{"id":29,"car_make":"Mercury","car_model":"Topaz","car_year":1993}, +{"id":30,"car_make":"BMW","car_model":"6 Series","car_year":2010}, +{"id":31,"car_make":"Pontiac","car_model":"GTO","car_year":1964}, +{"id":32,"car_make":"Dodge","car_model":"Ram Van 3500","car_year":1999}, +{"id":33,"car_make":"Jeep","car_model":"Wrangler","car_year":2011}, +{"id":34,"car_make":"Ford","car_model":"Escort","car_year":1991}, +{"id":35,"car_make":"Chrysler","car_model":"300M","car_year":2000}, +{"id":36,"car_make":"Volvo","car_model":"XC70","car_year":2003}, +{"id":37,"car_make":"Oldsmobile","car_model":"LSS","car_year":1997}, +{"id":38,"car_make":"Toyota","car_model":"Camry","car_year":1992}, +{"id":39,"car_make":"Ford","car_model":"Econoline E250","car_year":1998}, +{"id":40,"car_make":"Lotus","car_model":"Evora","car_year":2012}, +{"id":41,"car_make":"Ford","car_model":"Mustang","car_year":1965}, +{"id":42,"car_make":"GMC","car_model":"Yukon","car_year":1996}, +{"id":43,"car_make":"Mercedes-Benz","car_model":"R-Class","car_year":2009}, +{"id":44,"car_make":"Audi","car_model":"Q7","car_year":2012}, +{"id":45,"car_make":"Audi","car_model":"TT","car_year":2008}, +{"id":46,"car_make":"Oldsmobile","car_model":"Ciera","car_year":1995}, +{"id":47,"car_make":"Volkswagen","car_model":"Jetta","car_year":2007}, +{"id":48,"car_make":"Dodge","car_model":"Magnum","car_year":2008}, +{"id":49,"car_make":"Chrysler","car_model":"Sebring","car_year":1996}, +{"id":50,"car_make":"Lincoln","car_model":"Town Car","car_year":1999}]; + +// ==== Problem #1 ==== +// 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: +"Car 33 is a *car year goes here* *car make goes here* *car model goes here*" + +// ==== Problem #2 ==== +// 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: +"Last car is a *car make goes here* *car model goes here*" + +// ==== Problem #3 ==== +// 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. + +// ==== Problem #4 ==== +// 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. + +// ==== Problem #5 ==== +// 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. + +// ==== Problem #6 ==== +// 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. +``` + +## 7. Higher Order Array Functions + +Watch the videos and then practice + +- [https://www.youtube.com/watch?v=zdp0zrpKzIE](https://www.youtube.com/watch?v=zdp0zrpKzIE) +- [https://www.youtube.com/watch?v=rRgD1yVwIvE](https://www.youtube.com/watch?v=rRgD1yVwIvE) + +## 8. Best Practices: Higher Order Functions + +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. + +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. + +Bad Usage: +```javascript +const arr = [1, 2, 3, 4, 5]; + +const numbers = arr.filter(number => number > 5).map(number => number * number).reduce((acc, number) => acc + number); +``` + +Bad Usage: +```javascript +const arr = [1, 2, 3, 4, 5]; + +const numbers = arr.filter(number => number > 5) +.map(number => number * number) +.reduce((acc, number) => acc + number); +``` + +Good Usage: +```javascript +const arr = [1, 2, 3, 4, 5]; + +const numbers = arr.filter((number) => { + return number > 5; +}) +.map((number) => { + return number * number; +}) +.reduce((acc, number) => { + acc = acc + number; + + return acc; +}) +``` + +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. + +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. + +Bad Usage: +```javascript +const arr = [1, 2, 3, 4, 5]; + +const numbers = arr.filter(number => number > 5); +``` + +Good Usage: +```javascript +const arr = [1, 2, 3, 4, 5]; + +const numbers = arr.filter((number) => { + return number > 5; +}); +``` + +## 9. JS Drill: Cars 2 + +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. +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. + +PROJECT RESTRICTION: Use map, filter, reduce + +Create a function for each problem in a file called + + problem1.js + problem2.js + problem3.js +and so on in the root of the project. + +Ensure that the functions in each file is exported and tested in its own file called + + testProblem1.js + testProblem2.js + testProblem3.js +and so on in a folder called `test`. + +Each function must take at least one argument. The first argument must always be the inventory. + +Example: +```js +const result = problem1(inventory); +``` + +If you want to pass more arguments, that is up to you. + +Create a new git repo on gitlab for this project, ensure that you commit after you complete each problem in the project. +Ensure that the repo is a public repo. + +```js + +let inventory = [{"id":1,"car_make":"Lincoln","car_model":"Navigator","car_year":2009}, +{"id":2,"car_make":"Mazda","car_model":"Miata MX-5","car_year":2001}, +{"id":3,"car_make":"Land Rover","car_model":"Defender Ice Edition","car_year":2010}, +{"id":4,"car_make":"Honda","car_model":"Accord","car_year":1983}, +{"id":5,"car_make":"Mitsubishi","car_model":"Galant","car_year":1990}, +{"id":6,"car_make":"Audi","car_model":"riolet","car_year":1995}, +{"id":7,"car_make":"Smart","car_model":"Fortwo","car_year":2009}, +{"id":8,"car_make":"Audi","car_model":"4000CS Quattro","car_year":1987}, +{"id":9,"car_make":"Ford","car_model":"Windstar","car_year":1996}, +{"id":10,"car_make":"Mercedes-Benz","car_model":"E-Class","car_year":2000}, +{"id":11,"car_make":"Infiniti","car_model":"G35","car_year":2004}, +{"id":12,"car_make":"Lotus","car_model":"Esprit","car_year":2004}, +{"id":13,"car_make":"Chevrolet","car_model":"Cavalier","car_year":1997}, +{"id":14,"car_make":"Dodge","car_model":"Ram Van 1500","car_year":1999}, +{"id":15,"car_make":"Dodge","car_model":"Intrepid","car_year":2000}, +{"id":16,"car_make":"Mitsubishi","car_model":"Montero Sport","car_year":2001}, +{"id":17,"car_make":"Buick","car_model":"Skylark","car_year":1987}, +{"id":18,"car_make":"Geo","car_model":"Prizm","car_year":1995}, +{"id":19,"car_make":"Oldsmobile","car_model":"Bravada","car_year":1994}, +{"id":20,"car_make":"Mazda","car_model":"Familia","car_year":1985}, +{"id":21,"car_make":"Chevrolet","car_model":"Express 1500","car_year":2003}, +{"id":22,"car_make":"Jeep","car_model":"Wrangler","car_year":1997}, +{"id":23,"car_make":"Eagle","car_model":"Talon","car_year":1992}, +{"id":24,"car_make":"Toyota","car_model":"MR2","car_year":2003}, +{"id":25,"car_make":"BMW","car_model":"525","car_year":2005}, +{"id":26,"car_make":"Cadillac","car_model":"Escalade","car_year":2005}, +{"id":27,"car_make":"Infiniti","car_model":"Q","car_year":2000}, +{"id":28,"car_make":"Suzuki","car_model":"Aerio","car_year":2005}, +{"id":29,"car_make":"Mercury","car_model":"Topaz","car_year":1993}, +{"id":30,"car_make":"BMW","car_model":"6 Series","car_year":2010}, +{"id":31,"car_make":"Pontiac","car_model":"GTO","car_year":1964}, +{"id":32,"car_make":"Dodge","car_model":"Ram Van 3500","car_year":1999}, +{"id":33,"car_make":"Jeep","car_model":"Wrangler","car_year":2011}, +{"id":34,"car_make":"Ford","car_model":"Escort","car_year":1991}, +{"id":35,"car_make":"Chrysler","car_model":"300M","car_year":2000}, +{"id":36,"car_make":"Volvo","car_model":"XC70","car_year":2003}, +{"id":37,"car_make":"Oldsmobile","car_model":"LSS","car_year":1997}, +{"id":38,"car_make":"Toyota","car_model":"Camry","car_year":1992}, +{"id":39,"car_make":"Ford","car_model":"Econoline E250","car_year":1998}, +{"id":40,"car_make":"Lotus","car_model":"Evora","car_year":2012}, +{"id":41,"car_make":"Ford","car_model":"Mustang","car_year":1965}, +{"id":42,"car_make":"GMC","car_model":"Yukon","car_year":1996}, +{"id":43,"car_make":"Mercedes-Benz","car_model":"R-Class","car_year":2009}, +{"id":44,"car_make":"Audi","car_model":"Q7","car_year":2012}, +{"id":45,"car_make":"Audi","car_model":"TT","car_year":2008}, +{"id":46,"car_make":"Oldsmobile","car_model":"Ciera","car_year":1995}, +{"id":47,"car_make":"Volkswagen","car_model":"Jetta","car_year":2007}, +{"id":48,"car_make":"Dodge","car_model":"Magnum","car_year":2008}, +{"id":49,"car_make":"Chrysler","car_model":"Sebring","car_year":1996}, +{"id":50,"car_make":"Lincoln","car_model":"Town Car","car_year":1999}]; + +// ==== Problem #1 ==== +// 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: +"Car 33 is a *car year goes here* *car make goes here* *car model goes here*" + +// ==== Problem #2 ==== +// 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: +"Last car is a *car make goes here* *car model goes here*" + +// ==== Problem #3 ==== +// 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. + +// ==== Problem #4 ==== +// 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. + +// ==== Problem #5 ==== +// 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. + +// ==== Problem #6 ==== +// 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. +``` + +## 10. Scopes and Closures +- [JavaScript Scope and Closures](https://css-tricks.com/javascript-scope-closures/) + +- [The Ultimate Guide to Hoisting, Scopes, and Closures in JavaScript](https://ui.dev/ultimate-guide-to-execution-contexts-hoisting-scopes-and-closures-in-javascript/) diff --git a/2. javascript/3. javascript-practice.md b/2. javascript/3. javascript-practice.md new file mode 100644 index 0000000..a6df12a --- /dev/null +++ b/2. javascript/3. javascript-practice.md @@ -0,0 +1,377 @@ +# Javascript Practice + +## Best Practices + +### 1. Case + +Read: [Case Styles: Camel, Pascal, Snake, and Kebab Case](https://betterprogramming.pub/string-case-styles-camel-pascal-snake-and-kebab-case-981407998841) + +Read: [What is camelCase, PascalCase, kebab-case and snake_case? +](https://winnercrespo.com/naming-conventions/) + +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. + +Bad Inconsistent Style: +```javascript +let name = "John"; +let Age = 25; +let is_married = false; +let salaryDetails = { + company_name: "MountBlue", + CompanyAddress: "Bangalore", + amount: 10000, +}; + +function PrintDetails() { + console.log(name, Age); + console.log(salaryDetails); + console.log(is_married ? "Married" : "Single"); +} +``` + + +Good Consistent style: +```javascript +let name = "John"; +let age = 25; +let isMarried = false; +let salaryDetails = { + companyName: "MountBlue", + companyAddress: "Bangalore", + amount: 10000, +}; + +function printDetails() { + console.log(name, age); + console.log(salaryDetails); + console.log(isMarried ? "Married" : "Single"); +} +``` + +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**. + +Do not use `thISWayOFNaMiNg`. + +### 2. Naming Loop Variables + +Keeping your variable names as descriptive as possible includes naming variables in loops as well. + +Bad Naming: +```javascript +for(let i = 0; i < numbers.length; i++) { + console.log(numbers[i]); +} +``` + +Good naming: +```javascript +for(let index = 0; index < numbers.length; index++) { + console.log(numbers[index]); +} +``` + +This applies to naming them when using higher order array methods as well: + + +Bad Naming: +```javascript +const squares = numbers.map((number, i) => { + console.log(i); + return number * number; +}) +``` + +Good naming: +```javascript +const squares = numbers.map((number, index) => { + console.log(index); + return number * number; +}) +``` + +Similarly, when working with matrices: + + +Bad Naming: +```javascript +for(let i = 0; i < matrix.length; i++) { + for(let j = 0; j < matrix[i].length; j++) { + console.log(matrix[i][j]); + } +} +``` + +Good naming: +```javascript +for(let rowIndex = 0; rowIndex < matrix.length; rowIndex++) { + for(let columnIndex = 0; columnIndex < matrix[rowIndex].length; columnIndex++) { + console.log(matrix[rowIndex][columnIndex]); + } +} +``` + +Though it is often better to be explicit with it as well: + +Explicit and good naming: +```javascript +for(let rowIndex = 0; rowIndex < matrix.length; rowIndex++) { + let row = matrix[rowIndex]; + + for(let columnIndex = 0; columnIndex < row.length; columnIndex++) { + console.log(row[columnIndex]); + } +} +``` + +### 3. Improving Readability + +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. + +An easy way to do that would be to add new lines between declaration and operations parts of your code. + +Poor Readability: +```javascript +const fs = require("fs"); +let numbers = [1,2,3,4,5]; +let pi = 3.14; +let squares = numbers.map(number => number * number); +console.log(squares); +``` + +Good Readability +```javascript +const fs = require("fs"); + +let numbers = [1,2,3,4,5]; +let pi = 3.14; + +let squares = numbers.map(number => number * number); +console.log(squares); +``` + +An example without declaration: + +Bad Readability: +```javascript +function problem1(inventory, id){ + if(!inventory || !id) return []; + for(let cars of inventory){ + if(cars.id===id){ + return cars; + } + + }return []; +} + +module.exports=problem1; +``` + +Good Readability: +```javascript +function problem1(inventory, id){ + if(inventory == undefined || id == undefined) { + return []; + } else { + for(let cars of inventory){ + if(cars.id === id){ + return cars; + } + } + + return []; + } +} + +module.exports = problem1; +``` + +### 4. Starting NodeJS Projects + +Best Practices When Starting NodeJS Projects +[https://www.youtube.com/watch?v=X_UQbPnvSx4](https://www.youtube.com/watch?v=X_UQbPnvSx4) + +## JS Drill: Arrays + +```js +const items = [1, 2, 3, 4, 5, 5]; // use this array to test your code. +/* + Complete the following functions. + These functions only need to work with arrays. + A few of these functions mimic the behavior of the `Built` in JavaScript Array Methods. + The idea here is to recreate the functions from scratch BUT if you'd like, + feel free to Re-use any of your functions you build within your other functions. + **DONT** Use for example. .forEach() to recreate each, and .map() to recreate map etc. + You CAN use concat, push, pop, etc. but do not use the exact method that you are replicating + + Name your files like so: + each.js + testEach.js + map.js + testMap.js +*/ + +function each(elements, cb) { + // Do NOT use forEach to complete this function. + // Iterates over a list of elements, yielding each in turn to the `cb` function. + // This only needs to work with arrays. + // You should also pass the index into `cb` as the second argument + // based off http://underscorejs.org/#each +} + +function map(elements, cb) { + // Do NOT use .map, to complete this function. + // 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 . + // Produces a new array of values by mapping each value in list through a transformation function (iteratee). + // Return the new array. +} + +function reduce(elements, cb, startingValue) { + // Do NOT use .reduce to complete this function. + // How reduce works: A reduce function combines all elements into a single value going from left to right. + // Elements will be passed one by one into `cb` along with the `startingValue`. + // `startingValue` should be the first argument passed to `cb` and the array element should be the second argument. + // `startingValue` is the starting value. If `startingValue` is undefined then make `elements[0]` the initial value. +} + +function find(elements, cb) { + // Do NOT use .includes, to complete this function. + // Look through each value in `elements` and pass each element to `cb`. + // If `cb` returns `true` then return that element. + // Return `undefined` if no elements pass the truth test. +} + +function filter(elements, cb) { + // Do NOT use .filter, to complete this function. + // Similar to `find` but you will return an array of all elements that passed the truth test + // Return an empty array if no elements pass the truth test +} + +const nestedArray = [1, [2], [[3]], [[[4]]]]; // use this to test 'flatten' + +function flatten(elements) { + // Flattens a nested array (the nesting can be to any depth). + // Hint: You can solve this using recursion. + // Example: flatten([1, [2], [3, [[4]]]]); => [1, 2, 3, 4]; +} +``` + +## JS Drill: Objects + +```js +const testObject = { name: 'Bruce Wayne', age: 36, location: 'Gotham' }; // use this object to test your functions + +// Complete the following underscore functions. +// Reference http://underscorejs.org/ for examples. +// Check and use MDN as well + +/* + Create a function for each problem in a file called + keys.js + values.js + pairs.js + and so on in the root of the project. + + Ensure that the functions in each file is exported and tested in its own file called + testKeys.js + testValues.js + testPairs.js + and so on in a folder called test. + + Create a new git repo on gitlab for this project, ensure that you commit after you complete each problem in the project. + Ensure that the repo is a public repo. + + When you are done, send the gitlab url to your mentor +*/ + +function keys(obj) { + // Retrieve all the names of the object's properties. + // Return the keys as strings in an array. + // Based on http://underscorejs.org/#keys +} + +function values(obj) { + // Return all of the values of the object's own properties. + // Ignore functions + // http://underscorejs.org/#values +} + +function mapObject(obj, cb) { + // Like map for arrays, but for objects. Transform the value of each property in turn by passing it to the callback function. + // http://underscorejs.org/#mapObject +} + +function pairs(obj) { + // Convert an object into a list of [key, value] pairs. + // http://underscorejs.org/#pairs +} + +/* STRETCH PROBLEMS */ + +function invert(obj) { + // Returns a copy of the object where the keys have become the values and the values the keys. + // Assume that all of the object's values will be unique and string serializable. + // http://underscorejs.org/#invert +} + +function defaults(obj, defaultProps) { + // Fill in undefined properties that match properties on the `defaultProps` parameter object. + // Return `obj`. + // http://underscorejs.org/#defaults +} +``` + +## Best Practices When Starting NodeJS Projects +[Watch this video](https://www.youtube.com/watch?v=X_UQbPnvSx4) + +## Choosing npm modules +[Watch this video](https://www.youtube.com/watch?v=DuyxqG3L7A8) + +## IPL Data Project I + +**Download the data from:** [https://www.kaggle.com/manasgarg/ipl](https://www.kaggle.com/manasgarg/ipl) + +There should be 2 files: +- deliveries.csv +- matches.csv + +In this data assignment you will transform raw data of IPL to calculate the following stats: +1. Number of matches played per year for all the years in IPL. +2. Number of matches won per team per year in IPL. +3. Extra runs conceded per team in the year 2016 +4. Top 10 economical bowlers in the year 2015 +5. Find the number of times each team won the toss and also won the match +6. Find a player who has won the highest number of *Player of the Match* awards for each season +7. Find the strike rate of a batsman for each season +8. Find the highest number of times one player has been dismissed by another player +9. Find the bowler with the best economy in super overs + +Implement the functions, **one for each task**. +Use the results of the functions to dump JSON files in the output folder + +### Instructions: +- Create a new repo with name js-ipl-data-project in Gitlab subgroup, before starting implementation of the solution +- Make sure to follow proper Git practices +- Before submission, make sure that all the points in the below checklist are covered: + - Git commits + - Directory structure + - package.json - dependencies, devDependencies + - .gitignore file + - Proper/Intuitive Variable names + - Separate module for functions + +### Directory structure: + +- src/ + - server/ + - 1-matches-per-year.js + - 2-matches-won-per-team-per-year.js + - public/ + - output + - matchesPerYear.json + - ... + - data/ + - matches.csv + - deliveries.csv +- package.json +- package-lock.json +- .gitignore diff --git a/2. javascript/4. js-debugging-and-review.md b/2. javascript/4. js-debugging-and-review.md new file mode 100644 index 0000000..ba302a8 --- /dev/null +++ b/2. javascript/4. js-debugging-and-review.md @@ -0,0 +1,73 @@ +# JavaScript Debugging and Review + +## Debugging + +- 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) +- 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) +- Using console methods - [https://fireship.io/courses/javascript/concepts-console/](https://fireship.io/courses/javascript/concepts-console/) + + +## Self Review + +Write a technical paper on each topic listed below. + +All technical papers should be: +1. in markdown format +2. hosted in a single folder on Gitlab. +3. Use your own words and your own examples. +4. This is for your own revision. Do not copy paste from internet or each other. +5. Less words is appreciated. Make sure it is to the point. +6. Focus more on code samples and codeblocks. + +Share link of the folder in your private Discord channel when you start. Also just drop a message when each technical paper is completed. + +### Topics: +- Loops + - for + - forEach + - for .. in + - for .. of + - while +- Mutable and Immutable Methods (in strings and arrays) +- Pass by Reference and Pass by Value - add codeblocks +- Array methods - add codeblocks and mention mutable/immutable + - **Basics**: + - Array.pop + - Array.push + - Array.concat + - Array.slice + - Array.splice + - Array.join + - Array.flat + - **Finding**: + - Array.find + - Array.indexOf + - Array.includes + - Array.findIndex + - **Higher Order Functions**: + - Array.forEach + - Array.filter + - Array.map + - Array.reduce + - Array.sort + - **Advanced**: + - Array methods chaining +- String methods - add codeblocks and mention mutable/immutable +- Object methods and operations - add codeblocks and mention mutable/immutable +- Hoisting +- Scopes +- Closures +- Higher Order Functions +- Best Practices +- Debugging + +## Miscellaneous + +- History of JavaScript + - [https://ui.dev/ecmascript/](https://ui.dev/ecmascript/) + - [https://auth0.com/blog/a-brief-history-of-javascript/](https://auth0.com/blog/a-brief-history-of-javascript/) +- Imperative VS Declarative Programming + - [https://ui.dev/imperative-vs-declarative-programming/](https://ui.dev/imperative-vs-declarative-programming/) +- Clean Code + - [https://github.com/ryanmcdermott/clean-code-javascript](https://github.com/ryanmcdermott/clean-code-javascript) + diff --git a/3. asynchronous-javascript/1. callback-functions.md b/3. asynchronous-javascript/1. callback-functions.md new file mode 100644 index 0000000..29288d3 --- /dev/null +++ b/3. asynchronous-javascript/1. callback-functions.md @@ -0,0 +1,87 @@ +# Callback functions + +## Passing function as an argument + +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. + +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. + +![callback function](./Callback_Function.png "callback function") + +## An Example + +Have a look at the code given below. + +```javascript +function calculateSum(n, callback) { + var i; + var sum = 0; + for (i = 1; i <= n; i++) { + sum += i; + } + console.log(`Sum is: ${sum}`); + callback(sum); +} + +var n = 10; +calculateSum(n, function(sum){ + console.log(`Average is: ${sum/n}`); +}); +``` + +This is how it’s working: + +- **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. + +- **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. + +> The callback function can also be defined separately and then passed to the function call. + +## Why do we need Callback Functions? + +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. + +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. + +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… + +## How to create a Callback? + +Let's say we want to log a message to the console but it should be there after 3 seconds. + +```javascript +const message = function() { + console.log("This message is shown after 3 seconds"); +} + +setTimeout(message, 3000); +``` + +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) + +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. + +## What is an Anonymous Function? + +Alternatively, we can define a function directly inside another function, instead of calling it. It will look like this: + +```javascript +setTimeout(function() { + console.log("This message is shown after 3 seconds"); +}, 3000); +``` + +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. + +## Callback as an Arrow Function + +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: + +```javascript +setTimeout(() => { + console.log("This message is shown after 3 seconds"); +}, 3000); +``` + +## Video +[https://www.youtube.com/watch?v=qtfi4-8dj9c](https://www.youtube.com/watch?v=qtfi4-8dj9c) diff --git a/3. asynchronous-javascript/2. asynchronous-programming.md b/3. asynchronous-javascript/2. asynchronous-programming.md new file mode 100644 index 0000000..2e31c6e --- /dev/null +++ b/3. asynchronous-javascript/2. asynchronous-programming.md @@ -0,0 +1,52 @@ +# Asynchronous Programming + +Read this + +[https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Asynchronous/Concepts](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Asynchronous/Concepts) + +## Tutorials + +[https://github.com/workshopper/learnyounode](https://github.com/workshopper/learnyounode) + +Remaining Sections/Topics from [CodeAcademy](https://www.codecademy.com/learn/introduction-to-javascript) Promises, Async/Await, Request + +## Best Practices: if else + +Bad Usage: + +```javascript +fs.readFile(filePath, "utf-8", (err, data) => { + if(err) { + console.error(err); + } + + console.log(data); +}); +``` + +Good Usage: + +```javascript +fs.readFile(filePath, "utf-8", (err, data) => { + if(err) { + console.error(err); + } else { + console.log(data); + } +}); +``` + +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. + +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. + +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. + +## Error First Callback Functions + +[Read this article](https://fredkschott.com/post/2014/03/understanding-error-first-callbacks-in-node-js/) + +## Asynchronous Callbacks Control - Clarification Session + +[https://www.youtube.com/watch?v=mZ0FkdIBE2o](https://www.youtube.com/watch?v=mZ0FkdIBE2o) + diff --git a/3. asynchronous-javascript/3. promise.md b/3. asynchronous-javascript/3. promise.md new file mode 100644 index 0000000..d28c6f5 --- /dev/null +++ b/3. asynchronous-javascript/3. promise.md @@ -0,0 +1,76 @@ +# Promise + +## What is a Promise? +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. + +A promise has 2 possible outcomes: it will either be kept when the time comes, or it won’t. + +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. + +## Promises in JavaScript + +First of all, a Promise is an object. There are 3 states of the Promise object: + +- **Pending**: is the initial state. +- **Resolved**: indicates that the promised operation was successful. +- **Rejected**: indicates that the promised operation was unsuccessful.​ + +![promise states](./promise_states.png "promise states") + +For example, when we request data from the server by using a Promise, it will be in pending mode until we receive our data. + +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. + +## Creating a simple promise + +1. A promise is created using a constructor that takes a call back function with two arguments (line 1). +2. The code needed to perform the promised task is written. In this example, it is assumed that the code executes successfully (line 2). +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). +4. If the task is unsuccessful, then the promise is rejected. In this example, an optional parameter is passed (lines 6-7). +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). + +```javascript +let promise = new Promise((resolve, reject) => { + // Code to perform the promised task + let task_performed = true; + if(task_performed) { + resolve('The promised task was performed successfully.'); + } else { + reject('The promised task was not performed.'); + } +}); +promise.then((fromRes) => console.log(fromRes)). + catch((fromRej) => console.log(fromRej)); +``` + +## Using Promise.all() + +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. + +```javascript +let promise1 = new Promise((resolve, reject) => { + resolve(1); +}); +let promise2 = new Promise((resolve, reject) => { + setTimeout(resolve, 1000,2); +}); +Promise.all([promise1, promise2]).then( () => { + console.log("Both the promises have been resolved successfully."); +}); +``` + +## Using Promise.race() + +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. + +```javascript +let promise1 = new Promise((resolve, reject) => { + setTimeout(resolve(2), 100); +}); +let promise2 = new Promise((resolve, reject) => { + resolve(1); +}); +Promise.race([promise1, promise2]).then((fromRes) => { + console.log(fromRes); +}); +``` diff --git a/3. asynchronous-javascript/4. callback-hell-promise-chaining.md b/3. asynchronous-javascript/4. callback-hell-promise-chaining.md new file mode 100644 index 0000000..a6a7dad --- /dev/null +++ b/3. asynchronous-javascript/4. callback-hell-promise-chaining.md @@ -0,0 +1,56 @@ +# Callback-Hell and Chaining of Promises + +## What is the difference between Callbacks and Promises? +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). + +This is one of the greatest advantages of using Promises, but why? + +## What is Chaining? +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. + +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: + +```javascript +firstRequest(function(response) { + secondRequest(response, function(nextResponse) { + thirdRequest(nextResponse, function(finalResponse) { + console.log('Final response: ' + finalResponse); + }, failureCallback); + }, failureCallback); +}, failureCallback); +``` +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: + +```javascript +firstRequest() + .then(function(response) { + return secondRequest(response); +}).then(function(nextResponse) { + return thirdRequest(nextResponse); +}).then(function(finalResponse) { + console.log('Final response: ' + finalResponse); +}).catch(failureCallback); +``` +The code just above shows how multiple callbacks can be chained one after another. Chaining is one of the best features of Promises. + +### Video +[https://www.youtube.com/watch?v=OXpZfyVXeI8](https://www.youtube.com/watch?v=OXpZfyVXeI8) + +## Recap + +Go through the following blog and related video to get an idea of asynchronous JavaScript + +[https://ui.dev/async-javascript-from-callbacks-to-promises-to-async-await/](https://ui.dev/async-javascript-from-callbacks-to-promises-to-async-await/) + +### Video +[https://www.youtube.com/watch?v=gB-OmN1egV8](https://www.youtube.com/watch?v=gB-OmN1egV8) + +## Event Loop +Read this + +[https://flaviocopes.com/javascript-event-loop/](https://flaviocopes.com/javascript-event-loop/) + +### Video +[https://www.youtube.com/watch?v=8aGhZQkoFbQ](https://www.youtube.com/watch?v=8aGhZQkoFbQ) + + diff --git a/3. asynchronous-javascript/5. project.md b/3. asynchronous-javascript/5. project.md new file mode 100644 index 0000000..6935672 --- /dev/null +++ b/3. asynchronous-javascript/5. project.md @@ -0,0 +1,157 @@ +# IPL Project + +## Best Practices: Imports + +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. + +If you are using [destructuring](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment), this does not apply. + +Bad Usage: +```javascript +const functions = require("./ipl"); + +functions.mostManOfTheMatch(); +``` + +Good Usage: +```javascript +const ipl = require("./ipl"); + +ipl.mostManOfTheMatch(); +``` + +## Best Practices: Semi-Colon Usage + +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. + +So, + +If you are using `;`, use it everywhere. + +If you not are using `;`, do not use it everywhere. + +Bad Usage: +```javascript +let factor = 2 +let numbers = [1, 2, 3, 4, 5, 6]; + +let computedNumbers = numbers.map((number) => { + console.log(number); + return (number * factor) +}) +``` + +Good Usage: +```javascript +let factor = 2; +let numbers = [1, 2, 3, 4, 5, 6]; + +let computedNumbers = numbers.map((number) => { + console.log(number); + return (number * factor); +}) +``` + +Alternative Good Usage: +```javascript +let factor = 2 +let numbers = [1, 2, 3, 4, 5, 6] + +let computedNumbers = numbers.map((number) => { + console.log(number) + return (number * factor) +}) +``` + +## Best Practices: Objects and Arrays Readability + +In an object, ensure that every `key: value` pair is on a new line. This will increase the readability of your code. + +Bad: +```javascript +const user = {name: "John Doe", age: 55, address: "Hello World Town"}; +``` + +Good: +```javascript +const user = { + name: "John Doe", + age: 55, + address: "Hello World Town" +}; +``` + +Bad: +```javascript +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"}]; +``` + +Bad: +```javascript +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"} +]; +``` + +Good: +```javascript +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" + }, +]; +``` + +## Best Practices: Comments + +Comments describe ***why*** certain code works the way it does and now what it does. + +For example, +```javascript +// Convert the bowlers array of objects into a string +const bowlersJSONData = JSON.stringify(bowlers);` +``` + +This is fairly obvious to anyone who is familiar with javascript and does not serve any purpose. Hence the comment should be removed. + +Similarly, comments that are there for your own understanding such as: +```javascript +const fs = require("fs"); // Internal module +const ipl = require("./ipl"); // Custom module +const csvtojson = require("csvtojson"); // External module +``` + +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.* + +A good place to add a comment would be in a place like this: +```javascript +const economicalBowlers = bowlers.sort((bowlerA, bowlerB) => { + return bowlerA[1] - bowlerB[1]; +}); +``` + +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.*** + +This is a good reason to write a descriptive comment such as: +```javascript +const economicalBowlers = bowlers.sort((bowlerA, bowlerB) => { + // [1] contains the economy of the bowler stored as a number + return bowlerA[1] - bowlerB[1]; +}); +``` + +So that anyone else who reads your code can use the comment to immediately understand *why* that code was written in that way. diff --git a/3. asynchronous-javascript/6. es6.md b/3. asynchronous-javascript/6. es6.md new file mode 100644 index 0000000..c47cd08 --- /dev/null +++ b/3. asynchronous-javascript/6. es6.md @@ -0,0 +1,3 @@ +# ES6 + +[https://www.youtube.com/watch?v=NCwa_xi0Uuc](https://www.youtube.com/watch?v=NCwa_xi0Uuc) diff --git a/3. asynchronous-javascript/7. self-review.md b/3. asynchronous-javascript/7. self-review.md new file mode 100644 index 0000000..c26cfe6 --- /dev/null +++ b/3. asynchronous-javascript/7. self-review.md @@ -0,0 +1,6 @@ +# Self Review + +Write a technical paper on: +* Callbacks +* Promises +* Code Control diff --git a/3. asynchronous-javascript/Callback_Function.png b/3. asynchronous-javascript/Callback_Function.png new file mode 100644 index 0000000..71a93d2 Binary files /dev/null and b/3. asynchronous-javascript/Callback_Function.png differ diff --git a/3. asynchronous-javascript/promise_states.png b/3. asynchronous-javascript/promise_states.png new file mode 100644 index 0000000..d47c274 Binary files /dev/null and b/3. asynchronous-javascript/promise_states.png differ diff --git a/4. web-app-architecture/1. web-app-architecture.md b/4. web-app-architecture/1. web-app-architecture.md new file mode 100644 index 0000000..f47e446 --- /dev/null +++ b/4. web-app-architecture/1. web-app-architecture.md @@ -0,0 +1,110 @@ +# Web App Architecture + +## 1. What is a Web App? + +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. + +People often confuse web applications and websites as being the same but actually, the two are quite different. + +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. + + +![web app](./web-app.png "web app") + +### Types of web applications +The two main types of web applications are: + +- Dynamic: Require server-side processing to input your data and show you the relevant information. +- Static: Do not require any server-side processing. + +### Examples +Some of the more popular examples of web applications include things like Google Docs, DropBox, and Spotify. + +### 2. Web Server versus Application Server + +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. + +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. + +The illustration below highlights the difference in their architecture: + +![web server versus application server](./web-server-vs-application-server.png "web server versus application server") + +The columns below summarize the key differences between the two types of servers: + +| Web Server | Application Server | +|---------------------------|-----------------------| +| Deliver static content.| Delivers dynamic content.| +|Content is delivered using the HTTP protocol only.| Provides business logic to application programs using several protocols (including HTTP).| +|Serves only web-based applications.|Can serve web and enterprise-based applications.| +|No support for multi-threading.| Uses multithreading to support multiple requests in parallel.| +|Facilitates web traffic that is not very resource intensive.| Facilitates longer running processes that are very resource-intensive​.| + +## 3. HTTP + +Read this article on Mozilla Developer Network. +[https://developer.mozilla.org/en-US/docs/Web/HTTP/Overview](https://developer.mozilla.org/en-US/docs/Web/HTTP/Overview) + +## 4. Choosing a HTTP Response Code + +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) +2. [Commonly used Response Codes with Discussion](https://www.bigbinary.com/conversation) + +## 6. HTTP Drills I + +Go through the following link to learn the basics of the node `http` standard library. +[https://flaviocopes.com/node-module-http/](https://flaviocopes.com/node-module-http/) + +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: + + +- **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. +``` + + + + + +

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

+

- Martin Fowler

+ + + +``` +- **GET /json** - Should return the following JSON string +``` +{ + "slideshow": { + "author": "Yours Truly", + "date": "date of publication", + "slides": [ + { + "title": "Wake up to WonderWidgets!", + "type": "all" + }, + { + "items": [ + "Why WonderWidgets are great", + "Who buys WonderWidgets" + ], + "title": "Overview", + "type": "all" + } + ], + "title": "Sample Slide Show" + } +} +``` +- **GET /uuid** - Should return a UUID4. For example: +``` +{ + "uuid": "14d96bb1-5d53-472f-a96e-b3a1fa82addd" +} +``` +- **GET /status/{status_code}** - Should return a response with a status code as specified in the request. For example: + - /status/100 - Return a response with 100 status code + - /status/500 - Return a response with 500 status code + + Try it out for 100,200,300,400,500. + +- **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. diff --git a/4. web-app-architecture/2. express-js.md b/4. web-app-architecture/2. express-js.md new file mode 100644 index 0000000..5bb9f1e --- /dev/null +++ b/4. web-app-architecture/2. express-js.md @@ -0,0 +1,79 @@ +# Express JS + +- Hello World with ExpressJS - [https://expressjs.com/en/starter/hello-world.html](https://expressjs.com/en/starter/hello-world.html) +- Video - ExpressJS Crash Course - [https://www.youtube.com/watch?v=L72fhGm1tfE](https://www.youtube.com/watch?v=L72fhGm1tfE) +- Writing Middleware - [https://expressjs.com/en/guide/writing-middleware.html](https://expressjs.com/en/guide/writing-middleware.html) + +## Project - IPL Project II + +Instructions: +**For this part, create a new branch called `webapp` in your previously created IPL Project repository and make commits in it.** + +Use a static webserver to serve your output JSON files. ( Remember your CLI drills on how to start a static server? ) + +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/) + + +Directory structure: + +- src/ + - server/ + - ipl.js + - index.js + - **public**/ + - output + - matchesPerYear.json + - ... + - index.html + - style.css + - data/ + - matches.csv + - deliveries.csv +- package.json +- package-lock.json +- .gitignore + +### API Design Guidelines + +### HTTP Drills II +On a separate branch, convert your http-drill-1 project to use expressjs. + +### Express Error Handlers + +Use google and do the following: + +1. Understand what the default error handler is +2. Learn how to setup a custom error handler +3. Learn how to setup a 404 error handler + +### Git Merge Drill 1 + +**DO NOT ATTEMPT THIS BY YOURSELF** + +[Ping your mentor and ask about this](https://gitlab.com/mountblue/cohort-js-common/express-merge-conflicts) + + +## Authentication + +### JWT- JSON Web Token + +- [Authentication and Authorization with JWTs in Express.js](https://stackabuse.com/authentication-and-authorization-with-jwts-in-express-js/) +- [Technical Introduction to JSON Web Tokens](https://jwt.io/introduction/) +- [JSON Web Tokens (JWTs) in Express.js](https://www.digitalocean.com/community/tutorials/nodejs-jwt-expressjs) +- Video - [https://www.youtube.com/watch?v=7nafaH9SddU](https://www.youtube.com/watch?v=7nafaH9SddU) + +## Loggers + +### What is a logger? + +Why not console.log +https://www.twilio.com/blog/guide-node-js-logging + +Log Levels +https://blog.logrocket.com/node-js-logging-best-practices/ + +Implement: +https://github.com/winstonjs/winston + +### What is a log shipper? +https://sematext.com/blog/logging-libraries-vs-log-shippers/ diff --git a/4. web-app-architecture/web-app.png b/4. web-app-architecture/web-app.png new file mode 100644 index 0000000..b294f40 Binary files /dev/null and b/4. web-app-architecture/web-app.png differ diff --git a/4. web-app-architecture/web-server-vs-application-server.png b/4. web-app-architecture/web-server-vs-application-server.png new file mode 100644 index 0000000..111f596 Binary files /dev/null and b/4. web-app-architecture/web-server-vs-application-server.png differ diff --git a/5. databases/1. databases.md b/5. databases/1. databases.md new file mode 100644 index 0000000..2a6adb8 --- /dev/null +++ b/5. databases/1. databases.md @@ -0,0 +1,245 @@ +# Databases + +## 1. Introduction + +### Types of Databases + +- Flat File Databases - [https://www.youtube.com/watch?v=vAA1VVExV5Q](https://www.youtube.com/watch?v=vAA1VVExV5Q) +- What is a database - [https://www.youtube.com/watch?v=Tk1t3WKK-ZY](https://www.youtube.com/watch?v=Tk1t3WKK-ZY) + +### Setting up Database in Local Machine + +Setting up MySQL 8 + +[Installing on Ubuntu](https://linuxize.com/post/how-to-install-mysql-on-ubuntu-18-04/) + +[Installing on Mac](https://dev.mysql.com/doc/mysql-osx-excerpt/5.7/en/osx-installation-pkg.html) + +[Installing on Windows](https://www.liquidweb.com/kb/install-mysql-windows/) + +Optional : MySQL Workbench + +## 2. Relational Databases & SQL + +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. + +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/) + +- Fetching data with SELECT +- Queries with constraints using WHERE +- Filtering and sorting +- JOINS +- NULL values +- Creating tables with CREATE +- Adding data to a table with INSERT +- Changing existing data in a table with UPDATE +- Removing data from a table with DELETE + +### NULL Values + +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. + +### SQL Syntax Differences + +SQL, like most programming and scripting languages, has a standard definition for how it should work. + +From Wikipedia, +> 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. + +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. + +Another reason is that the SQL standard is vast and often covering just the mandatory standard features in a compliant way is difficult. + +Because of these differences, some relational database systems are known to be more standards compliant` than others. + +### Comparison of RDBMS (Relational Database Management System) + +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. + +### Database Design and Data Normalization + +[https://www.youtube.com/watch?v=tR_rOJPiEXc](https://www.youtube.com/watch?v=tR_rOJPiEXc) + +### Database Design Drills + +Normalize Each Of The Following Tables + +For each task, create a separate `.sql` file with the create statements for the tables in a GitLab repository and submit the repo. + +**DO NOT SUBMIT mysqldump files**. You have to create the tables in the SQL files and submit them directly. + +#### Task 1: BRANCH + +- Branch# +- Branch_Addr +- ISBN +- Title +- Author +- Publisher +- Num_copies + +#### Task 2: CLIENT + +- Client# +- Name +- Location +- Manager# +- Manager_name +- Manager_location +- Contract# +- Estimated_cost +- Completion_date +- Staff# +- Staff_name +- Staff_location + +#### Task 3: PATIENT + +- Patient# +- Name +- DOB +- Address +- Prescription# +- Drug +- Date +- Dosage +- Doctor +- Secretary + +#### Task 4 :DOCTOR + +- Doctor# +- DoctorName +- Secretary +- Patient# +- PatientName +- PatientDOB +- PatientAddress +- Prescription# +- Drug +- Date +- Dosage + +## 3. Using SQL with NodeJS + +### Which npm package to choose to connect to the database server? + +We choose npm packages to use in our projects based on the following criteria: + +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. +2. `Last publish` date - The sooner the better because it means that it is still in active development +3. `Documentation` - Good documentation will have a quick start guide, API documentation with parameters and return values as well as sample code. + +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: + +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. +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. +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. +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. +5. If you want to write raw SQL queries, ensure that the library allows you to do that and is not primarily an ORM. + +### ENV Variables and Connection Configuration + +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`. + +Common environments that you will be exposed to are as follows: + +* Development environment + + This usually refers to the machine on which you are writing code and building functionality for your projects. + + `NODE_ENV` usually refers to `development` or `dev` or `undefined` when working in this environment. + +* Production environment + + 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. + + `NODE_ENV` usually refers to `production` when working in this environment. + + 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. + +* Staging environment + + 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. + + `NODE_ENV` usually refers to `staging` when working in this environment. + + Usually, there are no optimizations that occur when the value is set to this so that errors can be easily traced if they occur. + +* Testing environment + + 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. + + `NODE_ENV` usually refers to `testing` when working in this environment. + + 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. + +#### Setting Environmental Variables + +Learn how to set environmental variables by reading [this article](https://linuxize.com/post/how-to-set-and-list-environment-variables-in-linux/) + +#### How To Manage Configuration For Different Environments? + +Because we have different possible environments, we have to configure our code to connect to different database in each of these environments. + +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. + +Similarly, when running tests, we would not want tests to run on live data from customers directly on production. + +In order to manage this difference in connection configuration for each of these environments, there are two ways we can go about doing it. + +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. + +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. + +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!** + +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. + +You can learn how to do both of these methods by following the instructions mentioned in the article below. + +## 4. Intermediate Topics + +- SQL Injection +- Pools and pooling + +## 5. ORM + +### What is an ORM? + +[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) + +[Popular ORMs for NodeJS](https://www.dunebook.com/best-node-js-orms/) + +### Advantages & Disadvantages of an ORM + +#### Advantages + +- Gives you a standard and consistent way to write SQL queries without worrying about code style. + +- Improves the speed of development. Your code also becomes easier to update, maintain, and reuse since you can write queries using native javascript objects. + +- Gives you the ability to protect your queries from SQL injection attacks. + +- You can write correct and optimized SQL code without worrying about the SQL language and how the queries have to be structured. + +- 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. + +- Most ORM Models use OOP, which means that you can extend and inherit from models and extend functionality easily. + +- Some ORMs let you switch between database vendors easily so porting between two different database systems becomes seamless. + + +#### Disadvantages + +- ORMs have their own syntax so learning that takes time. + +- Small misconfigurations in how you use the ORM can lead to massive performance issues. + +- 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. + +- Documentation for some ORMs is difficult to navigate even if they are the most commonly used libraries. + +### Sequelize ORM + +[https://www.npmjs.com/package/sequelize](https://www.npmjs.com/package/sequelize) diff --git a/5. databases/2. optional-practice.md b/5. databases/2. optional-practice.md new file mode 100644 index 0000000..97accd2 --- /dev/null +++ b/5. databases/2. optional-practice.md @@ -0,0 +1,58 @@ +# SQL + +## 1. Install and get familiar with PostgreSQL + +Follow the instructions given in this article +[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) + +## 2. Practice SQL + +### 2a. SQLBolt + +Complete [SQLBolt](https://sqlbolt.com/) 3 times. + +### 2b. PG Exercises + +Complete [PostgreSQL Exercises](https://pgexercises.com/) 3 times. (Recursive Queries are optional) + +## 3. Data Project - SQL Version + +Solve the IPL data problem, but this time with SQL, using PostgreSQL database. + +#### 1. Create DB, permissions etc. +Write a SQL script that creates a new user, and database. Make the user the owner of the db. + +#### 2. Clean up script +Write another SQL script that cleans up the user, and database created in the previous step. + +#### 3. Load CSV +Write a SQL script that loads CSV data into a table. + +#### 4. Solve the IPL problems +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. + +**Note:** the result in this case is not a graph but SQL Result Set. + +### Submission +As with previous projects ... + +1. Create a repository - `data-project-database`. +2. All the code for this assignment should be in that repo. +3. Supporting files like .gitignore, README.md should also be included. +4. The README should have all the info for your mentor to run the scripts. + +## 4. SQL Concepts - Technical Paper + +Write a technical paper in detail in markdown format + +Some concepts to understand for databases: +* ACID +* CAP Theorem +* Joins +* Aggregations, Filters in queries +* Normalization +* Indexes +* Transactions +* Locking mechanism +* Database Isolation Levels +* Triggers diff --git a/6. html-css/1. basics.md b/6. html-css/1. basics.md new file mode 100644 index 0000000..bcc811d --- /dev/null +++ b/6. html-css/1. basics.md @@ -0,0 +1,51 @@ +# HTML and CSS Basics + +## Do any 1 Tutorial + +- [https://www.udacity.com/course/intro-to-html-and-css--ud001](https://www.udacity.com/course/intro-to-html-and-css--ud001) +- [https://dash.generalassemb.ly/](https://dash.generalassemb.ly/) +- [https://learn.shayhowe.com/](https://learn.shayhowe.com/) +- [https://marksheet.io/](https://marksheet.io/) +- [https://www.internetingishard.com/html-and-css/](https://www.internetingishard.com/html-and-css/) + +## CSS Selectors + +- [https://www.educative.io/edpresso/what-are-css-selectors](https://www.educative.io/edpresso/what-are-css-selectors) +- [https://css-tricks.com/how-css-selectors-work/](https://css-tricks.com/how-css-selectors-work/) + +## Box Model + +[https://css-tricks.com/the-css-box-model/](https://css-tricks.com/the-css-box-model/) + +## Flexbox + +Resources: +- [CSS Flex Video](https://www.youtube.com/watch?v=JJSoEo8JSnc) +- [https://css-tricks.com/snippets/css/a-guide-to-flexbox/](https://css-tricks.com/snippets/css/a-guide-to-flexbox/) + +Play the games to practice: +- [https://flexboxfroggy.com/](https://flexboxfroggy.com/) +- [http://www.flexboxdefense.com/](http://www.flexboxdefense.com/) + +## Default Browser Styles + +This is a zine by Julia Evans. +![default stylesheets](./default-stylesheets.jpeg "default stylesheets") + +## Layout Drills + +[https://gitlab.com/mountblue/js/css-layout-drills](https://gitlab.com/mountblue/js/css-layout-drills) + +Create a [codepen](https://codepen.io/) collection with solutions for all problems and submit the Codepen collection URL + +NOTE: Each problem can have multiple solutions. Also, ignore the `div` numbers, they have been used for illustrations only. + +## Pricing Page Project + +**Instructions** +- Fork this repository: +[https://gitlab.com/mountblue/js/pricing-html-css](https://gitlab.com/mountblue/js/pricing-html-css) +- Clone it in your local machine +- **Make regular commits to your project** + +### Optionally use reset.css diff --git a/6. html-css/2. responsive-web-design.md b/6. html-css/2. responsive-web-design.md new file mode 100644 index 0000000..11eb564 --- /dev/null +++ b/6. html-css/2. responsive-web-design.md @@ -0,0 +1,35 @@ +# Responsive Web Design + +## Live Coding Tutorial + +[https://www.youtube.com/watch?v=Wm6CUkswsNw](https://www.youtube.com/watch?v=Wm6CUkswsNw) + +## Relative Units + +- [https://css-tricks.com/the-lengths-of-css/](https://css-tricks.com/the-lengths-of-css/) +- [https://css-tricks.com/building-resizeable-components-relative-css-units/](https://css-tricks.com/building-resizeable-components-relative-css-units/) + +## CSS Media Queries + +- [https://css-tricks.com/css-media-queries/](https://css-tricks.com/css-media-queries/) +- [https://css-tricks.com/logic-in-media-queries/](https://css-tricks.com/logic-in-media-queries/) + +## Responsive Drills + +[https://gitlab.com/mountblue/js/responsive-layout-drill](https://gitlab.com/mountblue/js/responsive-layout-drill) + +Create a Codepen collection with solutions and submit the collection URL + +## Project - EasyBank Landing Page + +Link to project: [https://gitlab.com/mountblue/js/easybank-landing-page](https://gitlab.com/mountblue/js/easybank-landing-page) + +- Fork the repository +- Clone it in your local machine +- **Make regular commits to your project** + +## Testing on your mobile + +You can use `ngrok` or `localtunnel` + +Video - [https://www.youtube.com/watch?v=DCxt9SAnkyc](https://www.youtube.com/watch?v=DCxt9SAnkyc) diff --git a/6. html-css/3. standard-design-practices.md b/6. html-css/3. standard-design-practices.md new file mode 100644 index 0000000..433f33d --- /dev/null +++ b/6. html-css/3. standard-design-practices.md @@ -0,0 +1,5 @@ +# Standard Design Practices + +- Commonly used design elements +- Providing feedback to the user +- Professional practices diff --git a/6. html-css/4. css-frameworks.md b/6. html-css/4. css-frameworks.md new file mode 100644 index 0000000..1a43ae6 --- /dev/null +++ b/6. html-css/4. css-frameworks.md @@ -0,0 +1,5 @@ +# CSS Frameworks + +- Popular Frameworks +- Common Terminology +- How to use a CSS Framework diff --git a/6. html-css/default-stylesheets.jpeg b/6. html-css/default-stylesheets.jpeg new file mode 100644 index 0000000..b3b8be0 Binary files /dev/null and b/6. html-css/default-stylesheets.jpeg differ diff --git a/6. html-css/html-css.md b/6. html-css/html-css.md new file mode 100644 index 0000000..6038b7f --- /dev/null +++ b/6. html-css/html-css.md @@ -0,0 +1,216 @@ +# HTML and CSS + +## 1. Basics + +Start with [Learn to Code HTML and CSS by Shay Howe](https://learn.shayhowe.com/) + +In particular read the following sections and complete the exercises. + +HTMl & CSS + +* Lesson 1: Building your first web page +* Lesson 2: Getting to know HTML +* Lesson 3: Getting to know CSS +* Lesson 4: Opening the Box Model +* Lesson 5: Positioning content + +Advanced HTML & CSS + +* Lesson 3: Complex Selectors +* Lesson 4: Responsive Web Design + +Resources for Web Development for any Topic: +[Mozilla Web Docs](https://developer.mozilla.org/en-US/) + +CSS Reference: +[A Visual Reference to CSS](https://cssreference.io/) + +### Optional Resources + +Do any 1, Refer others + +[https://www.udacity.com/course/intro-to-html-and-css--ud001](https://www.udacity.com/course/intro-to-html-and-css--ud001) + +[https://dash.generalassemb.ly/](https://dash.generalassemb.ly/) + +[https://learn.shayhowe.com/](https://learn.shayhowe.com/) + +[https://marksheet.io/](https://marksheet.io/) + +[https://www.internetingishard.com/html-and-css/](https://www.internetingishard.com/html-and-css/) + +## 2. CSS Selectors + +[https://www.educative.io/edpresso/what-are-css-selectors](https://www.educative.io/edpresso/what-are-css-selectors) + +[https://css-tricks.com/how-css-selectors-work/](https://css-tricks.com/how-css-selectors-work/) + +## 3. Box Model + +[https://css-tricks.com/the-css-box-model/](https://css-tricks.com/the-css-box-model/) + +## 4. Flexbox + +Resources: +- [CSS Flex Video](https://www.youtube.com/watch?v=JJSoEo8JSnc) +- [https://css-tricks.com/snippets/css/a-guide-to-flexbox/](https://css-tricks.com/snippets/css/a-guide-to-flexbox/) + +Play the games to practice: +- [https://flexboxfroggy.com/](https://flexboxfroggy.com/) +- [http://www.flexboxdefense.com/](http://www.flexboxdefense.com/) + + +## 5. Grid + +Resources: +- [CSS Grid Video](https://www.youtube.com/watch?v=jV8B24rSN5o) + +Play the game to practice: +- [CSS Grid Garden - Game](https://cssgridgarden.com/) + +## 6. CSS Units + +- [https://css-tricks.com/the-lengths-of-css/](https://css-tricks.com/the-lengths-of-css/) +- [https://css-tricks.com/building-resizeable-components-relative-css-units/](https://css-tricks.com/building-resizeable-components-relative-css-units/) + +## 7. CSS Specificity + +## 8. Layout Drills + +[https://gitlab.com/mountblue/js/css-layout-drills](https://gitlab.com/mountblue/js/css-layout-drills) + +Create a [codepen](https://codepen.io/) collection with solutions for all problems and submit the Codepen collection URL + +NOTE: Each problem can have multiple solutions. Also, ignore the `div` numbers, they have been used for illustrations only. + +## 9. CSS Media Queries + +- [https://css-tricks.com/css-media-queries/](https://css-tricks.com/css-media-queries/) +- [https://css-tricks.com/logic-in-media-queries/](https://css-tricks.com/logic-in-media-queries/) + +## 10. Responsive Drills + +[https://gitlab.com/mountblue/js/responsive-layout-drill](https://gitlab.com/mountblue/js/responsive-layout-drill) + +Create a Codepen collection with solutions and submit the collection URL + +## 11. Code Walkthrough of an Entire Project + +[https://www.youtube.com/watch?v=Wm6CUkswsNw](https://www.youtube.com/watch?v=Wm6CUkswsNw) + +## 12. Project I: Green Tree Initiative + +* Project Adobe XD wireframes - [Wireframes](https://xd.adobe.com/spec/a75faa97-2d9f-401c-6140-8fac4a6601aa-d16e/grid/) +* Project assets - [Assets](https://drive.google.com/drive/folders/1raP7YpOF4knQnX7UWOYJYoTU4KSGJAyy?usp=share_link) + +Build the two pages - home page and donation page. + +Get the layout and positioning right first before jumping into details. Link the pages among themselves for navigation. + +### Hosting + +Host your website on Netlify. + +### Some pointers: + +* Please work *mobile-first*. +* Mostly use flexbox or grid. +* Add README.md and .gitignore files to your repository. +* Make a common styles.css. Include it on each HTML page. Put the style classes here. They can be gradually reused. +* Structural CSS should be different for each page. +* 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. +* Try to work with high energy and complete things. + +### CSS Specific: + +* Always make the mobile resolution working first, then tablet, then webpage. +* Separate out classes for structure and style. +* Get the structure - layout and positioning right first before jumping into styling details. +* Use structural CSS (like flex and grid) in a way to avoid too much responsive logic. +* Link the pages among themselves for navigation. +* Use Flexbox and Grid as much as possible. Minimise use of positioning - relative or absolute. +* Use rem for font-size. Don't use em, px, vh or vw. +* Understand "in-the-flow" and "out-of-flow". +* Anything specific width, height, top, left, right, bottom, positioning: (absolute, fixed or float) can break the flow. Use when necessary e.g. overlapping elements. +* Try to avoid using width as much as possible. Use percentages for sections inside containers. +* Try to limit use of height wherever necessary. + +### Submission + +This section requires you to submit the following URLs: +1. URL of your hosted webpages +2. URL of the GitLab repo of this project. + +## 13. Technical Paper on HTML/CSS + +Write a technical paper. + +Concepts: + +* Box Model +* Inline versus Block Elements. Examples. +* Positioning: Relative/Absolute +* Common CSS structural classes +* Common CSS syling classes +* CSS Specificity +* CSS Responsive Queries +* Flexbox/Grid +* Common header meta tags +* Any other topic you think is important. + +Add references at the end. + +## 14. Optional Project I: Portfolio + +### Goal + +Build your portfolio website using your knowledge of HTML and CSS. The display should work in all resolutions. + +Use your knowledge of responsive media queries, CSS flex, and CSS grid for handling multi-column layouts. + +### Hosting + +Host your website on Netlify. + +### Submission + +This section requires you to submit the following URLs ... +1. URL of your hosted webpages +2. URL of the GitLab repo of this project. + +## 15. Optional Project II: Themed E-Commerce Website + +### Goal + +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. + +**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. + +### Project Description + +The website should have 5 pages: + +1. Home Page +2. Item listing page +3. Single Item Page +4. Cart Page (hard code the items in the cart) +5. Checkout Page + +Some pointers: + +* Please work *mobile-first*. +* Use of a CSS framework like Bootstrap is encouraged but not required. +* Add README.md and .gitignore files to your repository. +* Make a common styles.css. Include it on each HTML page. Put the style classes here. They can be gradually reused. +* 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. +* Try to work with high energy and complete things. + +### Hosting + +Host your website on Netlify. + +### Submission + +This section requires you to submit the following URLs ... +1. URL of your hosted webpages +2. URL of the GitLab repo of this project. diff --git a/7. javascript-dom/1. dom.md b/7. javascript-dom/1. dom.md new file mode 100644 index 0000000..bb20153 --- /dev/null +++ b/7. javascript-dom/1. dom.md @@ -0,0 +1,877 @@ +# DOM + +## 1. What is DOM? + +- Programming interface for HTML +- A representation of HTML that can be accessed using Javascript + +#### How does it get created? + +- When a web page is loaded, the browser creates the DOM for that specific page +- This allows for the creation of dynamic web pages where users can interact with the page + +#### DOM under the hood +The structure of the DOM uses something called a tree, where the topmost node is the ***document*** object. + +![dom](./dom.png "dom") + +#### Using the *document* object + +- the ***document*** object represents the web page that has been loaded +- it acts as the “starting point” for access to the DOM. + +#### The things we can do with the ***document*** object +- Finding Elements +- Creating new elements +- Updating elements +- Changing properties of an elements +- Listening to events like click, hover, etc + +### Element Selection in DOM + +#### How to select elements in DOM + +To access the DOM, we make use of the document object. + +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. + +#### Available Methods: +- **getElementById:** + + **getElementById** accepts a string which is the name of an ***id*** in the DOM and it finds the first matching id. + + ``` + document.getElementById("div1"); + ``` + We get back a special object called an **HTMLElement**. + + 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) + +- **getElementsByTagName** + + **getElementsByTagName** accepts a string which is the ***HTML tags*** (like div, p, a, li, ul etc) in the DOM. + + It returns a list of all of the elements that match the string passed to the function + ``` + document.getElementByTagName("p"); + ``` + This function returns an **HTMLCollection** to us! + + It looks a lot like an array, and you can access it at a specific index or use a for loop + + However, you can not use common methods like ***push***, ***pop***, ***indexOf*** or ***includes*** + +- **getElementsByClassName** + + **getElementsByClassName** accepts a string which is the name of an element in the DOM. + + It returns a list of all of the elements that have a class attribute, which matches the string passed to the function + + ``` + document.getElementsByClassName("p2"); + ``` + + Just like *getElementsByTagName*, we get back a special kind of array called an HTMLCollection. + + Read more about [HTMLCollection](https://developer.mozilla.org/en-US/docs/Web/API/HTMLCollection) + +- **querySelector** + + **querySelector** accepts a string that is a valid CSS selector (I hope you remember them!!!). + It returns the **first element** that matches the CSS selector passed to the function + + ```html + document.querySelector("#div1"); + + document.querySelector("p.p2"); + ``` + + Just like *getElementById*, this function returns a special HTMLElement object to us. + + + + +- **querySelectorAll** + + + **querySelectorAll** accepts a string that is a valid CSS selector. +It returns **all the elements** that matches the CSS selector passed to the function. + ``` + document.querySelectorAll("div"); + + document.querySelectorAll("ul .nav-links"); + ``` + + This function returns a **NodeList** to us! + + It looks a lot like an array, and you can access it at a specific index or use a for loop + + However, you can not use common methods like ***push***, ***pop***, ***indexOf*** or ***includes*** + + It’s almost identical to an HTMLCollection except it can include special kinds of nodes. + + Read more about [NodeList](https://developer.mozilla.org/en-US/docs/Web/API/NodeList) + + +[Difference b/w NodeList & HTMLCollection](https://dev.to/jharteaga/difference-between-htmlcollection-and-nodelist-25bp) + +#### Crash Course + +Check out the below playlist. +[https://www.youtube.com/watch?list=PLillGF-RfqbYE6Ik_EuXA2iZFcE082B3s&v=0ik6X4DJKCc](https://www.youtube.com/watch?list=PLillGF-RfqbYE6Ik_EuXA2iZFcE082B3s&v=0ik6X4DJKCc) + +## 2. DOM Manipulation + +### Modifying Elements in the DOM + +#### Accessing Text + +The easiest way to access the text of an element is to use ***innerText*** + +```html +
+
Hello World!
+
+``` +```js +const greeting = document.getElementById("greeting") + +console.log(greeting.innerText) // "Hello World!" +``` + +#### Modifying Text + +If you need to change any text, you can assign a new value to the innerHTML: +```js +const greeting = document.getElementById("greeting") + +greeting.innerText = "It's changed !!!" +``` + +#### Using textContent + +Another common way to access and modify text is to use the ***textContent*** property +```js +const greeting = document.getElementById("greeting") + +greeting.textContent = "It's changed !!!" +``` +
+ +**So what’s the difference?** + +There are quite a few small differences: + +- innerText is aware of the rendered appearance of text, while textContent is not. +- textContent gets the content of all elements, including ` + + +``` + +Take a look at some parent, child, and sibling element relationships. + +We will be focusing specifically on the `
` element. + +#### Accessing a parent element +If you want to access the parent element of another element, you can use the ***parentElement*** method. +```js +const foundDiv = document.querySelector("div") + +foundDiv.parentElement //
+``` +#### Accessing the children of an element +If you want to access the child elements of another element, you can use the ****children**** method. +```js +foundDiv.children //HTMLCollection(2) [p, ul] +foundDiv.firstElementChild //

Here is a paragraph inside a div!

+foundDiv.lastElementChild //
    +``` + +#### Accessing the siblings of an element +If you want to access the previous sibling or next sibling element of another element, you can use the ***previousElementSibling*** or ***nextElementSibling*** method. +```js +foundDiv.previousElementSibling //

    Here is a main heading!

    +foundDiv.nextElementSibling //
    Here is the second div!
    +``` + +#### Text Nodes + +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*** + +More about [Text Node](https://stackoverflow.com/questions/17195868/what-is-a-text-node-its-uses-document-createtextnode) + +### Nodes VS Elements +- 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 +- Everything in the DOM is a **node**, some nodes are not actually HTML elements, but text or even comments! +- With most of the common traversal methods, you will not need to worry about text nodes +- 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. + +Know more about [NodeTypes](https://developer.mozilla.org/en-US/docs/Web/API/Node/nodeType) + +Video - [https://www.youtube.com/watch?v=mPd2aJXCZ2g](https://www.youtube.com/watch?v=mPd2aJXCZ2g) + +## 3. Javascript Events + +#### What is an event??? +DOM events are “actions” that occur as a result of something the user or the browser does. + +We can use JavaScript to execute code when these kinds of “events” happen. + +#### What Kinds Of Events Do We Have??? +- clicking on something +- hovering over something with the mouse +- pressing certain keys +- when the DOM has loaded +- when a form is submitted + +We write code that listens for events - and react accordingly! + +This is commonly called [Event Driven Programming](https://www.valentinog.com/blog/event/) + +#### How do we do it??? +We have three options: + +- Attach the name of the function to the element in HTML +- Attach the name of the function to an element in JavaScript +- Use the addEventListener method + +**Attaching The Name Of The Function** +```html +

    Hello World

    +``` +```js +function runClickHandler(){ + console.log("You just clicked the h1 element!"; +}) +``` +
    + +**Adding in Javascript** +```js +const h1 = document.querySelector("h1"); + +h1.onclick = function(){ + console.log("You just clicked the h1 element!"; +} +``` +
    + +**Using addEventListener** +```js +const h1 = document.querySelector("h1"); + +h1.addEventListener("click", function(){ + console.log("You just clicked the h1 element!"; +}) +``` + +#### Which One Should We Use??? +We’re going to go with addEventListener - here’s why: + +- It gives us the most flexibility around our event listeners +- It avoids writing any inline code in our HTML and keeps our HTML and JS separate +- This is commonly called “Separation of Concerns” + +#### Important: Waiting For The Dom To Load!!! +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 ` + + +``` +```js +// listen for the keypress everywhere +document.addEventListener("keypress", function(event) { + if (event.key === "a") { + alert("you just pressed the 'a' key!"); + } +}); +``` + +### Adding Multiple Event Listeners +It’s very common that you will want to add multiple event listeners on elements + +Let’s see an example: +```html + +

    See your friend list!

    +
      +
    • Thor
    • +
    • Iron-man
    • +
    • Captain America
    • +
    + + +``` +```js +const buttons = document.querySelectorAll("button"); + +for (let button of buttons) { + button.addEventListener("click", function(event) { + event.target.parentElement.remove(); + }); +} +``` +Everything seems to be working! + +**What happens when we want to add new elements?** +```html + +

    See your friend list!

    +
      ...
    +
    + + + +
    + + +``` +```js +const form = document.querySelector("form"); +const friendList = document.querySelector("#friend-list"); + +const buttons = document.querySelectorAll("li button"); + +for (let button of buttons) { + button.addEventListener("click", function(event) { + event.target.parentElement.remove(); + }); +} + +form.addEventListener("submit", function(event) { + event.preventDefault(); + const newFriendInput = document.querySelector("#first-name"); + const newLi = document.createElement("li"); + const newButton = document.createElement("button"); + newLi.innerText = newFriendInput.value; + newButton.innerText = "Remove"; + + newLi.append(newButton); + friendList.append(newLi); + form.reset(); +}); +``` +
    + +**It doesn’t work!!!** + +The issue here is that our event listener only works for elements **currently** on the page + +There are two ways we can fix this: + +- Adding the event listener when we create elements +- Event Delegation + +Let’s start with adding an event listener when we create + +**Adding the listener when we create** +```js +const form = document.querySelector("form"); +const friendList = document.querySelector("#friend-list"); + +form.addEventListener("submit", function(event) { + event.preventDefault(); + const newFriendInput = document.querySelector("#first-name"); + const newLi = document.createElement("li"); + const newButton = document.createElement("button"); + newLi.innerText = newFriendInput.value; + newButton.innerText = "Remove"; + + newButton.addEventListener("click", function(event) { + event.target.parentElement.remove(); + }); + + newLi.append(newButton); + friendList.append(newLi); + form.reset(); +}); +``` +This will work, but it’s not the most efficient approach + +We’re adding an event listener for every single button inside of each `
  • ` + +This means if we had 1,000,000 friends, we’d have 1,000,000 listeners! + +We can fix this using **event delegation** + +#### Event Delegation +The idea behind event delegation is that we make a parent element the “delegate” + +In our case, the parent element is the `
      ` element + +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 + +**How to do better using event delegation** +```js +friendList.addEventListener("click", function(event) { + if (event.target.tagName === "BUTTON") { + event.target.parentElement.remove(); + } +}); +``` +Exact same behavior with only one event listener! + +#### Event Bubbling And Capturing +The process of an event moving from the place it is clicked to its target is called **capturing** + +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. + +This is called **bubbling**. + +Read more on [Event Bubbling and Capturing](https://medium.com/@vsvaibhav2016/event-bubbling-and-event-capturing-in-javascript-6ff38bec30e) + +### Removing Event Listeners +Sometimes after you add an event listener, you will want to remove it. + +Some examples of this include: + +- A game is over and no more events should be registered +- You can no longer drag and drop something into a part of the page +- You do not want the user submitting any more information + +
      + +**How it works** + +We can use the removeEventListener function to remove any event listeners + +This **can not** be called on multiple elements +```js +let buttons = document.getElementsByTagName("button"); + +buttons.removeEventListener("click", function(){ + alert("You just clicked a button"); +}); +``` +The code above will not work!!! + +Maybe we can just add it to an element individually like this: +```js +for(let button of buttons){ + button.removeEventListener("click", function(){ + alert('You just clicked on a button!'); + }); +} +``` + +But this won’t work either!!! :P + +**Removing Event Listeners Correctly** + +removeEventListener needs a reference to the name of the function to remove +```js +function alertData(){ + alert("You just clicked a button"); +} + +for(let button of buttons){ + button.removeEventListener("click", alertData); +} +``` +**Note:** anonymous functions will not work here! + +### Data attributes +When creating elements and HTML pages, it’s very common that you might want to add some metadata or additional information about elements + +These are not things that the user should see, but accessible information in CSS and JavaScript + +Instead of placing this in ***id*** or ***class***, we can create custom attributes called **data attributes** + +These attributes start with data- and then anything you would like. You can read them easily in CSS and JavaScript + +**Example:** +```html + + + +
        +
      • Tesla +
      • Honda +
      • Ford +
      • Toyota +
      + + + +``` +```js +const ul = document.querySelector("ul"); + +ul.addEventListener("click", function(event) { + const selectedElement = event.target; + console.log("see all data attributes", selectedElement.dataset); + console.log( + "see one data attribute", + selectedElement.getAttribute("data-model") + ); +}); +``` +
      + +Read more about [Data attributes](https://css-tricks.com/a-complete-guide-to-data-attributes/) + +## 4. Web Storage APIs + +The **Web Storage API** provides mechanisms by which browsers can store key/value pairs, in a much more intuitive fashion than using cookies. + +Video - [https://www.youtube.com/watch?v=MOd5cTJ6kaA](https://www.youtube.com/watch?v=MOd5cTJ6kaA) + +### Introduction +- [https://flaviocopes.com/web-platform/](https://flaviocopes.com/web-platform/) +### Web storage +- [https://flaviocopes.com/web-storage-api/](https://flaviocopes.com/web-storage-api/) +- [https://javascript.info/data-storage](https://javascript.info/data-storage) +### Cookies vs localStorage vs sessionStorage +- [https://www.youtube.com/watch?v=AwicscsvGLg](https://www.youtube.com/watch?v=AwicscsvGLg) + +## 5. Important Concepts to Understand +- Why using alert and prompt is bad practice +- 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) +- 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) diff --git a/7. javascript-dom/2. browser.md b/7. javascript-dom/2. browser.md new file mode 100644 index 0000000..214ff06 --- /dev/null +++ b/7. javascript-dom/2. browser.md @@ -0,0 +1,24 @@ +# Browsers + +## How does a Browser Work? + +How Browser Rendering Works + +Text: +[https://blog.logrocket.com/how-browser-rendering-works-behind-the-scenes-6782b0e8fb10/](https://blog.logrocket.com/how-browser-rendering-works-behind-the-scenes-6782b0e8fb10/) + +Video: +[https://www.youtube.com/watch?v=0IsQqJ7pwhw](https://www.youtube.com/watch?v=0IsQqJ7pwhw) + + +## Developer Tools + +Google Chrome Developer Tools Crash Course +[https://www.youtube.com/watch?v=x4q86IjJFag](https://www.youtube.com/watch?v=x4q86IjJFag) + +### Debugging Tips + +- [The 16 JavaScript debugging tips you probably didn’t know](https://raygun.com/learn/javascript-debugging-tips) +- Debugging in the browser - [https://javascript.info/debugging-chrome](https://javascript.info/debugging-chrome) +- Understand Client Side VS Server Side Rendering + diff --git a/7. javascript-dom/3. negative-testing.md b/7. javascript-dom/3. negative-testing.md new file mode 100644 index 0000000..e7d236f --- /dev/null +++ b/7. javascript-dom/3. negative-testing.md @@ -0,0 +1,3 @@ +# Negative Testing Web Apps + +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/) diff --git a/7. javascript-dom/4. client-server-architecture.md b/7. javascript-dom/4. client-server-architecture.md new file mode 100644 index 0000000..51db804 --- /dev/null +++ b/7. javascript-dom/4. client-server-architecture.md @@ -0,0 +1,11 @@ +# Client Server Architecture + +Articles +- [https://www.pagecloud.com/blog/website-terminology](https://www.pagecloud.com/blog/website-terminology) +- [https://engineering.videoblocks.com/web-architecture-101-a3224e126947](https://engineering.videoblocks.com/web-architecture-101-a3224e126947) + +Check the Slides on Slideshare for Client Server Architecture [https://www.slideshare.net/secret/wYOQgHZBO0B1qm](https://www.slideshare.net/secret/wYOQgHZBO0B1qm) + +Watch the video below for the recorded session. (55 minutes 59 seconds) + +[https://www.youtube.com/watch?v=h_7XxdbnkAg](https://www.youtube.com/watch?v=h_7XxdbnkAg) diff --git a/7. javascript-dom/dom.png b/7. javascript-dom/dom.png new file mode 100644 index 0000000..c89e5c2 Binary files /dev/null and b/7. javascript-dom/dom.png differ diff --git a/8. react/babel.png b/8. react/babel.png new file mode 100644 index 0000000..bd9ec21 Binary files /dev/null and b/8. react/babel.png differ diff --git a/8. react/react.md b/8. react/react.md new file mode 100644 index 0000000..6a8008b --- /dev/null +++ b/8. react/react.md @@ -0,0 +1,91 @@ +# React + +## Prerequisites + +- JS Library vs Framework +- 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) +- Webpack - [https://ui.dev/webpack/](https://ui.dev/webpack/) +- Polyfills - [https://ui.dev/compiling-polyfills/](https://ui.dev/compiling-polyfills/) +- Babel - [https://babeljs.io/repl](https://babeljs.io/repl) + +### Babel & Webpack with React + +Go through the following articles for a good understanding of the topic. You do not need to implement anything. + +- [JavaScript Transpilers: What They Are & Why We Need Them](https://scotch.io/tutorials/javascript-transpilers-what-they-are-why-we-need-them) +- [Using Vite to create a new React app](https://flaviocopes.com/vite-react-app/) +- [React Developer Tools + ](https://react.dev/learn/react-developer-tools) + +## ReactJS + +### 1. React Crash course + +- [Programming with Mosh](https://youtu.be/SqcY0GlETPk?si=PZzD9Mo7SKKEU6OB) - This is a simple introduction to React +- [Traversy Media](https://youtu.be/LDB4uaJ87e0?si=aDVqcrFVw0tzrUuZ) - This includes introduction and more stuff like routing etc. + +### 2. React Mini Projects (Build any two) + +- [Video with 25 projects](https://youtu.be/5ZdHfJVAY-s?si=DgQvMSzLXYTGhrgq) +- [React Official tutorial](https://react.dev/learn/tutorial-tic-tac-toe) + +### 4. Read the following sections from official docs and practice the challenges at the end of each sub-section + +- [Describing the UI + ](https://react.dev/learn/describing-the-ui) +- [Adding Interactivity](https://react.dev/learn/adding-interactivity) +- Also go through this [The Interactive Guide to Rendering in React + ](https://ui.dev/why-react-renders) + > This is a good reference for all the react hooks - [Codevolution playlist](https://www.youtube.com/playlist?list=PLC3y8-rFHvwisvxhZ135pogtX7_Oe3Q3A) + +### 5. REST Countries project + +Points to focus on when building this project + +- Code quality - spell check, code convetions, code formatting - eslint and prettied enabled +- Separating out different components +- Building reusable components if feasible +- Ensuring component state doesn't contain derived data +- Controlled vs Un-controlled components +- Repo https://gitlab.com/mountblue/js/rest-countries + +### 6. Read the following sections from official docs and practice the challenges at the end of each sub-section + +- [Managing State + ](https://react.dev/learn/managing-state) +- [Escape Hatches + ](https://react.dev/learn/escape-hatches) + +### 7. Trello project + +Points to focus on when building this project + +- Code quality - spell check, code convetions, code formatting - eslint and prettied enabled +- Separating out different components +- Building reusable components if feasible +- Ensuring component state doesn't contain derived data +- Controlled vs Un-controlled components +- Project description: https://rentry.co/nsqq2wos + +### 8. useReducer + +Implement useReducer for Trello project in a different git branch. Understand the difference b/w useState vs useReducer vs useContext + +### 9. Redux toolkit + +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: + +- Should we move all the state to redux ? +- What kind of state should we not move to redux ? + +## React Router + +#### Blogs + +- https://ui.dev/react-router-tutorial +- https://www.freecodecamp.org/news/how-to-use-react-router-version-6/ + +#### Video tutorials + +- https://youtu.be/59IXY5IDrBA?si=WL-JWMQ_O5RMg5I_ +- https://youtu.be/Ul3y1LXxzdU?si=_xvwmQIk4asM2txz diff --git a/9. redux/redux.md b/9. redux/redux.md new file mode 100644 index 0000000..8f64df3 --- /dev/null +++ b/9. redux/redux.md @@ -0,0 +1,9 @@ +# Redux + +## Introduction to Redux + +[https://www.youtube.com/watch?v=poQXNp9ItL4](https://www.youtube.com/watch?v=poQXNp9ItL4) + +## React-Redux Library + +[React-Redux Guide](https://www.valentinog.com/blog/redux/) diff --git a/README.md b/README.md index 62acf0e..b9607c6 100644 --- a/README.md +++ b/README.md @@ -1,261 +1,20 @@ -# Full Stack Web Development Learning Path +# JavaScript Full Stack Path + +Sequence of topics (tentative): + +- Basics: + - Development Setup + - Command Line Interface - CLI + - Git + - Markdown + - Computer Networks +- JavaScript +- Asynchronous JavaScript +- Web App Architecture +- Databases +- HTML and CSS +- JavaScript DOM +- React +- Redux +- Searching -## Command Line Basics - -**Session** on CLI. - -[Command Line Crash Course](https://learnpythonthehardway.org/book/appendixa.html) - -[Commonly Used Linux Commands](https://www.thegeekstuff.com/2010/11/50-linux-commands/) - -## Version Control Systems - -**Session** on Git and Github - -[How to use Git and Github - Udacity](https://in.udacity.com/course/how-to-use-git-and-github--ud775) - -[Resources and Practice](https://try.github.io/levels/1/challenges/1) - Practice the **Learn Git branching** section - -## HTML and CSS - -Start with [Learn to Code HTML and CSS by Shay Howe](https://learn.shayhowe.com/) - -In particular read the following sections and complete the exercises. - -HTMl & CSS - -* Lesson 1: Building your first web page -* Lesson 2: Getting to know HTML -* Lesson 3: Getting to know CSS -* Lesson 4: Opening the Box Model -* Lesson 5: Positioning content - -Advanced HTML & CSS - -* Lesson 3: Complex Selectors -* Lesson 4: Responsive Web Design - -Resources for Flex and Grid Layouts - -[CSS Flex Video](https://www.youtube.com/watch?v=JJSoEo8JSnc) - -[CSS Grids](https://www.youtube.com/watch?v=jV8B24rSN5o) - -### Projects: - -**Responsive Portfolio Website** - - Build two versions of a portfolio website. With and without the Bootstrap CSS framework. These can be two different files in the same repository. You're required to submit the following: - - Link to repository. The repository to be named portfolio-(name) example portfolio-john - - Live URL containing links to both versions of the portfolio. - - - In an index.html provide links to both the files. - * portfolio.html - * portfolio-bootstrap.html - -#### CSS Reference - -[A Visual Reference to CSS](https://cssreference.io/) - -**Themed Ecommerce Website** - - Pick a website or theme of your choice and build it without looking at the source code. - - - Submit the URL to the Git repository and the URL where the project is deployed. Please name the repository theme-(name) e.g. (theme-john) - - -## Web Architecture Overview - -**Session** on Web Architecture Overview - -## JavaScript and Ecosytem - -### JavaScript Basics -[Introduction to JavaScript - Udacity](https://in.udacity.com/course/intro-to-javascript--ud803) - -### ECMAScript 6 Basics -[Introduction to ES6 - Udacity](https://www.udacity.com/course/es6-javascript-improved--ud356) - -### Recommended Projects: - -**ToDo List in JavaScript** - - Implement a todo list with ordering with persistence using localStorage - -**Memory Game in JavaScript** - - Create a Memory Game in JavaScript capturing the total number of moves and time taken to complete the game. - -**Chess Game in JavaScript** (Advanced) - - Build a 2 player chess game in JavaScript using principles of object oriented programming, game state and game loop. - -**Session**: Recap on Functions, Scope and Callbacks. - -**Session** on JavaScript Environment Setup - JS, Node, NPM. Introduction to JavaScript. - -### Developer Tools - -[Getting Started with Developer Tools](https://developers.google.com/web/tools/chrome-devtools/) - -### Jquery - -[Introduction to Jquery - Udacity](https://in.udacity.com/course/intro-to-jquery--ud245) - -**ToDo List in Jquery** - - Implement a todo list with ordering in Jquery - -**Session** Recap Jquery - -### MongoDB and Express - -[Introduction to MongoDB](https://www.youtube.com/playlist?list=PL4cUxeGkcC9jpvoYriLI0bY8DOgWZfi6u) - -**Session** on databases - -**Session** on JS Utility functions - -**Full Stack ToDo List** - - Todo List with data storage in backend with Express API and MongoDB as database. - -### REST - -1. Basics of [REST APIs](https://en.wikipedia.org/wiki/Representational_state_transfer) -2. [RESTful Design](https://blog.philipphauer.de/restful-api-design-best-practices/) - Best practices to use -3. [Building good APIs](http://conversation.bigbinary.com/) - Using appropriate HTTP Response codes - -**Session** on REST - -### Configuring Node and Mongo for REST - -[Using Mongo, Express and REST](https://www.youtube.com/playlist?list=PL4cUxeGkcC9jBcybHMTIia56aV21o2cZ8) - -[Mongoose](http://mongoosejs.com/) - -**Session** on Mongoose. - -### Data Project - -Get the [IPL Dataset](https://www.kaggle.com/manasgarg/ipl) - - In this data assignment you will transform raw data from IPL into graphs that will convey some meaning / analysis. For each part of this assignment you will have 2 parts - - - - Download both csv files from https://www.kaggle.com/manasgarg/ipl - - Part 1 - - Code a javascript program that will transform the raw csv data to a json file which contains only the data necessary and in a format suitable for plotting in the next step and plot with highcharts. - - Generate the following plots ... - - 1. Plot the number of matches played per year of all the years in IPL. - 2. Plot a stacked bar chart of matches won of all teams over all the years of IPL. - 3. For the year 2016 plot the extra runs conceded per team. - 4. For the year 2015 plot the top economical bowlers. - 5. Discuss a "Story" you want to tell with the given data. As with part 1, prepare the JSON file and plot with highcharts. - - Part 2 - - Create a Node Web API with MongoDB as the backend. Solve the same above problems by getting data using MongoDB queries. - - -### Unit Testing in JavaScript - -[JavaScript Testing - Udacity](https://in.udacity.com/course/javascript-testing--ud549) - -**Session** Unit testing - -### Time and Space Complexity - -[Time Complexity Videos - mycodeschool](https://www.youtube.com/watch?v=8syQKTdgdzc) - -Create an account on [Interviewbit](https://www.interviewbit.com) and solve the practice problems in the Time Complexity section. - -[Measuring execution time in JavaScript](https://blog.mariusschulz.com/2013/11/22/measuring-execution-times-in-javascript-with-consoletime) - -**NavTree Project in Jquery** - - Repository name: navtree-(name) Example navtree-john - - - Build a hierarchical, navigable tree structure using jQuery. The tree structure should be at least 3 levels deep. - - For example: - - Depth 0 - - -- Depth 1 - - -- Depth 2 - - It should expand and minimize to reveal and hide nested nodes. Do not use an existing library to build the tree structure. - - Please use the IPL dataset that you had previously used for the Visualisation assignment. An example hierarchy could be - - Year > Team > Players - - When the last entity is selected, show a stat relevant to that identity on the page. This can either be a visualisation or a table. - - -### Object Oriented JavaScript - -[Introduction to Object Oriented JavaScript](https://classroom.udacity.com/courses/ud711) - Only complete scopes, closures, 'this' keyword and prototype chains. - -**Session**: Object and Prototypes. - -## React and Ecosytem - -### Build Tools - -[Webpack and Babel](https://stanko.github.io/webpack-babel-react-revisited/) - -### React - -[Introduction to React - Techsith](https://www.youtube.com/watch?v=bUTsVY6VUQA&list=PL7pEw9n3GkoVPFsAylfniAT3QQcjWGl5C) - -**Session** Recap React - -**ToDo List** - - Implement a todo list with ordering which interacts with a backend Web Server in Node or Django with each update. - -**NavTree Project in React** - - Implement the NavTree structure using the React library. - - Name the project navtree-react-(name) - -### Redux - -[Introduction to Redux - Academind](https://www.youtube.com/watch?v=YmGm-qwbJdc&index=9&list=PL55RiY5tL51rrC3sh8qLiYHqUV3twEYU_) - -Advanced: - -[Getting Started with Redux - Egghead](https://egghead.io/courses/getting-started-with-redux) - -[Introduction to Idiomatic Redux - Egghead](https://egghead.io/courses/building-react-applications-with-idiomatic-redux) - -**Session** Recap Redux - -## Capstone Project - -The final project of the bootcamp. - -Deliverables: - -1. User Personas - [How to define a User Persona](https://careerfoundry.com/en/blog/ux-design/how-to-define-a-user-persona/) -2. User Stories - [Writing User Stories](https://www.mountaingoatsoftware.com/agile/user-stories) -3. Wireframes - [Website Wireframes](https://en.wikipedia.org/wiki/Website_wireframe) -4. API Contracts -5. Trello Board for managing and prioritising user stories -6. Gitlab Repository for managing the code -7. Deployment link for the project - -Thanks.