├── .DS_Store
├── .eslintrc.json
├── .gitignore
├── .travis.yml
├── .vscode
└── settings.json
├── LICENSE
├── README.md
├── Week1
├── LESSONPLAN.md
├── MAKEME.md
├── README.md
├── homework
│ ├── app.js
│ ├── index.html
│ └── style.css
├── js-exercises
│ ├── ex1-bookList.html
│ ├── ex1-bookList.js
│ ├── ex2-aboutMe.html
│ ├── ex2-aboutMe.js
│ ├── ex3-hijackLogo.js
│ ├── ex4-whatsTheTime.html
│ ├── ex4-whatsTheTime.js
│ ├── ex5-catWalk.html
│ └── ex5-catWalk.js
└── project
│ ├── index.css
│ ├── index.html
│ └── index.js
├── Week2
├── LESSONPLAN.md
├── MAKEME.md
├── README.md
├── homework
│ ├── maartjes-work.js
│ └── map-filter.js
├── js-exercises
│ ├── ex1-oddOnesOut.js
│ ├── ex2-whatsYourMondayWorth.js
│ ├── ex3-lemonAllergy.js
│ ├── ex4-collectiveAge.js
│ ├── ex5-myFavoriteHobbies.html
│ └── ex5-myFavoriteHobbies.js
├── project
│ ├── index.html
│ └── index.js
└── test
│ ├── maartjes-work.test.js
│ └── map-filter.test.js
├── Week3
├── LESSONPLAN.md
├── MAKEME.md
├── README.md
├── js-exercises
│ ├── ex1-AddSix.js
│ ├── ex2-RemoveDuplicates.js
│ ├── ex3-GuessTheOutput.js
│ ├── ex4-GuessMore.js
│ └── ex5-LotteryMachine.js
├── old-homework
│ ├── step2-1.js
│ ├── step2-2.js
│ ├── step2-3.js
│ ├── step2-4.js
│ ├── step2-5.js
│ ├── step2-6.js
│ ├── step2-7.js
│ ├── step3-bonus.js
│ └── step3.js
├── project
│ ├── index.html
│ └── index.js
└── test
│ ├── console-test.js
│ ├── step2-1.test.js
│ ├── step2-2.test.js
│ ├── step2-3.test.js
│ ├── step2-4.test.js
│ ├── step2-5.test.js
│ ├── step2-6.test.js
│ ├── step3-bonus.test.js
│ └── step3.test.js
├── assets
├── array-methods-exercises.js
├── call_stack_example.png
├── callbacks.js
├── domtree.png
├── hoisting.js
├── javascript-sync-vs-async.png
├── javascript2.png
├── pomodoro.png
├── randomquotegenerator.png
├── scope.js
├── scopes.png
├── servicequality.png
├── simple-dom.png
├── submit-homework.png
├── sync-async.js
├── tipcalculator.png
├── weekflow.png
└── wilgert.png
├── hand-in-homework-guide.md
├── package-lock.json
├── package.json
├── prettier.config.js
└── test
└── README.md
/.DS_Store:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/HackYourFuture/JavaScript2/8e77a7ea1bee5d6aed42d4bee5fcb6f683c4f40c/.DS_Store
--------------------------------------------------------------------------------
/.eslintrc.json:
--------------------------------------------------------------------------------
1 | {
2 | "extends": ["airbnb", "prettier"],
3 | "plugins": ["prettier"],
4 | "env": {
5 | "browser": true,
6 | "jest": true
7 | },
8 | "rules": {
9 | "prettier/prettier": ["error"],
10 | "strict": "off",
11 | "func-names": "off",
12 | "import/no-dynamic-require": "off",
13 | "no-console": "off",
14 | "no-param-reassign": "off",
15 | "no-plusplus": "off",
16 | "no-restricted-syntax": "off",
17 | "object-shorthand": "off",
18 | "operator-assignment": "off",
19 | "prefer-arrow-callback": "off",
20 | "prefer-destructuring": "off",
21 | "prefer-template": "off",
22 | "trailing-comma": "off",
23 | "linebreak-style": "off"
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # Logs
2 | logs
3 | *.log
4 | npm-debug.log*
5 | yarn-debug.log*
6 | yarn-error.log*
7 |
8 | # Runtime data
9 | pids
10 | *.pid
11 | *.seed
12 | *.pid.lock
13 |
14 | # Directory for instrumented libs generated by jscoverage/JSCover
15 | lib-cov
16 |
17 | # Coverage directory used by tools like istanbul
18 | coverage
19 |
20 | # nyc test coverage
21 | .nyc_output
22 |
23 | # Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files)
24 | .grunt
25 |
26 | # Bower dependency directory (https://bower.io/)
27 | bower_components
28 |
29 | # node-waf configuration
30 | .lock-wscript
31 |
32 | # Compiled binary addons (http://nodejs.org/api/addons.html)
33 | build/Release
34 |
35 | # Dependency directories
36 | node_modules/
37 | jspm_packages/
38 |
39 | # Typescript v1 declaration files
40 | typings/
41 |
42 | # Optional npm cache directory
43 | .npm
44 |
45 | # Optional eslint cache
46 | .eslintcache
47 |
48 | # Optional REPL history
49 | .node_repl_history
50 |
51 | # Output of 'npm pack'
52 | *.tgz
53 |
54 | # Yarn Integrity file
55 | .yarn-integrity
56 |
57 | # dotenv environment variables file
58 | .env
59 |
60 | .netlify
61 | dist/
62 |
--------------------------------------------------------------------------------
/.travis.yml:
--------------------------------------------------------------------------------
1 | language: node_js
2 | node_js:
3 | - '10'
4 |
5 | script:
6 | - npm run lint
7 |
--------------------------------------------------------------------------------
/.vscode/settings.json:
--------------------------------------------------------------------------------
1 | {
2 | "editor.formatOnSave": true,
3 | "editor.formatOnType": true,
4 | "editor.formatOnPaste": true,
5 | "editor.detectIndentation": false,
6 | "editor.tabSize": 2,
7 | "cSpell.words": [
8 | "Debouncing",
9 | "Maartje",
10 | "blabla",
11 | "codewars",
12 | "keyup",
13 | "maartje's",
14 | "maartjes",
15 | "roverjs",
16 | "taalmap",
17 | "trollface"
18 | ]
19 | }
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | This work is licensed under the Creative Commons Attribution 4.0 International License.
2 | To view a copy of this license, visit http://creativecommons.org/licenses/by/4.0/
3 | or send a letter to Creative Commons, PO Box 1866, Mountain View, CA 94042, USA.
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # DEPRECATED - JavaScript 2
2 | This module has been replace with the Browsers module, find it [here](https://github.com/HackYourFuture/Browsers)
3 |
4 |
5 | ```If you were to ask a random person on the street the question "What is a browser?", you'll most likely get a variety of (incorrect) answers. For proof, check [this](https://www.youtube.com/watch?v=o4MwTvtyrUQ) out.
6 |
7 | You might be one of those people right now, but after this module no more. In **JavaScript2** you'll learn all about how to use JavaScript within the browser.
8 |
9 | ## Learning goals
10 |
11 | In order to successfully complete this module you will need to master the following:
12 |
13 | - Understand what the `DOM` is
14 | - Use the basics of `DOM Manipulation`
15 | - Differentiate between `synchronous` and `asynchronous` operations
16 | - Gain awareness of the inner workings of JavaScript
17 | - Learn to think based on `principles`, instead of libraries and frameworks
18 |
19 | ## How to use this repository
20 |
21 | ### Repository content
22 |
23 | This repository consists of 3 essential parts:
24 |
25 | 1. `README`: this document contains all the required theory you need to understand **while** working on the homework. It contains not only the right resources to learn about the concepts, but also lectures done by HackYourFuture teachers. This is the **first thing** you should start with every week
26 | 2. `MAKEME`: this document contains the instructions for each week's homework. Start with the exercises rather quickly, so that you can ground the concepts you read about earlier.
27 | 3. `LESSONPLAN`: this document is meant for teachers as a reference. However, as a student don't be shy to take a look at it as well!
28 |
29 | ### How to study
30 |
31 | Let's say you are just starting out with the JavaScript2 module. This is what you do...
32 |
33 | 1. The week always starts on **Wednesday**. First thing you'll do is open the `README.md` for that week. For the first week of `JavaScript2`, that would be [Week1 Reading](/Week1/README.md)
34 | 2. You spend **Wednesday** and **Thursday** going over the resources and try to get a basic understanding of the concepts. In the meanwhile, you'll also implement any feedback you got on last week's homework (from the JavaScript1 module)
35 | 3. On **Friday** you start with the homework, found in the `MAKEME.md`. For the first week of `JavaScript2`, that would be [Week1 Homework](/Week1/MAKEME.md)
36 | 4. You spend **Friday** and **Saturday** playing around with the exercises and write down any questions you might have
37 | 5. **DEADLINE 1**: You'll submit any questions you might have before **Saturday 23.59**, in the class channel
38 | 6. On **Sunday** you'll attend class. It'll be of the Q&A format, meaning that there will be no new material. Instead your questions shall be discussed and you can learn from others
39 | 7. You spend **Monday** and **Tuesday** finalizing your homework
40 | 8. **DEADLINE 2**: You submit your homework to the right channels (GitHub) before **Tuesday 23.59**. If you can't make it on time, please communicate it with your mentor
41 | 9. Start the new week by going back to point 1!
42 |
43 | In summary:
44 |
45 | 
46 |
47 | To have a more detailed overview of the guidelines, please read [this document](https://docs.google.com/document/d/1JUaEbxMQTyljAPFsWIbbLwwvvIXZ0VCHmCCN8RaeVIc/edit?usp=sharing) or ask your mentor/class on Slack!
48 |
49 | ### Video lectures
50 |
51 | For each module HackYourFuture provides you with video lectures. These are made by experienced software developers who know what they're talking about. The main teacher for this module will be [Wilgert Velinga](https://hackyourfuture.slack.com/team/UGTGC0T41): senior frontend developer and consultant!
52 |
53 | You can find out more about him here:
54 |
55 | - [GitHub](https://github.com/wilgert)
56 | - [@Wilgert on Slack](https://hackyourfuture.slack.com/team/UGTGC0T41)
57 |
58 | Learn from Wilgert in the following playlist of videos he has made for you! (Click on the image to open the link)
59 |
60 |
61 |
62 | ## Planning
63 |
64 | | Week | Topic | Reading Materials | Homework | Lesson Plan |
65 | | ---- | -------------------------------------------------------------------- | ------------------------------ | ------------------------------- | -------------------------------------- |
66 | | 1. | Document-Object Model (DOM), DOM manipulation | [Reading W1](/Week1/README.md) | [Homework W1](/Week1/MAKEME.md) | [Lesson Plan W1](/Week1/LESSONPLAN.md) |
67 | | 2. | Synchronous vs. asynchronous, Event Loop, Callbacks, Array Functions | [Reading W2](/Week2/README.md) | [Homework W2](/Week2/MAKEME.md) | [Lesson Plan W2](/Week1/LESSONPLAN.md) |
68 | | 3. | Scope, Hoisting, Closures, Thinking like a programmer II | [Reading W3](/Week3/README.md) | [Homework W3](/Week3/MAKEME.md) | [Lesson Plan W3](/Week1/LESSONPLAN.md) |
69 | | 4. | Test | [Details](/test/README.md) | - | - |
70 |
71 | ## Finished?
72 |
73 | Did you finish the module? Good job! You're doing great!
74 |
75 | If you feel ready for the next challenge, click [here](https://www.github.com/HackYourFuture/JavaScript3) to go to JavaScript3!
76 |
77 | _The HackYourFuture curriculum is subject to CC BY copyright. This means you can freely use our materials, but just make sure to give us credit for it :)_
78 |
79 | This work is licensed under a Creative Commons Attribution 4.0 International License.```
80 |
--------------------------------------------------------------------------------
/Week1/LESSONPLAN.md:
--------------------------------------------------------------------------------
1 | # Lesson Plan JavaScript2 Week 1
2 |
3 | ## Agenda
4 |
5 | The purpose of this class is to introduce to the student:
6 |
7 | - How a webpage is made up of objects (DOM)
8 | - How JavaScript can be used to manipulate those objects (DOM manipulation)
9 | - Commonly used browser defined functions and properties
10 |
11 | ## Core concepts
12 |
13 | FIRST HALF (12.00 - 13.30)
14 |
15 | > Is this your first lecture for this class?
16 | > Please introduce yourself briefly:
17 | >
18 | > - Job
19 | > - Education
20 | > - City
21 | > - Why you love programming (if you do)
22 |
23 | ## 1. Document Object Model (DOM)
24 |
25 | ### Explanation
26 |
27 | The [Document Object Model (DOM)](https://developer.mozilla.org/en-US/docs/Web/API/Document_Object_Model/Introduction) is an _object-oriented representation_ of a web page (HTML document). Every HTML element (ex. `h1`, `p` or `img`) is corrected first and then converted into a JavaScript object by the browser, making it possible for us to use JavaScript to change the contents. Using JavaScript code we can access the `DOM` through a global object called `document` or `window.document`.
28 |
29 | ### Example
30 |
31 | > Show the student the following HTML in the browser, and then refer to it in the browser console.
32 |
33 | ```html
34 |
35 |
36 |
37 | My title
38 |
39 |
40 |
41 |
My header
42 |
This is a nice paragraph
43 |
44 |
Item 1
45 |
Item 2
46 |
47 | My link
48 |
49 |
50 | ```
51 |
52 | 
53 |
54 | Notice how the DOM is structured in a tree-like manner. It goes from top (highest) to bottom (lowest) level. It's very much like a family tree: the highest level is the great-great-great-grandparent, while the lowest level is the grand-grand-grand-child.
55 |
56 | ### Exercise
57 |
58 | 1. Create an HTML file including the structure of a basic webpage (including `!DOCTYPE`, `html`, `head` and `body`, 1 `h1` and 1 `p`)
59 | 2. Find out how to target the `head`, `body` and `h1` elements using the browser console
60 | 3. Present your solution and how you figured it out (_Teacher chooses two people_)
61 |
62 | ### Essence
63 |
64 | **The DOM is created by the browser: it reads your HTML file and transforms the elements into objects. We use JavaScript to select these elements in order to change them.**
65 |
66 | ## 2. Commonly used browser defined functions and properties
67 |
68 | ### Explanation
69 |
70 | As developers we can use code others have written. The browser contains predefined functions that we can use in order to get certain things done. For example, we can add/update/remove new HTML elements to the DOM. The browser also offers us properties, so that we can also play with the user's viewing experience. For example, we can modify the browser's width programmatically so we can offer a responsive website.
71 |
72 | ### Example
73 |
74 | ```js
75 | // 1. Print the current page
76 | window.print();
77 |
78 | // 2. Get the URL from the address bar
79 | window.location.href;
80 |
81 | // 3. Make a XHR request to an external service
82 | window.fetch('https://dog.ceo/api/breeds/image/random');
83 | ```
84 |
85 | ### Exercise
86 |
87 | Find browser functions or properties to show how we can...
88 |
89 | 1. display an alert box?
90 | 2. find out what the browser's name is?
91 | 3. go back one page?
92 |
93 | ### Essence
94 |
95 | **We can use by the browser predefined functions and properties to shape the user's experience of our application.**
96 |
97 | SECOND HALF (14.00 - 16.00)
98 |
99 | ## 3. DOM manipulation
100 |
101 | ### Explanation
102 |
103 | `DOM manipulation` refers to the act of using JavaScript to select and modify elements within the DOM. We do this in order to provide users interactivity with the page: for example, if a button is clicked the background color changes, or if a menu item is hovered over it becomes bigger.
104 |
105 | ### Example
106 |
107 | ```html
108 |
109 |
110 |
111 | My title
112 |
113 |
114 |
115 |
My header
116 |
This is a nice paragraph
117 |
118 |
Item 1
119 |
Item 2
120 |
121 |
122 | My link
123 |
124 |
125 | ```
126 |
127 | ```js
128 | // 1. Make body background color red
129 | const body = document.body;
130 | body.style.background = 'red';
131 |
132 | // 2. Change paragraph content
133 | const p = document.querySelector('p');
134 | p.innerHtml = 'This paragraph has changed!';
135 |
136 | // 3. Create and add a new element to an existing HTML element
137 | const thirdLi = document.createElement('li');
138 | const ul = document.querySelector('ul');
139 | ul.appendChild(thirdLi);
140 |
141 | // 4. On button click alert the user!
142 | const button = document.querySelector('button');
143 | button.addEventListener('click', function() {
144 | alert('You clicked the button!');
145 | });
146 | ```
147 |
148 | ### Exercise
149 |
150 | Write JavaScript code that...
151 |
152 | 1. changes the `href` value to `https://www.hackyourfuture.net/`
153 | 2. changes the `button` text to `Make background colored!`
154 | 3. colors the `body` background to your favorite color, when the button is clicked
155 |
156 | Present your solution and how you figured it out (_Teacher chooses two people_)
157 |
158 | ### Essence
159 |
160 | **Using JavaScript we can select and modify DOM elements. In this way we can provide the user useful interactions with the webpages they're engaged in.**
161 |
--------------------------------------------------------------------------------
/Week1/MAKEME.md:
--------------------------------------------------------------------------------
1 | # Homework JavaScript2 Week 1
2 |
3 | ## **Todo list**
4 |
5 | 1. Practice the concepts
6 | 2. JavaScript exercises
7 | 3. Code along
8 | 4. PROJECT: Random Quote Generator
9 |
10 | ## **1. Practice the concepts**
11 |
12 | Before we head into the exercises, it might be nice to do some interactive exercises first! In the following resource you'll find some exercises that'll teach you the basics of the interaction between JavaScript and the DOM:
13 |
14 | - [Making webpages interactive](https://www.khanacademy.org/computing/computer-programming/html-css-js)
15 |
16 | ## **2. JavaScript exercises**
17 |
18 | > Inside of your `JavaScript2` fork, find the folder called `Week1`. Inside of that folder, find the folder called `js-exercises`. In this folder you will find five `.js` files (sometimes with a matching `.html` file), one for each exercise where you need to write your code. Please use the correct file for the respective exercise.
19 |
20 | **Exercise 1: The book list**
21 |
22 | I'd like to display my three favorite books inside a nice webpage!
23 |
24 | ```js
25 | const books = [
26 | {
27 | title: 'The Design of Everyday Things',
28 | author: 'Don Norman',
29 | alreadyRead: false
30 | },
31 | {
32 | title: 'The Most Human Human',
33 | author: 'Brian Christian',
34 | alreadyRead: true
35 | },
36 | {
37 | title: 'The Pragmatic Programmer',
38 | author: 'Andrew Hunt',
39 | alreadyRead: true
40 | }
41 | ];
42 | ```
43 |
44 | 1. Iterate through the array of books.
45 | 2. For each book, create a `
` element with the book title and author and append it to the page.
46 | 3. Use a `
` and `
` to display the books.
47 | 4. Add an `` to each book that links to a URL of the book cover.
48 | 5. Change the style of the book depending on whether you have read it (green) or not (red).
49 |
50 | The end result should look something like this:
51 | https://hyf-js2-week1-makeme-ex1-demo.herokuapp.com/
52 |
53 | **Exercise 2: About me**
54 |
55 | Given this HTML:
56 |
57 | ```html
58 |
59 |
60 |
61 |
62 | About Me
63 |
64 |
65 |
About Me
66 |
67 |
68 |
Nickname:
69 |
Favorite food:
70 |
Hometown:
71 |
72 |
73 |
74 | ```
75 |
76 | 1. Add a script tag to the bottom of the HTML body.
77 | 2. (In the JavaScript) Change the body tag's style so it has a font-family of "Arial, sans-serif".
78 | 3. (In the JavaScript) Replace each of the spans (nickname, fav-food, hometown) with your own information.
79 | 4. Iterate through each li and change the class to "list-item".
80 | 5. (In the HTML head) Add a style tag that sets a rule for .list-item to make the color red.
81 | 6. Create a new img element and set its src attribute to a picture of you. Append that element to the page.
82 |
83 | **Exercise 3: The logo hijack**
84 |
85 | No homepage is safe from the logo bandit! Everytime he sees a Google Logo he replaces it with a logo from HackYourfuture instead: https://www.hackyourfuture.dk/static/logo-dark.svg.
86 |
87 | In this exercise you're expected to write a JavaScript function that can be executed in the console of the [Google website](https://www.google.com).
88 |
89 | 1. Find out how to select the element that contains the Google logo, and store it in a variable
90 | 2. Modify the source and sourceset of the logo so that it's replaced by the HackYourFuture logo instead
91 |
92 | **Exercise 4: What's the time?**
93 |
94 | Why wear a watch when you can check the time, live in your webpage?
95 |
96 | 1. Create a basic HTML file
97 | 2. Include a script tag and link the JavaScript file
98 | 3. Inside the JS file, write a function that adds the current time to the webpage. Make sure it's written in the HH:MM:SS notation (hour, minute, second). Hint: use `setInterval()` to make sure the time stays current
99 | 4. Have the function execute when it's loading in the browser
100 |
101 | **Exercise 5: The cat walk**
102 |
103 | Start with this webpage, which has a single img tag of an animated GIF of a cat walking.
104 |
105 | ```html
106 |
107 |
108 |
109 |
110 | Cat Walk
111 |
112 |
113 |
114 |
115 |
116 | ```
117 |
118 | 1. Create a variable to store a reference to the img.
119 | 2. Change the style of the img to have a "left" of "0px", so that it starts at the left hand of the screens.
120 | 3. Create a function called catWalk() that moves the cat 10 pixels to the right of where it started, by changing the "left" style property.
121 | 4. Call that function every 50 milliseconds. Your cat should now be moving across the screen from left to right. Hurrah!
122 | 5. When the cat reaches the right-hand of the screen, restart them at the left hand side ("0px"). So they should keep walking from left to right across the screen, forever and ever.
123 | 6. When the cat reaches the middle of the screen, replace the img with an image of a cat dancing (use this URL: https://tenor.com/StFI.gif), keep it dancing for 5 seconds, and then replace the img with the original image and have it continue the walk.
124 |
125 |
126 | The end result should look and behave similar to [https://dancingcat-sandbox.mxapps.io](https://dancingcat-sandbox.mxapps.io)
127 |
128 | ## **3. Code along**
129 |
130 | In the following tutorial you'll learn how to make a small web application that allows a user to add new issues to a board. Included is practice with [Bootstrap](https://getbootstrap.com/).
131 |
132 | Enjoy!
133 |
134 | - [Build an Issue Tracker](https://www.youtube.com/watch?v=NYq9J-Eur9U)
135 |
136 | ## **4. PROJECT: Random Quote Generator**
137 |
138 | > Every week ends with a project you have to build on your own. Instead of getting clear-cut instructions, you'll get a list of criteria that your project needs to measure up to.
139 |
140 | > Write the project code in the folder `Week1 \ project`.
141 |
142 | In this week's project you'll be making a Random Quote Generator! It includes a text box and a simple button that, when clicked, take a random quote out of a set amount of quotes and show it in the page. Here's how it should look:
143 |
144 | 
145 |
146 | Here are the requirements:
147 |
148 | - Include at least 1 JavaScript, CSS and HTML file
149 | - The design should look similar to the one in the picture above
150 | - No CSS frameworks allowed
151 | - Each time the button is clicked it should show a random quote
152 | - Create a function that fires after the button click
153 | - Collect 6 of your favorite quotes (quote and author) and store them in the right data structure
154 |
155 | Good luck!
156 |
157 | ## **SUBMIT YOUR HOMEWORK!**
158 |
159 | After you've finished your todo list it's time to show us what you got! Upload all your files to a forked repository (a copy from the original, which in this case is the [JavaScript2](https://www.github.com/HackYourFuture/JavaScript2) repository) using GIT. Then make a pull request to the original.
160 |
161 | If you need a refresher, take a look at the following [guide](../hand-in-homework-guide.md) to see how it's done.
162 |
163 | The homework that needs to be submitted is the following:
164 |
165 | 1. JavaScript exercises
166 | 2. Project: Random Quote Generator
167 |
168 | _Deadline Saturday 23.59 CET_
169 |
--------------------------------------------------------------------------------
/Week1/README.md:
--------------------------------------------------------------------------------
1 | # Reading Material JavaScript2 Week 1
2 |
3 | ## Agenda
4 |
5 | These are the topics for week 1:
6 |
7 | 1. What is a web browser?
8 | - How a browser works
9 | - Different browsers work differently
10 | 2. What is the Document-Object Model (DOM)?
11 | - JavaScript and the browser
12 | - The DOM
13 | - The Critical Rendering Path
14 | - Traversing the DOM
15 | 3. What is DOM Manipulation?
16 |
17 | - Manipulating elements
18 | - Browser events
19 | - Event listeners and handlers
20 |
21 | ## 0. Video Lectures
22 |
23 | Your teacher Wilgert has made video lectures for this week's material. You can find them here: [Videos 1 - 10](https://www.youtube.com/playlist?list=PLVYDhqbgYpYU-7_oyPBkUuuis5bL1Dk8n)
24 |
25 |
26 |
27 | ## 1. What is a web browser?
28 |
29 | A web browser is software that allows you to access websites.
30 |
31 | ### How a browser works
32 |
33 | In your journey into becoming a web developer it's important to know the tools you'll be using intimately. One such is the browser, which will be used to display your websites. In the following resources you'll learn about the many parts any web browser consists of and what their use is:
34 |
35 | - [How a web browser functions](https://www.youtube.com/watch?v=z0HN-fG6oT4)
36 | - [How do web browsers work?](https://medium.com/@monica1109/how-does-web-browsers-work-c95ad628a509)
37 |
38 | ### Different browsers work differently
39 |
40 | A website, ultimately is a set of instructions describing how a series of webpages should look. It's up to the browser to render it by reading the code from your HTML/CSS and JavaScript files. There are, however, differences in the code interpretation of the different browsers, thus making the output look differently.
41 |
42 | That's why you should check the way your website looks on different browsers during the development of your website. This is called making it **cross browser compatible**>
43 |
44 | You can use the following online tool in order see how your pages look on multiple browsers:
45 |
46 | - [Browsershots](http://browsershots.org)
47 |
48 | A good website should look and function the same in any browser.
49 |
50 | Unfortunately, there is no easy solution for that. You should check the specificities of each browser that fails to display your website correctly and make the necessary adjustments to your code. Such compatibility issues may occur not only in different browsers but because of an old browser version which does not support completely the latest standards.
51 |
52 | This is because browser development doesn't go at the same speed as programming language development. More often than not, the web technologies you're using will have more features you as a developer can make use of than the browser can currently handle. This is important to keep in mind.
53 |
54 | When you do your styling, especially, it's important to know if a certain browser (and browser version) is even able to understand it. A helpful tool in identifying this is a website called **caniuse.com**:
55 |
56 | - [caniuse](https://caniuse.com/)
57 | - [Check HTML5/CSS3 Support with CANIUSE.COM](https://www.youtube.com/watch?v=el7McMP8CB8)
58 |
59 | Generally speaking, you want to support as many browsers (and browser versions) with your code as possible.
60 |
61 | For more research, check out the following resources:
62 |
63 | - [Dealing with Cross Browser Compatibility](https://www.youtube.com/watch?v=9tEixRJ3GeI)
64 | - [Understanding The Stacking Context for Cross Browser Compatibility](https://medium.com/@mattcroak718/understanding-the-stacking-context-for-cross-browser-compatibility-2b21db1cf621)
65 |
66 | ## 2. What is the Document-Object Model (DOM)?
67 |
68 | ### JavaScript and the browser
69 |
70 | As we've learned in the previous module, JavaScript is a programming language. It allows you to write logical rules that the computer can execute in order to solve a problem. However, saying that the 'computer' executes it is actually inaccurate. There are two specific softwares that execute JavaScript: **the browser** and **Node.js**. We'll talk about the latter in a different module.
71 |
72 | The browser is software that has been build to understand JavaScript ((and HTML/CSS)). Each different browser (Chrome, Firefox, Safari, etc.) has, behind the scenes, a **JavaScript engine** that works to transform the JavaScript code that you write into code that the computer understands.
73 |
74 | - [How the JavaScript engine works](https://www.youtube.com/watch?v=KM9coMpy5sQ)
75 |
76 | Every programming language sits at a certain level of abstraction, relative to the only real language a computer understands: machine code (which is only 0's and 1's). For more information on this, check out the following [video](https://www.youtube.com/watch?v=bUWCD45qniA)
77 |
78 | For our purposes, it's only important to understand that the browser looks at JavaScript and then does what it's instructed to do: add elements, modify text or media files, etc. That's the purpose of JavaScript in the browser: to add interactivity based off of the user's behavior.
79 |
80 | - [JavaScript, the Browser, and the DOM](https://www.youtube.com/watch?v=31ViueuIXGE)
81 |
82 | ### The DOM
83 |
84 | The Document-Object Model (DOM) is a tree-like representation of the structure of a webpage. The following is a simple example:
85 |
86 | 
87 |
88 | JavaScript is made accessible to the DOM by embedding it into an HTML file. You might've seen the `` before; well, this is how the browser becomes aware of JavaScript.
89 |
90 | - [What exactly is the DOM](https://bitsofco.de/what-exactly-is-the-dom/)
91 | - [JavaScript and the browser](https://eloquentjavascript.net/13_browser.html)
92 | - [JavaScript DOM Crash Course - Part 1](https://www.youtube.com/watch?v=0ik6X4DJKCc)
93 |
94 | ### The Critical Rendering Path
95 |
96 | The actual process of transforming HTML, CSS and JavaScript into a user-viewable version of a webpage is called **the Critical Rendering Path**.
97 |
98 | - [Understanding the Critical Rendering Path](https://bitsofco.de/understanding-the-critical-rendering-path/)
99 |
100 | ## 3. What is DOM Manipulation?
101 |
102 | **DOM manipulation** refers to the activity of selecting and modifying DOM elements. The main reason why this is done is that **you want to show the user different things depending their activity**, for example if you click on a [hamburger menu icon](https://bit.ly/2Yr4O7Z) and a navigation menu slides in.
103 |
104 | Finding the right elements is called **traversing the DOM**. Traversing the DOM essential means: using JavaScript to select certain elements within the DOM in order to modify them (change color, size or make them disappear, for example).
105 |
106 | ### Manipulating elements
107 |
108 | Look at the following code sample:
109 |
110 | ```js
111 | const body = document.querySelector('body'); // you can also use 'document.body'
112 | const newParagraph = document.createElement('p');
113 | newParagraph.innerText = 'This paragraph will be added to the body!';
114 | newParagraph.style.background = 'red';
115 | body.appendChild(newParagraph);
116 | ```
117 |
118 | In this example we're executing the following steps:
119 |
120 | 1. Selecting the body: this is always necessary, as we can only add or remove elements from the body of the document
121 | 2. Creating a new DOM element: a paragraph i.e. a `
` element
122 | 3. Injecting content into the newly create paragraph element
123 | 4. Setting the background color for the newly create paragraph element
124 | 5. Adding the newly create paragraph element element to the body
125 |
126 | Test this code out by copying and pasting it in the Developer Console of your browser. After you've pressed the Enter/Return key you will find your new `
` at the end of the page!
127 |
128 | Learning how to write JavaScript that targets the DOM is an essential part of being a web developer. In the following resources you'll more about how to do that:
129 |
130 | - [Traversing the DOM with JavaScript](https://zellwk.com/blog/dom-traversals/)
131 | - [JavaScript DOM Crash Course - Part 2](https://www.youtube.com/watch?v=mPd2aJXCZ2g)
132 |
133 | ### Browser events
134 |
135 | Browser events (also known as DOM events) are very much like real-life events: they are important things that happen. In real-life this could be getting a job, graduating from school or receiving a birthday gift. In terms of the browser, this is much more small scale: user actions like `clicking`, `scrolling` or `typing` are all considered events.
136 |
137 | These events are important to know about, because based on those we manipulate the DOM. For example, user clicks on an image and as a result it increases in size.
138 |
139 | Effectively it's cause and effect.
140 |
141 | Check out the following resources to learn more about what events there are, and what you can do to manipulate elements after an event has happened:
142 |
143 | - [What are browser events?](https://www.youtube.com/watch?v=LeKKU3a4AQo)
144 | - [Introduction to browser events](https://javascript.info/introduction-browser-events)
145 | - [JavaScript DOM Crash Course - Part 3](https://www.youtube.com/watch?v=wK2cBMcDTss)
146 |
147 | ### Event listeners and handlers
148 |
149 | Take a look at this code:
150 |
151 | ```js
152 | const body = document.querySelector('body');
153 | body.addEventListener('click', function () {
154 | body.style.background = 'black';
155 | });
156 | ```
157 |
158 | Test this code out by copying and pasting it in the Developer Console of your browser. After you've pressed the Enter/Return click the website. You should see the whole `
` becoming black!
159 |
160 | This is DOM manipulation in its simplest form. It goes in three essential steps:
161 |
162 | (1) An event happens ("User clicks on the page")
163 | (2) JavaScript is aware and looks for this specific user action (The browser is listening for the event, in this case a `click` event)
164 | (3) JavaScript modifies the DOM as a result (A function that makes the body background color black is executed)
165 |
166 | The second step is called **listening for the event**. We do this by using a by the browser predefined function called `addEventListener()`, which we get from the `document` object in the browser. The browser needs to listen to the event in order to know what it should do ("make the body background color black") in case a certain event (`click`) happens to a certain element (`body`).
167 |
168 | The third and final step is called **handling the event**. The term "handler" effectively means "taking care of" the event; the response to the event. The handler itself is nothing more than a function that executes more JavaScript code in order to manipulate a particular part of the page (either the element that experienced the event or a totally different part of the page).
169 |
170 | - [Events in JavaScript](https://www.youtube.com/watch?v=7UstS0hsHgI)
171 | - [JavaScript Events Tutorial](https://www.youtube.com/watch?v=e57ReoUn6kM)
172 |
173 | ## Finished?
174 |
175 | Are you finished with going through the materials? High five! If you feel ready to get practical, click [here](./MAKEME.md).
176 |
--------------------------------------------------------------------------------
/Week1/homework/app.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | {
4 | const bookTitles = [
5 | // Replace with your own book titles
6 | 'harry_potter_chamber_secrets',
7 | ];
8 |
9 | // Replace with your own code
10 | console.log(bookTitles);
11 | }
12 |
--------------------------------------------------------------------------------
/Week1/homework/index.html:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/Week1/homework/style.css:
--------------------------------------------------------------------------------
1 | /* add your styling here */
--------------------------------------------------------------------------------
/Week1/js-exercises/ex1-bookList.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 | Book List
8 |
9 |
10 |
11 |
My Book List
12 |
13 |
14 |
15 |
16 |
17 |
--------------------------------------------------------------------------------
/Week1/js-exercises/ex1-bookList.js:
--------------------------------------------------------------------------------
1 | /**
2 |
3 | ** Exercise 1: The book list **
4 |
5 | I 'd like to display my three favorite books inside a nice webpage!
6 |
7 | 1. Iterate through the array of books.
8 | 2. For each book, create a `
`
9 | element with the book title and author and append it to the page.
10 | 3. Use a `
` and `
` to display the books.
11 | 4. Add an `` to each book that links to a URL of the book cover.
12 | 5. Change the style of the book depending on whether you have read it(green) or not(red).
13 |
14 | The end result should look something like this:
15 | https: //hyf-js2-week1-makeme-ex1-demo.herokuapp.com/
16 |
17 | */
18 |
19 | function createBookList(books) {
20 | // your code goes in here, return the ul element
21 | }
22 |
23 | const books = [{
24 | title: 'The Design of Everyday Things',
25 | author: 'Don Norman',
26 | alreadyRead: false
27 | },
28 | {
29 | title: 'The Most Human Human',
30 | author: 'Brian Christian',
31 | alreadyRead: true
32 | },
33 | {
34 | title: 'The Pragmatic Programmer',
35 | author: 'Andrew Hunt',
36 | alreadyRead: true
37 | }
38 | ];
39 |
40 | let ulElement = createBookList(books);
41 |
42 | document.querySelector("#bookList").appendChild(ulElement);
--------------------------------------------------------------------------------
/Week1/js-exercises/ex2-aboutMe.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | About Me
7 |
8 |
9 |
10 |
11 |
12 |
13 |
About Me
14 |
15 |
16 |
Nickname:
17 |
Favorite food:
18 |
Hometown:
19 |
20 |
21 |
22 |
23 |
24 |
--------------------------------------------------------------------------------
/Week1/js-exercises/ex2-aboutMe.js:
--------------------------------------------------------------------------------
1 | /**
2 |
3 | ** Exercise 2: About me **
4 |
5 | 1. See HTML
6 | 2. Change the body tag 's style so it has a font-family of "Arial, sans-serif".
7 | 3. Replace each of the spans(nickname, fav - food, hometown) with your own information.
8 | 4. Iterate through each li and change the class to "list-item".
9 | 5. See HTML
10 | 6. Create a new img element and set its src attribute to a picture of you.Append that element to the page.
11 | */
--------------------------------------------------------------------------------
/Week1/js-exercises/ex3-hijackLogo.js:
--------------------------------------------------------------------------------
1 | /**
2 |
3 | ** Exercise 3: The logo hijack **
4 |
5 | No homepage is safe from the logo bandit!Everytime he sees a Google Logo he replaces it with a logo from HackYourfuture instead: https: //www.hackyourfuture.dk/static/logo-dark.svg.
6 |
7 | In this exercise you 're expected to write a JavaScript function that can be executed in the console of the [Google website](https://www.google.com).
8 |
9 |
10 | 1. Find out how to select the element that contains the Google logo, and store it in a variable.
11 | 2. Modify the source and sourceset of the logo so that it 's replaced by the HackYourFuture logo instead.
12 |
13 | */
14 |
15 | function hijackGoogleLogo() {
16 | // your code goes in here
17 | }
18 |
19 | hijackGoogleLogo();
--------------------------------------------------------------------------------
/Week1/js-exercises/ex4-whatsTheTime.html:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/Week1/js-exercises/ex4-whatsTheTime.js:
--------------------------------------------------------------------------------
1 | /**
2 |
3 | ** Exercise 4: What 's the time? **
4 |
5 | Why wear a watch when you can check the time, live in your webpage ?
6 |
7 | 1. Create a basic HTML file
8 | 2. in the HTML file Include a script tag and link the JavaScript file
9 | 3. Inside the JS file, write a function that adds the current time to the webpage. Make sure it 's written in the HH:MM:ss notation (hour, minute, second). Hint: use `setInterval()` to make sure the time stays current
10 | 4. Have the function execute when it 's loading in the browser
11 |
12 | */
13 |
14 | function displayCurrentTime() {
15 | // your code goes in here
16 | }
17 |
18 | setInterval(displayCurrentTime, 1000);
--------------------------------------------------------------------------------
/Week1/js-exercises/ex5-catWalk.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | Cat Walk
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
--------------------------------------------------------------------------------
/Week1/js-exercises/ex5-catWalk.js:
--------------------------------------------------------------------------------
1 | /**
2 |
3 | ** Exercise 5: The cat walk **
4 | Starting with an HTML, which has a single img tag of an animated GIF of a cat walking.
5 |
6 | 1. Create a variable to store a reference to the img.
7 | 2. Change the style of the img to have a "left" of "0px", so that it starts at the left hand of the screens.
8 | 3. Create a function called catWalk() that moves the cat 10 pixels to the right of where it started, by changing the "left" style property.
9 | 4. Call that function every 50 milliseconds.Your cat should now be moving across the screen from left to right.Hurrah!
10 | 5. When the cat reaches the right - hand of the screen, restart them at the left hand side("0px").So they should keep walking from left to right across the screen, forever and ever.
11 | 6. When the cat reaches the middle of the screen, replace the img with an image of a cat dancing(use this URL: https: //tenor.com/StFI.gif), keep it dancing for 5 seconds, and then replace the img with the original image and have it continue the walk.
12 |
13 | */
--------------------------------------------------------------------------------
/Week1/project/index.css:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/HackYourFuture/JavaScript2/8e77a7ea1bee5d6aed42d4bee5fcb6f683c4f40c/Week1/project/index.css
--------------------------------------------------------------------------------
/Week1/project/index.html:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/Week1/project/index.js:
--------------------------------------------------------------------------------
1 | // your code goes in here
--------------------------------------------------------------------------------
/Week2/LESSONPLAN.md:
--------------------------------------------------------------------------------
1 | # Lesson Plan JavaScript2 Week 2
2 |
3 | ## Agenda
4 |
5 | The purpose of this class is to introduce to the student:
6 |
7 | - What synchronous vs. asynchronous processes are
8 | - What callbacks are and how to write your own
9 | - How the event loop works
10 | - Show 3 commonly used array functions (filter, reduce, map)
11 |
12 | ## Core concepts
13 |
14 | FIRST HALF (12.00 - 13.30)
15 |
16 | ## 1. Q&A about last week's concepts & homework
17 |
18 | - DOM
19 | - DOM manipulation
20 | - browser defined functions
21 |
22 | Note: You can ask students to explain a concept or summerise the last lecture themselves
23 |
24 | ## 2. What synchronous vs. asynchronous processes are
25 |
26 | ### Explanation
27 |
28 | ### Example
29 |
30 | ### Exercise
31 |
32 | ### Essence
33 |
34 | Notes:
35 |
36 | - Synchronous refers to a linear execution process: one step at a time
37 | - Asynchronous helps us do multiple things in parallel
38 |
39 | ## 3. Callbacks
40 |
41 | ### Explanation
42 |
43 | A callback in JavaScript is basically a function(callback) being passed as a parameter to another function which after some point of time would execute the function passed or invoke the callback.
44 |
45 | Callbacks were primarily introduced in JavaScript to achieve asynchronous behaviour
46 | (https://codeburst.io/javascript-what-the-heck-is-a-callback-aba4da2deced)
47 |
48 | ### Example
49 |
50 | Consider a situation where person A wishes to go out for a movie with a friend person B one evening. Person A finds out the time and place and now needs to share it with B. A picks up the phone and tries to call B. Let's say that B is currently busy with some work and can't answer the phone. Person A has now got two options. One option is to stay on the line until B picks up the phone and then share the movie details. Or A could drop a voicemail and ask B to **callback** once free.
51 |
52 | ```javascript
53 | function doHomework(subject, callback) {
54 | alert(`Starting my ${subject} homework.`);
55 | callback();
56 | }
57 | function alertFinished() {
58 | alert('Finished my homework');
59 | }
60 | doHomework('math', alertFinished);
61 | ```
62 |
63 | more examples (made by Yash): https://github.com/HackYourFuture/JavaScript2/blob/master/assets/callbacks.js
64 |
65 | ### Exercise
66 |
67 | #### 1. What will happen?
68 |
69 | #### 2. How to turn the output order around?
70 |
71 | ```javascript
72 | function first() {
73 | // Simulate a code delay
74 | setTimeout(function() {
75 | console.log(1);
76 | }, 500);
77 | }
78 | function second() {
79 | console.log(2);
80 | }
81 |
82 | first();
83 | second();
84 | ```
85 |
86 | ### Essence
87 |
88 | you can’t just call one function after another and hope they execute in the right order. Callbacks are a way to make sure certain code doesn’t execute until other code has already finished execution.
89 |
90 | SECOND HALF (14.00 - 16.00)
91 |
92 | ## 4. Event loops
93 |
94 | ### Explanation
95 |
96 | https://github.com/HackYourFuture/fundamentals/blob/master/fundamentals/event_loop.md
97 |
98 | ### Example
99 |
100 | ```Javascript
101 | const bar = () => console.log('bar')
102 |
103 | const baz = () => console.log('baz')
104 |
105 | const foo = () => {
106 | console.log('foo')
107 | bar()
108 | baz()
109 | }
110 |
111 |
112 | foo()
113 | ```
114 |
115 | Output:
116 |
117 | ```Javascript
118 | foo
119 | bar
120 | baz
121 | ```
122 |
123 | Call stack
124 | 
125 |
126 | ### Exercise
127 |
128 | > [Visualisation of an eventloop](http://latentflip.com/loupe/?code=JC5vbignYnV0dG9uJywgJ2NsaWNrJywgZnVuY3Rpb24gb25DbGljaygpIHsKICAgIHNldFRpbWVvdXQoZnVuY3Rpb24gdGltZXIoKSB7CiAgICAgICAgY29uc29sZS5sb2coJ1lvdSBjbGlja2VkIHRoZSBidXR0b24hJyk7ICAgIAogICAgfSwgMjAwMCk7Cn0pOwoKY29uc29sZS5sb2coIkhpISIpOwoKc2V0VGltZW91dChmdW5jdGlvbiB0aW1lb3V0KCkgewogICAgY29uc29sZS5sb2coIkNsaWNrIHRoZSBidXR0b24hIik7Cn0sIDUwMDApOwoKY29uc29sZS5sb2coIldlbGNvbWUgdG8gbG91cGUuIik7!!!PGJ1dHRvbj5DbGljayBtZSE8L2J1dHRvbj4%3D)
129 |
130 | ### Essence
131 |
132 | ## 5. filter, reduce, map
133 |
134 | ### Explanation
135 |
136 | **map**, **filter** and **reduce** are three array methods that iterate (loop!) over the whole array and preform a computation or a transformation.
137 | They have in common that they return a new array based on the transformations/calculations.
138 |
139 | > [MDN definition](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map): The **map()** method creates a new array with the results of calling a provided function on every element in the calling array.
140 |
141 | > [MDN definition](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter): The **filter()** method creates a new array with all elements that pass the test implemented by the provided function
142 |
143 | > [MDN definition](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce): The **reduce()** method executes a **reducer** function (that you provide) on each member of the array resulting in a single output value†.
144 |
145 | Writing the functions yourself: https://github.com/HackYourFuture/fundamentals/blob/master/fundamentals/map_filter.md
146 |
147 | ### Example
148 |
149 | ```Javascript
150 | const numbers = [1, 2, 3, 4];
151 | const square = x => x * x;
152 | const squaredNumbers = numbers.map(square);
153 |
154 | console.log(squaredNumbers); // -> [ 1, 4, 9, 16 ]
155 | ```
156 |
157 | ```Javascript
158 | const numbers = [1, 2, 3, 2];
159 | const isTwo = x => x === 2;
160 | const Twos = numbers.filter(isTwo);
161 |
162 | console.log(Twos); // -> [ 2, 4 ]
163 | ```
164 |
165 | ```Javascript
166 | const numbers = [1, 2, 3, 4];
167 |
168 | const sum = (a, b) => a + b;
169 | const total = numbers.xxx(sum, 0);
170 |
171 | console.log(total); // -> 10
172 | ```
173 |
174 | ### Exercise
175 |
176 | Fill in the xxx with map, filter or reduce:
177 |
178 | ```Javascript
179 | const numbers = [1, 2, 3, 4];
180 | const doubled = numbers.xxx(item => item * 2);
181 | console.log(doubled); // [2, 4, 6, 8]
182 | ```
183 |
184 | ```Javascript
185 | const numbers = [1, 2, 3, 4];
186 |
187 | const times = (a, b) => a * b;
188 | const total = numbers.xxx(times, 0);
189 |
190 | console.log(total); // -> 10
191 | ```
192 |
193 | ```Javascript
194 | const numbers = [1, 2, 3, 4];
195 | const evens = numbers.xxx(item => item % 2 === 0);
196 | console.log(evens); // [2, 4]
197 | ```
198 |
199 | Yash made a very nice exercise (with answers):
200 | https://github.com/yash-kapila/HYF-JS2-Week2/tree/master/src
201 |
202 | ### Essence
203 |
204 | Easy methodes to transform arrays, wich you'll have to do quite often, while keeping the original array intact.
205 | You can see it as a shortcut. Of course you can write these methodes yourself many times, but 'they' already did it for you
206 |
--------------------------------------------------------------------------------
/Week2/MAKEME.md:
--------------------------------------------------------------------------------
1 | # Homework JavaScript2 Week 2
2 |
3 | ## **Todo list**
4 |
5 | 1. Practice the concepts
6 | 2. JavaScript exercises
7 | 3. Code along
8 | 4. PROJECT: The Pomodoro Clock
9 |
10 | ## **1. Practice the concepts**
11 |
12 | Before we head into the exercises, it might be nice to do some interactive exercises first! In the following resource you'll find some exercises that'll teach you all about callbacks and array functions!
13 |
14 | - [Learn JavaScript: Iterators](https://www.codecademy.com/learn/introduction-to-javascript/modules/learn-javascript-iterators)
15 |
16 | ## **2. JavaScript exercises**
17 |
18 | > Inside of your `JavaScript2` fork, find the folder called `Week2`. Inside of that folder, find the folder called `js-exercises`. In this folder you will find five `.js` files, one for each exercise where you need to write your code. Please use the correct file for the respective exercise.
19 |
20 | **Exercise 1: The odd ones out**
21 |
22 | Look at the following code snippet:
23 |
24 | ```js
25 | function doubleEvenNumbers(numbers) {
26 | const newNumbers = [];
27 | for (let i = 0; i < numbers.length; i++) {
28 | if (numbers[i] % 2 === 0) {
29 | newNumbers.push(numbers[i] * 2);
30 | }
31 | }
32 | return newNumbers;
33 | }
34 |
35 | const myNumbers = [1, 2, 3, 4];
36 | console.log(doubleEvenNumbers(myNumbers)); // Logs "[4, 8]" to the console
37 | ```
38 |
39 | The `doubleEvenNumbers` function returns only the even numbers in the array `myNumbers` and doubles them. Like you've learned in the [README](README.md), this block of code isn't easy to decipher.
40 |
41 | Let's rewrite it.
42 |
43 | - Using the `map` and `filter` functions, rewrite the `doubleEvenNumbers` function.
44 |
45 | **Exercise 2: What's your Monday worth?**
46 |
47 | When you're a developer at a big company your Monday could look something like this:
48 |
49 | ```js
50 | const mondayTasks = [
51 | {
52 | name: 'Daily standup',
53 | duration: 30, // specified in minutes
54 | },
55 | {
56 | name: 'Feature discussion',
57 | duration: 120,
58 | },
59 | {
60 | name: 'Development time',
61 | duration: 240,
62 | },
63 | {
64 | name: 'Talk to different members from the product team',
65 | duration: 60,
66 | },
67 | ];
68 | ```
69 |
70 | Let's assume your hourly rate is €25. How much would you earn on that day?
71 |
72 | - Write a program that finds out what your hourly rate on a Monday would be
73 | - Use the `map` array function to take out the duration time for each task.
74 | - Multiply each duration by a per-hour rate for billing and sum it all up.
75 | - Output a formatted Euro amount, rounded to Euro cents, e.g: `€11.34`.
76 | - Make sure the program can be used on any array of objects that contain a `duration` property with a number value
77 |
78 | **Exercise 3: Lemon allergy**
79 |
80 | Your mom bought you a basket of fruit, because you're doing so well in HackYourFuture. How sweet of her!
81 |
82 | ```js
83 | const fruitBasket = ['Apple', 'Lemon', 'Grapefruit', 'Lemon', 'Banana', 'Watermelon', 'Lemon'];
84 | ```
85 |
86 | However, she forgot that you are allergic to lemons! Let's quickly dispose of them before you get an attack.
87 |
88 | - Write a function
89 | - Use the `filter` array function to take out the lemons
90 | - Output a string that says: "My mom bought me a fruit basket, containing [array of fruits] !"
91 |
92 | **Exercise 4: Collective age**
93 |
94 | Have you ever wondered how old the HackYourFuture team members are? Or better yet: what the collective age is? Let's find out!
95 |
96 | ```js
97 | const hackYourFutureMembers = [
98 | { name: 'Wouter', age: 33 },
99 | { name: 'Federico', age: 32 },
100 | { name: 'Noer', age: 27 },
101 | { name: 'Tjebbe', age: 22 },
102 | ];
103 | ```
104 |
105 | - Write a program that calculates the combined age of every member
106 | - Make use of the `map` function to get the ages
107 | - It should contain a function that takes a callback
108 | - The callback adds all the ages together and returns the number
109 | - The main function should log the string "The collective age of the HYF team is: [number]" to the console, and afterwards return the number
110 |
111 | **Exercise 5: My favorite hobbies**
112 |
113 | I've got a couple of hobbies that I want to showcase in a webpage.
114 |
115 | ```js
116 | const myHobbies = [
117 | 'Meditation',
118 | 'Reading',
119 | 'Programming',
120 | 'Hanging out with friends',
121 | 'Going to the gym',
122 | ];
123 | ```
124 |
125 | - Write a program that outputs each of these inside an HTML file
126 | - Create an HTML and JavaScript file, link them together
127 | - Use the `map` and/or `forEach` function to put each hobby into a list item
128 | - Output the list items in an unordered list
129 |
130 | ## **3. Code along**
131 |
132 | Programming can be used to not only make websites, but also games! In the following tutorial you're going to apply your DOM manipulation skills in order to make a classic game: Rock, Paper, Scissors! Enjoy!
133 |
134 | - [Build a Rock, Paper, Scissors Game](https://www.youtube.com/watch?v=WR_pWXJZiRY)
135 |
136 | ## **4. PROJECT: The Pomodoro Clock**
137 |
138 | > Every week ends with a project you have to build on your own. Instead of getting clear-cut instructions, you'll get a list of criteria that your project needs to measure up to.
139 |
140 | > Write the project code in the folder `Week2 \ project`.
141 |
142 | In this week's project you'll be making a Pomodoro Clock! A user can specify how many minutes the timer should be set, and with a click on the play button it starts counting down! If the user wants to pause the timer, they can do so by clicking the pause button.
143 |
144 | It should look like this:
145 |
146 | 
147 |
148 | Here are the requirements:
149 |
150 | - If the timer is running, the user can't change the session length anymore
151 | - Use at least 3 functions
152 | - Display minutes and seconds
153 | - If the timer finishes the timer should be replaced by the message: `Time's up!`
154 |
155 | If you are having trouble understanding the functionality check this [demo](https://pomodoroclock-sandbox.mxapps.io).
156 |
157 | Good luck!
158 |
159 | ## **SUBMIT YOUR HOMEWORK!**
160 |
161 | After you've finished your todo list it's time to show us what you got! The homework that needs to be submitted is the following:
162 |
163 | 1. JavaScript exercises
164 | 2. PROJECT: The Pomodoro Clock
165 |
166 | Upload both to your forked JavaScript2 repository in GitHub. Make a pull request to the original repository.
167 |
168 | > Forgotten how to upload your homework? Go through the [guide](../hand-in-homework-guide.md) to learn how to do this again.
169 |
170 | _Deadline Saturday 23.59 CET_
171 |
--------------------------------------------------------------------------------
/Week2/README.md:
--------------------------------------------------------------------------------
1 | # Reading Material JavaScript2 Week 2
2 |
3 | ## Agenda
4 |
5 | These are the topics for week 2:
6 |
7 | 1. Synchronous vs. asynchronous
8 | - Synchronous
9 | - Asynchronous
10 | 2. Introducing asynchronicity using callbacks
11 | - Higher order functions
12 | - Functions as arguments to other functions
13 | 3. Array Functions
14 | 4. Event Loop
15 |
16 | ## 0. Video Lectures
17 |
18 | Your teacher Wilgert has made video lectures for this week's material. You can find them here: [Videos 11 - 21](https://www.youtube.com/playlist?list=PLVYDhqbgYpYU-7_oyPBkUuuis5bL1Dk8n)
19 |
20 |
21 |
22 | ## 1. Synchronous vs. asynchronous
23 |
24 | ### Synchronous
25 |
26 | In the previous module you've learned about **control flow**. In short: it's the order in which the computer executes statements in a script. In JavaScript this goes from left to right, top to bottom.
27 |
28 | Let's look at code execution from another angle. The program that executes your code can do it in two basic ways: synchronous or asynchronous. Whenever code blocks are executed line after line (from top to bottom) we call this **synchronous execution**. However, when code blocks can be executed **without having to wait until a command ends**, we call this **asynchronous execution**. This is illustrated in the following diagram:
29 |
30 | 
31 |
32 | Now imagine the following scenario:
33 |
34 | > Noer wants to have breakfast but he doesn't have any food at home. He decides he want to eat oatmeal. The ingredients (oats and milk) can be bought at the supermarket. How to do this? First Noer takes a shower. Then he puts on some clothes. Then some shoes. Then he opens the door and goes outside. Then he jumps on the bike and goes to the closest supermarket. After looking for some time he finds the ingredients. Then Noer buys the ingredients. Then he jump back on the bike and go home. Then he mixes the ingredients and makes oatmeal. Then Noer eats and feels amazing!
35 |
36 | In this example, each action could only happen after the previous has been completed. Noer can't put on his shoes, while taking a shower. Or, he can't eat oatmeal while he buys the ingredients.
37 |
38 | As you can see, each action is executed in a synchronous manner. This is to say: in a logical order sequentially and only one action at a time.
39 |
40 | **This is also how JavaScript by default operates**. Only one operation can happen at a time. If something else wants to start, it has to wait until the current action has finished.
41 |
42 | ### Asynchronous
43 |
44 | Sometimes we want to do multiple things at the same time, without each action to be dependent on each other. Asynchronous execution avoids this bottleneck. You are essentially saying, “I know this function call is going to take a great deal of time, but my program doesn’t want to wait around while it executes.” Consider the following scenario:
45 |
46 | > Wouter is feeling hungry, so he decides to go to a restaurant. He arrives there and gets into the line to order food. After ordering he takes a seat and, while he waits, reads a book. Occassionally he looks around and sees different things happening: new people enter the restaurant, some people get their food served and others are just talking. After a short while Wouter's food arrives and it's time to dig in!
47 |
48 | In this example Wouter reads a book, but that doesn't affect his meal from being prepared. While his meal is prepared there are other people walking around, eating or just talking with each other. In short: multiple things are happening simultaneously and every event is not dependent upon another.
49 |
50 | This does not happen by default in JavaScript, and needs to be invoked. A way to do that is by using `callbacks`, which you'll be learning about in the next section.
51 |
52 | ## 2. Introducing asynchronicity using callbacks
53 |
54 | Before we dive into what a `callback` is we have to understand a little about `higher order functions`.
55 |
56 | ### Higher order functions
57 |
58 | Let's start with a simple, practical definition: a higher order function is any function that can take another function as an argument or returns a function.
59 |
60 | ```js
61 | // Example 1
62 | function higherOrderFunction(anotherFunction) {
63 | anotherFunction();
64 | return;
65 | }
66 |
67 | // Example 2
68 | function anotherHigherOrderFunction() {
69 | return function () {
70 | return;
71 | };
72 | }
73 | ```
74 |
75 | Why do we need them? A higher order function integrates multiple functions, which each have a singular operational purpose. This will allow us to reuse code much more than if we had to write everything out.
76 |
77 | > Higher order functions are a core concept within a programming paradigm called "functional programming". It's not relevant at all for you to know or care about this, but it's important to be exposed to it.
78 |
79 | ### Functions as arguments to other functions
80 |
81 | Imagine the following situation:
82 |
83 | > It's 15.00 and you're studying at home for an exam on the next day. Suddenly, your phone rings. You pick up and find it's your best friend! They ask if you'd like to hang out later. What do you do? On the one hand, you'd love to hang out have fun. On the other hand, you really should study some more. You don't know so you tell your friend that you're going to _call back_ later with your answer. You end the conversation and go back to studying. Maybe you take a break or have a snack as well. On the other line your friend hangs up the phone and continues along with their day: they go out grocery shopping, cleaning the house and cooking dinner. After finishing your studies you call your friend and makes plans to go out together.
84 |
85 | This example illustrates the concept of **asynchronicity**: there are multiple processes happening simultaneously, without any single thing being dependent upon another. Your friend is not waiting by the phone until you have the answer. Or in technical terms: until the callback (which is you) has the return value (the answer to your friend's request to hang out).
86 |
87 | This is the utility of `callbacks`: they allow us to introduce asynchronicity into the control flow of an application.
88 |
89 | Study the following resources to learn more about the importance of callbacks:
90 |
91 | - [Asynchronous JavaScript](https://www.youtube.com/watch?v=YxWMxJONp7E)
92 | - [Understanding JavaScript Callbacks](https://www.youtube.com/watch?v=Nau-iEEgEoM)
93 | - [Callback Functions](https://www.youtube.com/watch?v=QRq2zMHlBz4)
94 |
95 | ## 3. Array Functions
96 |
97 | There are different ways of dealing with arrays. The most common way is by using a loop and then writing custom logic inside it in order to manipulate the values. This solution works, but it comes at several disadvantages.
98 |
99 | 1. The first disadvantage is that using loops requires us to write custom logic for each use case. This can lead to repeated code, which we always want to [avoid](https://www.youtube.com/watch?v=IGH4-ZhfVDk)
100 | 2. The second disadvantage is that a loop isn't descriptive about what it intends to do. If another developer reads that code it wouldn't be obvious what it would do, without spending time on it to decipher it
101 |
102 | There are certain functions, `array functions`, that aim to solve these two problems simultaneously. Array functions are higher order functions, because they take a function as an argument.
103 |
104 | Let's take an example: the `map()` function. It takes a function as an argument, and executes that unto each index position of the array, returning at the end a new array with all the "mapped" values.
105 |
106 | Take a look at the following code snippet to see it in action:
107 |
108 | ```js
109 | const numbers = [2, 4, 6, 8, 10];
110 |
111 | function addTwo(number) {
112 | return number + 2;
113 | }
114 |
115 | const numbersPlusTwo = numbers.map(addTwo);
116 |
117 | console.log(numbersPlusTwo);
118 | ```
119 |
120 | Copy and paste this snippet in the browser console to see how it works. As you can see the function `addTwo` added 2 to each value in the `numbers` array, because that's what the `map()` function does: it "maps" a function unto each array index.
121 |
122 | We could've done the same thing with a regular loop, but that would've been (1) much less readable, and (2) much more code:
123 |
124 | ```js
125 | const numbers = [2, 4, 6, 8, 10];
126 | const numbersPlusTwo = [];
127 |
128 | for (let i = 0; i < numbers.length; i++) {
129 | const number = numbers[i];
130 | const addedTwo = number + 2;
131 |
132 | numbersPlusTwo.push(addedTwo);
133 | }
134 |
135 | console.log(numbersPlusTwo);
136 | ```
137 |
138 | Can you see why the array function is the better way to go?
139 |
140 | Go through the following resources to learn more about the different array functions and their use:
141 |
142 | - [JavaScript Higher Order Functions & Arrays](https://www.youtube.com/watch?v=rRgD1yVwIvE)
143 | - [8 Must Know JavaScript Array Methods](https://www.youtube.com/watch?v=R8rmfD9Y5-c)
144 |
145 | ## 4. Event Loop
146 |
147 | If a webpage contains JavaScript, then the browser knows it has to execute the instructions contained in the script files. But how does the browser know what to do first? This is where the `Event Loop` comes in.
148 |
149 | Note: while this mechanism is important to be aware of, keep in mind that you won't be using it actively in development.
150 |
151 | In simple terms, the `Event Loop` is a mechanism that operates in the browser. It keeps track of the order of execution of JavaScript commands. consists of 4 parts:
152 |
153 | 1. Heap. This is where the browser assigns space in memory to each process
154 | 2. Call Stack. This is the amount of JavaScript commands (read: function calls and events) that need to be executed
155 | 3. Web APIs. These are objects (like the document) and functions (like XMLHttpRequest) that can be used within the JavaScript commands found in the Call Stack
156 | 4. Callback Queue. This is the "waiting line" for asynchronous function calls
157 |
158 | To see it in action check out the following resources:
159 |
160 | - [What the heck is an event loop?](https://www.youtube.com/watch?v=8aGhZQkoFbQ)
161 | - [JavaScript Event Loop](https://www.youtube.com/watch?v=XzXIMZMN9k4)
162 |
163 | ## Finished?
164 |
165 | Are you finished with going through the materials? High five! If you feel ready to get practical, click [here](./MAKEME.md).
166 |
--------------------------------------------------------------------------------
/Week2/homework/maartjes-work.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | const monday = [
4 | {
5 | name: 'Write a summary HTML/CSS',
6 | duration: 180,
7 | },
8 | {
9 | name: 'Some web development',
10 | duration: 120,
11 | },
12 | {
13 | name: 'Fix homework for class10',
14 | duration: 20,
15 | },
16 | {
17 | name: 'Talk to a lot of people',
18 | duration: 200,
19 | },
20 | ];
21 |
22 | const tuesday = [
23 | {
24 | name: 'Keep writing summary',
25 | duration: 240,
26 | },
27 | {
28 | name: 'Some more web development',
29 | duration: 180,
30 | },
31 | {
32 | name: 'Staring out the window',
33 | duration: 10,
34 | },
35 | {
36 | name: 'Talk to a lot of people',
37 | duration: 200,
38 | },
39 | {
40 | name: 'Look at application assignments new students',
41 | duration: 40,
42 | },
43 | ];
44 |
45 | const maartjesTasks = monday.concat(tuesday);
46 | const maartjesHourlyRate = 20;
47 |
48 | function computeEarnings(tasks, hourlyRate) {
49 | // Replace this comment and the next line with your code
50 | console.log(tasks, hourlyRate);
51 | }
52 |
53 | // eslint-disable-next-line no-unused-vars
54 | const earnings = computeEarnings(maartjesTasks, maartjesHourlyRate);
55 |
56 | // add code to convert `earnings` to a string rounded to two decimals (euro cents)
57 |
58 | console.log(`Maartje has earned €${'replace this string with the earnings rounded to euro cents'}`);
59 |
60 | // Do not change or remove anything below this line
61 | module.exports = {
62 | maartjesTasks,
63 | maartjesHourlyRate,
64 | computeEarnings,
65 | };
66 |
--------------------------------------------------------------------------------
/Week2/homework/map-filter.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | function doubleOddNumbers(numbers) {
4 | // Replace this comment and the next line with your code
5 | console.log(numbers);
6 | }
7 |
8 | const myNumbers = [1, 2, 3, 4];
9 | console.log(doubleOddNumbers(myNumbers));
10 |
11 | // Do not change or remove anything below this line
12 | module.exports = {
13 | myNumbers,
14 | doubleOddNumbers,
15 | };
16 |
--------------------------------------------------------------------------------
/Week2/js-exercises/ex1-oddOnesOut.js:
--------------------------------------------------------------------------------
1 | /**
2 |
3 | ** Exercise 1: The odd ones out **
4 |
5 | Rewrite the following function using map and filter.
6 | Avoid using for loop or forEach.
7 | The function should still behave the same.
8 |
9 | */
10 | function doubleEvenNumbers(numbers) {
11 | const newNumbers = [];
12 | for (let i = 0; i < numbers.length; i++) {
13 | if (numbers[i] % 2 === 0) {
14 | newNumbers.push(numbers[i] * 2);
15 | }
16 | }
17 | return newNumbers;
18 | }
19 |
20 | const myNumbers = [1, 2, 3, 4];
21 | console.log(doubleEvenNumbers(myNumbers)); // Logs "[4, 8]" to the console
--------------------------------------------------------------------------------
/Week2/js-exercises/ex2-whatsYourMondayWorth.js:
--------------------------------------------------------------------------------
1 | /**
2 |
3 | ** Exercise 2: What 's your Monday worth? **
4 |
5 | Write a function that finds out what your hourly rate on a Monday would be
6 | Use the map array function to take out the duration time for each task.
7 | Avoid using for loop or forEach.
8 | Multiply each duration by a per - hour rate for billing and sum it all up.
9 | Output a formatted Euro amount, rounded to Euro cents, e.g: €11.34.
10 | Make sure the function can be used on any array of objects that contain a duration property with a number value
11 |
12 | */
13 |
14 |
15 | function dayWorth(tasks, hourlyRate) {
16 | // put your code in here, the function does returns a euro formatted string
17 | }
18 |
19 | const mondayTasks = [{
20 | name: 'Daily standup',
21 | duration: 30, // specified in minutes
22 | },
23 | {
24 | name: 'Feature discussion',
25 | duration: 120,
26 | },
27 | {
28 | name: 'Development time',
29 | duration: 240,
30 | },
31 | {
32 | name: 'Talk to different members from the product team',
33 | duration: 60,
34 | },
35 | ];
36 |
37 | console.log(dayWorth(mondayTasks, 25))
38 | console.log(dayWorth(mondayTasks, 13.37))
--------------------------------------------------------------------------------
/Week2/js-exercises/ex3-lemonAllergy.js:
--------------------------------------------------------------------------------
1 | /**
2 |
3 | ** Exercise 3: Lemon allergy **
4 |
5 | Your mom bought you a basket of fruit, because you 're doing so well in HackYourFuture. How sweet of her!
6 | However, she forgot that you are allergic to lemons!Let 's quickly dispose of them before you get an attack.
7 |
8 | Write a function that uses the filter array function to take out the lemons.
9 | Avoid using for loop or forEach.
10 | Output a string that says: "My mom bought me a fruit basket, containing [array of fruits] !"
11 |
12 | */
13 |
14 |
15 | function takeOutLemons(basket) {
16 | // your code goes in here. The output is a string
17 | }
18 |
19 | const fruitBasket = ['Apple', 'Lemon', 'Grapefruit', 'Lemon', 'Banana', 'Watermelon', 'Lemon'];
20 |
21 | console.log(takeOutLemons(fruitBasket));
--------------------------------------------------------------------------------
/Week2/js-exercises/ex4-collectiveAge.js:
--------------------------------------------------------------------------------
1 | /**
2 |
3 | ** Exercise 4: Collective age **
4 |
5 | Have you ever wondered how old the HackYourFuture team members are ? Or better yet : what the collective age is ? Let 's find out!
6 |
7 | Write a function that calculates the combined age of every member
8 | Avoid using for loop or forEach.
9 | */
10 |
11 | function collectiveAge(people) {
12 | // return the sum of age for all the people
13 | }
14 |
15 | const hackYourFutureMembers = [{
16 | name: 'Wouter',
17 | age: 33
18 | },
19 | {
20 | name: 'Federico',
21 | age: 32
22 | },
23 | {
24 | name: 'Noer',
25 | age: 27
26 | },
27 | {
28 | name: 'Tjebbe',
29 | age: 22
30 | },
31 | ];
32 |
33 | console.log("The collective age of the HYF team is: " + collectiveAge(hackYourFutureMembers));
34 |
--------------------------------------------------------------------------------
/Week2/js-exercises/ex5-myFavoriteHobbies.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/Week2/js-exercises/ex5-myFavoriteHobbies.js:
--------------------------------------------------------------------------------
1 | /**
2 |
3 | ** Exercise 5: My favorite hobbies **
4 |
5 | Write a program that outputs each of these inside an HTML file
6 | Create an HTML and JavaScript file, link them together
7 | Use the map and / or forEach function to put each hobby into a list item
8 | Put the list items in an unordered list
9 | */
10 |
11 | function createHTMLList(arr) {
12 | // your code goes in here
13 | }
14 |
15 | const myHobbies = [
16 | 'Meditation',
17 | 'Reading',
18 | 'Programming',
19 | 'Hanging out with friends',
20 | 'Going to the gym',
21 | ];
--------------------------------------------------------------------------------
/Week2/project/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 | Pomodoro Clock
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
--------------------------------------------------------------------------------
/Week2/project/index.js:
--------------------------------------------------------------------------------
1 | /**
2 | In this week 's project you'll be making a Pomodoro Clock!
3 | A user can specify how many minutes the timer should be set, and with a click on the play button it starts counting down!If the user wants to pause the timer, they can do so by clicking the pause button.
4 |
5 | If the timer is running, the user can 't change the session length anymore
6 | Use at least 3 functions
7 | Display minutes and seconds
8 | If the timer finishes the timer should be replaced by the message: Time 's up!
9 | *
10 | */
--------------------------------------------------------------------------------
/Week2/test/maartjes-work.test.js:
--------------------------------------------------------------------------------
1 | const { maartjesTasks, maartjesHourlyRate, computeEarnings } = require(`../homework/maartjes-work`);
2 |
3 | describe('maartjes_work', () => {
4 | test('earnings rounded to euro cents', () => {
5 | const earnings = computeEarnings(maartjesTasks, maartjesHourlyRate);
6 | const result = earnings.toFixed(2);
7 | expect(result).toBe('373.33');
8 | });
9 | });
10 |
--------------------------------------------------------------------------------
/Week2/test/map-filter.test.js:
--------------------------------------------------------------------------------
1 | const { myNumbers, doubleOddNumbers } = require(`../homework/map-filter`);
2 |
3 | describe('map_filter', () => {
4 | test('result -> [2, 6]', () => {
5 | const result = doubleOddNumbers(myNumbers);
6 | expect(result).toEqual([2, 6]);
7 | });
8 | });
9 |
--------------------------------------------------------------------------------
/Week3/LESSONPLAN.md:
--------------------------------------------------------------------------------
1 | # Lesson Plan JavaScript2 Week 3
2 |
3 | ## Agenda
4 |
5 | The purpose of this class is to introduce to the student:
6 |
7 | - The importance of scope (global, functional and block)
8 | - What hoisting is and the difference between compile time and run time
9 | - The use and purpose of closures
10 |
11 | ## Core concepts
12 |
13 | FIRST HALF (12.00 - 13.30)
14 | ## 1. Q&A about last week's concepts & homework
15 | - synchronous vs. asynchronous
16 | - callbacks
17 | - eventloops
18 | - map, filter, reduce
19 |
20 | Note: You can ask students to explain a concept or summerise the last lecture themselves
21 |
22 | ## 2. Scope (global, functional and block)
23 | ### Explanation
24 | Scopes define the visiblity of declarations of variables and functions.
25 |
26 | The top level outside all your functions is called the _global scope_. Values defined in the global scope are accessible from everywhere in the code. Whereas, variables defined in local scope can only be accessed and altered inside the scope they were created.
27 |
28 | - `var` and `function` declarations are visible with function scope.
29 | - `let` and `const` declarations are visible with block scope. A block can be seen as a set of statements enclosed in curly brackets({}).
30 |
31 | Global scope:
32 |
33 | - Can be a real useful tool or a nightmare.
34 | - Useful in scenarios where we want to export JS modules, use third party libraries like jQuery etc.
35 | - Big risk of causing namespace clashes with multiple variables with same name being created in different places.
36 |
37 | Local Scope:
38 |
39 | - Think of local scope as any new scope that is created within the global scope.
40 | - Each function written in JavaScript creates a new local scope.
41 | - Variables defined within a function aren't available outside it. They are created when a function starts and are _in a way_ destroyed/hidden when a function ends.
42 |
43 | https://github.com/HackYourFuture/fundamentals/blob/master/fundamentals/scope.md
44 | ### Example
45 | 
46 |
47 | ```Javascript
48 | let villan = "Joker"; // | global scope
49 | // |
50 | function myFunction() { // | | function scope
51 | let hero = "Batman"; // | |
52 | if (hero === "Batman") { // | | | block scope
53 | let coHero = "Robin"; // | | |
54 | console.log(hero); // | | |
55 | console.log(coHero); // | | |
56 | console.log(villan); // | | |
57 | } // | | |
58 | console.log("------") // | |
59 | console.log(hero); // | |
60 | console.log(coHero); // | |
61 | console.log(villan); // | |
62 | } // | |
63 | // |
64 | myFunction(); // |
65 | ```
66 |
67 | And the same link as Explanation
68 | ### Exercise
69 | What happens if we use the same variable name in different scopes?
70 |
71 | ```Javascript
72 | function myFunction() {
73 | let hero = "Batman";
74 | if (true) {
75 | let hero = "The Flash";
76 | console.log(hero);
77 | }
78 | console.log(hero);
79 | }
80 |
81 | myFunction();
82 | ```
83 | Made by Yash: https://github.com/yash-kapila/HYF-JS2-Week3/blob/master/src/scope.js
84 | ### Essence
85 | Same link as Explanation
86 |
87 | ## 3. What hoisting is and the difference between compile time and run time
88 | ### Explanation
89 | ### Example
90 | ### Exercise
91 | Made by Yash: https://github.com/yash-kapila/HYF-JS2-Week3/blob/master/src/hoisting.js
92 | ### Essence
93 | Notes:
94 |
95 | - Compile time is when the JavaScript is prepared to be executed in the browser
96 | - Run time is when the JavaScript is actually executed, line by line
97 |
98 |
99 | SECOND HALF (14.00 - 16.00)
100 |
101 | ## 4. Closures
102 | ### Explanation
103 | Credits to Yash:
104 | A closure is when inner function remembers the environment in which it was created even after the outer function has returned.
105 |
106 | One powerful use of closures is to use the outer function as a factory for creating functions that are somehow related.
107 |
108 | In the code snippet underneath we can see that the `carColor` function has still got access to the outer function's properties like `wheels`, `seats` and `brand` even after the function `manufactureCar` has returned. We can then use the `carColor` as a factory to create multiple cards of the same type but with a different color.
109 | ### Example
110 | ```JavaScript
111 | function manufactureCar() {
112 | const wheels = 4;
113 | const seats = 5;
114 | const brand = 'Some Brand';
115 |
116 | return function carColor(color) {
117 | return {
118 | wheels,
119 | seats,
120 | brand,
121 | color,
122 | }
123 | };
124 | }
125 |
126 | const basicCar = manufactureCar();
127 |
128 | const redCar = basicCar('red');
129 | const blueCar = basicCar('blue');
130 | const greenCar = basicCar('green');
131 | ```
132 |
133 | ``` Javascript
134 | {
135 | 'use strict';
136 |
137 | const printName = () => {
138 | const message = 'My name is ';
139 |
140 | const displayName = name => {
141 | console.log(`${message}${name}`);
142 | }
143 |
144 | return displayName;
145 | };
146 |
147 | const name = printName();
148 | name('Yash Kapila');
149 | }
150 | ```
151 |
152 | ### Exercise
153 |
154 | ### Essence
155 |
156 |
157 |
--------------------------------------------------------------------------------
/Week3/MAKEME.md:
--------------------------------------------------------------------------------
1 | # Homework JavaScript2 Week 3
2 |
3 | ## **Todo list**
4 |
5 | 1. Practice the concepts
6 | 2. JavaScript exercises
7 | 3. Code along
8 | 4. PROJECT: The Tip Calculator
9 |
10 | ## **1. Practice the concepts**
11 |
12 | Let's get familiar with basic Javascript concepts, with interactive exercises! Check out the following resources:
13 |
14 | - [Introduction to JavaScript: Scope](https://www.codecademy.com/courses/introduction-to-javascript/lessons/scope/exercises/scope)
15 |
16 | ## **2. JavaScript exercises**
17 |
18 | > Inside of your `JavaScript2` fork, navigate to the folder `Week3`. Then to the folder `js-exercises`. In this folder you will find separate files for each exercise. Please put your code in the correct file.
19 |
20 | **Exercise 1: Add nine**
21 |
22 | Declare a function called `createBase`. The function takes a number as a parameter and return a closure, that adds a number to the base number argument.
23 |
24 | Call the function three times. The return values should be:
25 |
26 | 1. 15
27 | 2. 24
28 | 3. 33
29 |
30 | It should look a little like this:
31 |
32 | ```js
33 | function createBase() {
34 | // Put here your logic...
35 | }
36 |
37 | const addNine = createBase(6);
38 |
39 | // Put here your function calls...
40 | addNine();
41 | ```
42 |
43 | **Exercise 2: Take out the duplicates**
44 |
45 | Write a function called `removeDuplicates`, that takes in an array as an argument:
46 |
47 | ```js
48 | const letters = ['a', 'b', 'b', 'c', 'd', 'a', 'e', 'f', 'f', 'c', 'b'];
49 | ```
50 |
51 | The function should modifies the original array: it should remove duplicate letters and `return` the result.
52 |
53 | The end result should be:
54 |
55 | ```js
56 | ['a', 'b', 'c', 'd', 'e', 'f'];
57 | ```
58 |
59 | **Exercise 3: Guess the output**
60 |
61 | In this exercise you'll be presented with a code snippet. Your task is to guess the output and write out your reasoning in 50 words or less.
62 |
63 | ```js
64 | // Snippet
65 | let a = 10;
66 | const x = (function() {
67 | a = 12;
68 | return function() {
69 | alert(a);
70 | };
71 | })();
72 |
73 | x();
74 | ```
75 |
76 | **Exercise 4: Guess more**
77 |
78 | In this exercise you'll be presented with another code snippet. Guess the output and write out your reasoning in 50 words or less.
79 |
80 | ```js
81 | // Snippet
82 | const x = 9;
83 | function f1(val) {
84 | val = val + 1;
85 | return val;
86 | }
87 | f1(x);
88 | console.log(x);
89 |
90 | const y = { x: 9 };
91 | function f2(val) {
92 | val.x = val.x + 1;
93 | return val;
94 | }
95 | f2(y);
96 | console.log(y);
97 | ```
98 |
99 | **Exercise 5: The lottery machine**
100 |
101 | Don't you just love the thrill of the lottery? What if I told you we can make our own lottery machine? Let's get started!
102 |
103 | Write a function that takes 4 arguments.
104 |
105 | - A start value
106 | - An end value
107 | - A callback that executes if the number is divisible by 3
108 | - A callback that executes if the number is divisible by 5
109 |
110 | The function should first generate an array containing values from start value to end value (inclusive).
111 |
112 | Then the function should take the newly created array and iterate over it, and calling the first callback if the array value is divisible by 3.
113 |
114 | The function should call the second callback if the array value is divisible by 5.
115 |
116 | Both functions should be called if the array value is divisible by both 3 and 5.
117 |
118 | Here is a starter template:
119 |
120 | ```js
121 | function threeFive(startIndex, stopIndex, threeCallback, fiveCallback) {
122 | const numbers = [];
123 | // make array
124 | // start at beginning of array and check if you should call threeCallback or fiveCallback or go on to next
125 | }
126 |
127 | threeFive(10, 15, sayThree, sayFive);
128 |
129 | // Should create an array [10,11,12,13,14,15]
130 | // and call sayFive, sayThree, sayThree, sayFive
131 | ```
132 |
133 | ## **3. Code along**
134 |
135 | In the following "code along" you'll be making a Booklist App. A user will be able to add books to a list by filling in a form, and also delete each book entry in the list.
136 |
137 | You'll make the app using vanilla JavaScript and CSS framework [Bootstrap](https://www.getbootstrap.com).
138 |
139 | Happy learning!
140 |
141 | - [Build a Booklist App](https://www.youtube.com/watch?v=JaMCxVWtW58)
142 |
143 | ## **4. PROJECT: The Tip Calculator**
144 |
145 | > Every week ends with a project you have to build on your own. Instead of getting clear-cut instructions, you'll get a list of criteria that your project needs to measure up to.
146 |
147 | > Important! Place your code in the folder `Week3 \ project`.
148 |
149 | In this week's project you'll be making a Tip Calculator! A user can fill in 3 things:
150 |
151 | 1. The amount of the bill
152 | 2. How good the service was
153 | 3. How many people will share the bill
154 |
155 | When the button is clicked a calculation is made and the user can read the tip amount underneath.
156 |
157 | It should look like this:
158 |
159 | 
160 |
161 | Here are the requirements:
162 |
163 | - No frameworks allowed
164 | - Use a form, that has 3 input fields (the first and last can only take numbers)
165 | - The second field should have the following options:
166 |
167 | 
168 |
169 | - If there's only 1 person who shares the bill, output only the tip amount (omit the "each")
170 | - If any of the input fields are empty when the button is clicked, call an alert that says: "You need to fill in all the fields!"
171 |
172 | See it in action [here](https://tipcalculator-sandbox.mxapps.io/).
173 |
174 | Good luck!
175 |
176 | ## **SUBMIT YOUR HOMEWORK!**
177 |
178 | Finished? Good on you! The homework that needs to be submitted is the following:
179 |
180 | 1. JavaScript exercises
181 | 2. PROJECT: The Tip Calculator
182 |
183 | Upload both to your forked JavaScript2 repository in GitHub. Make a pull request to the original repository.
184 |
185 | > Forgotten how to upload your homework? Go through the [guide](../hand-in-homework-guide.md) to learn how to do this again.
186 |
187 | _Deadline Saturday 23.59 CET_
188 |
--------------------------------------------------------------------------------
/Week3/README.md:
--------------------------------------------------------------------------------
1 | # Reading Material JavaScript2 Week 3
2 |
3 | ## Agenda
4 |
5 | These are the topics for week 3:
6 |
7 | 1. Scope
8 | - Global vs. local (function and block)
9 | - Const and let
10 | 2. Hoisting
11 | - When does hoisting happen?
12 | 3. Closures
13 | - Execution context
14 | - Why do we need closures?
15 | 4. Thinking like a programmer II
16 |
17 | ## 0. Video Lectures
18 |
19 | Your teacher Wilgert has made video lectures for this week's material. You can find them here: [Videos 22 - 30](https://www.youtube.com/playlist?list=PLVYDhqbgYpYU-7_oyPBkUuuis5bL1Dk8n)
20 |
21 |
22 |
23 | ## 1. Scope
24 |
25 | One of the central concepts in programming is the idea of `context`: the meaning of any particular thing is only determined in relation to its direct surroundings. Let's take language for example. If I say the following sentence:
26 |
27 | > I never said she stole my money.
28 |
29 | Reading this it's not obvious how to interpret what the situation is about. Depending on the emphasis of the words it could mean any of the following:
30 |
31 | - _I_ never said she stole my money.
32 | - I _never_ said she stole my money.
33 | - I never _said_ she stole my money.
34 | - I never said _she_ stole my money.
35 | - I never said she _stole_ my money.
36 | - I never said she stole _my_ money.
37 | - I never said she stole my _money_.
38 |
39 | It depends on `context` for me to know what really happened.
40 |
41 | Let's draw the line to programming. Simply put, just like context gives meaning to a word, `scope` gives meaning to a variable/object.
42 |
43 | That meaning is defined by whether or not the variable is accessible. If the variable is not within the "scope" of any given code block, it can't access it. Which means it doesn't exist from the perspective of that code block.
44 |
45 | This is actually a good thing: we want to make sure that parts of our data have limited accessibility. Imagine that the password to your email account would be available everywhere, and you could easily get access to it by writing some code in the console of your browser. Do you know how easily it would be to hack into your account?
46 |
47 | For further research, check out the following:
48 |
49 | - [Variable Scope & Context](https://www.youtube.com/watch?v=WPcW83BMT3Y)
50 |
51 | ### Global vs. local (function and block)
52 |
53 | Scope can be divided into two basic types: global and local scope. In any given application, there is one global scope. But there can be many local scopes. Any variable declared outside of a function belongs to the global scope and is therefore accessible from anywhere in the code. Variables declared within a local scope are only accessible within that scope.
54 |
55 | Local scope can be further divided into two categories: function and block. Let's look at **function scope** first.
56 |
57 | A unique local scope gets created whenever a function is declared. The variables declared within will only be accessible within that scope, nowhere else. This makes it possible to declare variables within the same name in each different local scope. This also means that it's not possible to refer to a variable declared in one local scope, within another local scope.
58 |
59 | ```js
60 | function createLocalScope() {
61 | const localVariable = 'this variable can only be accessed within this function';
62 | console.log(localVariable);
63 |
64 | const localOnlyHere = 'This variable can only be accessed here, nowhere else';
65 | }
66 |
67 | function createAnotherLocalScope() {
68 | const localVariable =
69 | "Even though this variable has the same name, it has nothing to do with the other localVariable, because it doesn't exist outside of that function";
70 | console.log(localVariable);
71 | console.log(localOnlyHere);
72 | }
73 |
74 | createLocalScope();
75 | createAnotherLocalScope();
76 | ```
77 |
78 | However, variables declared within the global scope can be accessed anywhere! Actually, that's the very purpose of global scope. In the context of functions this means that you don't have to pass it as an argument, but that you can directly refer to it within the function.
79 |
80 | ```js
81 | const globalVariable = 'This variable can be accessed wherever in the code';
82 |
83 | function accessGlobalVariable() {
84 | console.log(globalVariable);
85 | }
86 | console.log(globalVariable);
87 | accessGlobalVariable();
88 | ```
89 |
90 | The second type of local scope is called **block scope**. A block, generally speaking, is any code wrapped within `{ }`. This includes conditional statements (`if` and `switch`) and loops (`for`, `while` and `do/while`).
91 |
92 | Go through the following resources to learn more about `scope`:
93 |
94 | - [JavaScript: Introduction to Scope (function scope, block scope)](https://dev.to/sandy8111112004/javascript-introduction-to-scope-function-scope-block-scope-d11)
95 | - [Understanding Scope in JavaScript](https://www.youtube.com/watch?v=SBjf9-WpLac)
96 | - [Everything you wanted to know about JavaScript scope](https://ultimatecourses.com/blog/everything-you-wanted-to-know-about-javascript-scope)
97 |
98 | ### Const and let
99 |
100 | As mentioned in the previous module, we prefer to declare variables using `const` and `let`. This is because the keywords are more descriptive and restrictive. This makes them easier to work with.
101 |
102 | In relation to scope both also behave differently: they are block scoped. This means that they can be accessed from outside a `{ }`.
103 |
104 | Go through the following resources to learn more about this:
105 |
106 | - [How let and const are scoped in JavaScript](https://wesbos.com/javascript-scoping/)
107 | - [Should you truly never use var?](https://dev.to/johnwolfe820/should-you-never-truly-use-var-bdi)
108 |
109 | ## 2. Hoisting
110 |
111 | If you look up the term "hoisting" in any dictionary, you'll find something like this:
112 |
113 | > "To raise [something] by means of ropes and pulleys"
114 |
115 | A simple example of hoisting is the hoisting of a flag on a pole. You pull on the rope and slowly but surely the flag gets raised up.
116 |
117 | In JavaScript, hoisting refers to the mechanism of the browser's JavaScript compiler to bring every function and variable declaration to the top of their `scope`, before it starts executing anything. This can be either global or local scope, depending on where it is defined.
118 |
119 | However, this does NOT mean that the actual value given to the variable or function will also be hoisted. It's just the declaration: that there are variables/functions that exist with that name.
120 |
121 | ### When does hoisting happen?
122 |
123 | Hoisting happens during `compile-time`.
124 |
125 | When you execute your JavaScript code, the interpreter goes through the code twice. The first time is called the `compile-time`, which is when your code is made ready to be executed: there will be safety checks, small optimizations and making sure the syntax is written correctly.
126 |
127 | The second time is called `run-time`, which is where it actually executes your code by going through it line by line, doing the assignments, calling the functions, etc.
128 |
129 | For more research, check out the following:
130 |
131 | - [What is Hoisting in JavaScript?](https://medium.com/javascript-in-plain-english/https-medium-com-javascript-in-plain-english-what-is-hoisting-in-javascript-a63c1b2267a1)
132 |
133 | ## 3. Closures
134 |
135 | Simply put, a closure is a function that is defined inside another function. This special function has access to the outer scope (and thus its variables), the scope that's created by the function that contains the closure function.
136 |
137 | That's nice and all, but in order to really understand what it is and why we need it we need to take a look at another concept.
138 |
139 | ### Execution context
140 |
141 | The execution context roughly equates to the 'environment' a function executes in. This consists of the following:
142 |
143 | - The variable scopes
144 | - Function arguments
145 | - The value of the `this` object (more on that in JavaScript3)
146 |
147 | Checkout the following to learn more about why this is important:
148 |
149 | - [What is the Execution Context & Stack in JavaScript?](https://blog.bitsrc.io/understanding-execution-context-and-execution-stack-in-javascript-1c9ea8642dd0)
150 |
151 | ### Why do we need closures?
152 |
153 | Closures are commonly used to give objects data privacy. We don't want certain data to be available globally. Think of it as "keeping something a secret. Take, for example, the following situation:
154 |
155 | > You want to log in to your email account, so you need a password. Usually you have that password in your head, or somewhere written down in a place that can only be accessed in a certain way. It's not out there in public, able to be accessed by anyone.
156 |
157 | In this example your password is the data you want to keep locally scoped. Your act of logging in is the inner function. The outer function could be your act of being on the computer, where your password is stored in a file somewhere.
158 |
159 | For further study please check the following resources:
160 |
161 | - [The Ultimate Guide to Execution Contexts, Hoisting, Scoping and Closures in JavaScript](https://www.youtube.com/watch?v=Nt-qa_LlUH0)
162 | - [Understanding Closures](https://www.youtube.com/watch?v=rBBwrBRoOOY)
163 | - [Master the JavaScript interview: what is a closure](https://medium.com/javascript-scene/master-the-javascript-interview-what-is-a-closure-b2f0d2152b36)
164 | - [I never understood JavaScript closures](https://medium.com/dailyjs/i-never-understood-javascript-closures-9663703368e8)
165 |
166 | ## 4. Thinking like a programmer II
167 |
168 | Becoming a good developer doesn't mean being good at any particular programming language: as a matter of fact, the language doesn't matter much.
169 |
170 | This is the secret behind being a good developer: if you understand the concept, structure and principles of what makes a software program work, it doesn't matter in what way (the syntax) it's written.
171 |
172 | This is also the reason why most developers, once they've mastered the fundamentals, are able to pick up another language quite easily. It's not because they have good memory; it's because they can recognize the patterns within the language.
173 |
174 | - [How To Think Like a Programmer](https://www.youtube.com/watch?v=azcrPFhaY9k)
175 | - [Computer Language Fundamentals: Five Core Concepts](https://blog.upperlinecode.com/computer-language-fundamentals-five-core-concepts-1aa43e929f40)
176 |
177 | ## Finished?
178 |
179 | Are you finished with going through the materials? High five! If you feel ready to get practical, click [here](./MAKEME.md).
180 |
--------------------------------------------------------------------------------
/Week3/js-exercises/ex1-AddSix.js:
--------------------------------------------------------------------------------
1 | /**
2 |
3 | ** Exercise 1: Add Six **
4 |
5 | Declare a function called `createBase`.The function takes a number as a parameter and
6 | return a closure, that adds a number to the base number argument.
7 |
8 | Call the function three times. The return values should be:
9 | 15, 24, 33
10 |
11 | */
12 |
13 | function createBase( /* ???? */ ) {
14 | // Put here your logic...
15 | }
16 |
17 | const addSix = createBase(6);
18 |
19 | // Put here your function calls...
20 |
--------------------------------------------------------------------------------
/Week3/js-exercises/ex2-RemoveDuplicates.js:
--------------------------------------------------------------------------------
1 | /**
2 |
3 | ** Exercise 2: The lottery machine **
4 | Write a function called removeDuplicates. This function accept an array as an argument
5 | does not return anything but removes any duplicate elements from the array.
6 |
7 | The function should remove duplicate elements. So the result should be:
8 | ['a', 'b', 'c', 'd', 'e', 'f']
9 |
10 | */
11 |
12 | /**
13 | * Checks your solution against correct solution
14 | * @param {Array} array your solution
15 | * @returns boolean
16 | */
17 | function checkSolution(array) {
18 | const solution = ['a', 'b', 'c', 'd', 'e', 'f'];
19 | if (array == null) return false;
20 | if (array.length !== solution.length) return false;
21 |
22 | for (let i = 0; i < solution.length; i++) {
23 | if (array[i] !== solution[i]) return false;
24 | }
25 | return true;
26 | }
27 |
28 | // WRITE YOUR FUNCTION HERE
29 |
30 | const letters = ['a', 'b', 'c', 'd', 'a', 'e', 'f', 'c', 'b'];
31 | removeDuplicates(letters);
32 |
33 | if (checkSolution(letters)) {
34 | console.log("Hooray!");
35 | }
--------------------------------------------------------------------------------
/Week3/js-exercises/ex3-GuessTheOutput.js:
--------------------------------------------------------------------------------
1 | /**
2 |
3 | ** Exercise 3: Guess the output **
4 |
5 | Look at the bellow code snippet.
6 | Can you guess the output?
7 | Write out your reasoning in 50 words or less.
8 |
9 | */
10 |
11 |
12 |
13 | let a = 10;
14 | const x = (function () {
15 | a = 12;
16 | return function () {
17 | alert(a);
18 | };
19 | })();
20 |
21 | x();
--------------------------------------------------------------------------------
/Week3/js-exercises/ex4-GuessMore.js:
--------------------------------------------------------------------------------
1 | /**
2 |
3 | ** Exercise 4: Guess more **
4 |
5 | Look at the bellow code snippet.
6 | Can you guess the output?
7 | Write out your reasoning in 50 words or less.
8 |
9 | */
10 |
11 | const x = 9;
12 |
13 | function f1(val) {
14 | val = val + 1;
15 | return val;
16 | }
17 | f1(x);
18 | console.log(x);
19 |
20 | const y = {
21 | x: 9
22 | };
23 |
24 | function f2(val) {
25 | val.x = val.x + 1;
26 | return val;
27 | }
28 | f2(y);
29 | console.log(y);
--------------------------------------------------------------------------------
/Week3/js-exercises/ex5-LotteryMachine.js:
--------------------------------------------------------------------------------
1 | /**
2 |
3 | ** Exercise 5: The lottery machine **
4 |
5 | Don't you just love the thrill of the lottery? What if I told you we can make our own lottery machine? Let'
6 | s get started!
7 |
8 | Write a
9 | function that takes 4 arguments.
10 |
11 | - A start value
12 | - An end value
13 | - A callback that executes if the number is divisible by 3
14 | - A callback that executes if the number is divisible by 5
15 |
16 | The function should first generate an array containing values from start value to end value(inclusive).
17 |
18 | Then the function should take the newly created array and iterate over it, and calling the first callback
19 | if the array value is divisible by 3.
20 |
21 | The function should call the second callback
22 | if the array value is divisible by 5.
23 |
24 | Both functions should be called
25 | if the array value is divisible by both 3 and 5.
26 |
27 | */
28 |
29 | function threeFive(startIndex, stopIndex, threeCallback, fiveCallback) {
30 | const numbers = [];
31 | // make array
32 | // start at beginning of array and check if you should call threeCallback or fiveCallback or go on to next
33 | }
34 |
35 | threeFive(10, 15, sayThree, sayFive);
36 |
37 | // Should create an array [10,11,12,13,14,15]
38 | // and call sayFive, sayThree, sayThree, sayFive
--------------------------------------------------------------------------------
/Week3/old-homework/step2-1.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | function foo(func) {
4 | // What to do here?
5 | // Replace this comment and the next line with your code
6 | console.log(func);
7 | }
8 |
9 | function bar() {
10 | console.log('Hello, I am bar!');
11 | }
12 |
13 | foo(bar);
14 |
15 | // Do not change or remove anything below this line
16 | module.exports = foo;
17 |
--------------------------------------------------------------------------------
/Week3/old-homework/step2-2.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | function threeFive(startIndex, stopIndex, threeCallback, fiveCallback) {
4 | const numbers = [];
5 |
6 | // Replace this comment and the next line with your code
7 | console.log(startIndex, stopIndex, threeCallback, fiveCallback, numbers);
8 | }
9 |
10 | function sayThree(number) {
11 | // Replace this comment and the next line with your code
12 | console.log(number);
13 | }
14 |
15 | function sayFive(number) {
16 | // Replace this comment and the next line with your code
17 | console.log(number);
18 | }
19 |
20 | threeFive(10, 15, sayThree, sayFive);
21 |
22 | // Do not change or remove anything below this line
23 | module.exports = threeFive;
24 |
--------------------------------------------------------------------------------
/Week3/old-homework/step2-3.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | // Use a 'for' loop
4 | function repeatStringNumTimesWithFor(str, num) {
5 | // eslint-disable-next-line prefer-const
6 | let result = '';
7 |
8 | // Replace this comment and the next line with your code
9 | console.log(str, num, result);
10 |
11 | return result;
12 | }
13 |
14 | console.log('for', repeatStringNumTimesWithFor('abc', 3));
15 |
16 | // Use a 'while' loop
17 | function repeatStringNumTimesWithWhile(str, num) {
18 | // eslint-disable-next-line prefer-const
19 | let result = '';
20 |
21 | // Replace this comment and the next line with your code
22 | console.log(str, num, result);
23 |
24 | return result;
25 | }
26 |
27 | console.log('while', repeatStringNumTimesWithWhile('abc', 3));
28 |
29 | // Use a 'do...while' loop
30 | function repeatStringNumTimesWithDoWhile(str, num) {
31 | // eslint-disable-next-line prefer-const
32 | let result = '';
33 |
34 | // Replace this comment and the next line with your code
35 | console.log(str, num, result);
36 |
37 | return result;
38 | }
39 |
40 | console.log('do-while', repeatStringNumTimesWithDoWhile('abc', 3));
41 |
42 | // Do not change or remove anything below this line
43 | module.exports = {
44 | repeatStringNumTimesWithFor,
45 | repeatStringNumTimesWithWhile,
46 | repeatStringNumTimesWithDoWhile,
47 | };
48 |
--------------------------------------------------------------------------------
/Week3/old-homework/step2-4.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | function Dog() {
4 | // add your code here
5 | }
6 |
7 | const hound = new Dog();
8 |
9 | // Do not change or remove anything below this line
10 | module.exports = hound;
11 |
--------------------------------------------------------------------------------
/Week3/old-homework/step2-5.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | function multiplyAll(arr) {
4 | // eslint-disable-next-line
5 | let product = 1;
6 |
7 | // Replace this comment and the next line with your code
8 | console.log(arr, product);
9 |
10 | return product;
11 | }
12 |
13 | const result = multiplyAll([[1, 2], [3, 4], [5, 6]]);
14 | console.log(result); // 720
15 |
16 | // Do not change or remove anything below this line
17 | module.exports = multiplyAll;
18 |
--------------------------------------------------------------------------------
/Week3/old-homework/step2-6.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | const arr2d = [[1, 2], [3, 4], [5, 6]];
4 | const arr3d = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]];
5 |
6 | function flattenArray2d(arr) {
7 | // Replace this comment and the next line with your code
8 | console.log(arr);
9 | }
10 |
11 | function flattenArray3d(arr) {
12 | // Replace this comment and the next line with your code
13 | console.log(arr);
14 | }
15 |
16 | console.log(flattenArray2d(arr2d)); // -> [1, 2, 3, 4, 5, 6]
17 | console.log(flattenArray3d(arr3d)); // -> [1, 2, 3, 4, 5, 6, 7, 8]
18 |
19 | // Do not change or remove anything below this line
20 | module.exports = {
21 | flattenArray2d,
22 | flattenArray3d,
23 | };
24 |
--------------------------------------------------------------------------------
/Week3/old-homework/step2-7.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | const x = 9;
4 | function f1(val) {
5 | val = val + 1;
6 | return val;
7 | }
8 |
9 | f1(x);
10 |
11 | console.log(x);
12 |
13 | const y = { x: 9 };
14 | function f2(val) {
15 | val.x = val.x + 1;
16 | return val;
17 | }
18 |
19 | f2(y);
20 |
21 | console.log(y);
22 |
23 | // Add your explanation as a comment here
24 |
--------------------------------------------------------------------------------
/Week3/old-homework/step3-bonus.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | const values = ['a', 'b', 'c', 'd', 'a', 'e', 'f', 'c'];
4 |
5 | function makeUnique(arr) {
6 | // Replace this comment and the next line with your code
7 | console.log(arr);
8 | }
9 |
10 | const uniqueValues = makeUnique(values);
11 | console.log(uniqueValues);
12 |
13 | // Do not change or remove anything below this line
14 | module.exports = makeUnique;
15 |
--------------------------------------------------------------------------------
/Week3/old-homework/step3.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | function createBase(base) {
4 | // Replace this comment and the next line with your code
5 | console.log(base);
6 | }
7 |
8 | const addSix = createBase(6);
9 |
10 | console.log(addSix(10)); // returns 16
11 | console.log(addSix(21)); // returns 27
12 |
13 | // Do not change or remove anything below this line
14 | module.exports = createBase;
15 |
--------------------------------------------------------------------------------
/Week3/project/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 | Tip Calculator
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
--------------------------------------------------------------------------------
/Week3/project/index.js:
--------------------------------------------------------------------------------
1 | // Your code goes in here
2 |
3 | document.querySelector("#app").innerText = "Tip Calculator";
--------------------------------------------------------------------------------
/Week3/test/console-test.js:
--------------------------------------------------------------------------------
1 | // see: https://stackoverflow.com/questions/44890836/how-to-test-console-log-output-using-jest-or-other-javascript-testing-framework?rq=1
2 |
3 | function consoleTest(filename, expectedOutput) {
4 | let outputData = '';
5 | // eslint-disable-next-line no-return-assign
6 | const storeLog = (...inputs) => (outputData += inputs.join(' '));
7 |
8 | test(filename, () => {
9 | console.log = jest.fn(storeLog);
10 | // eslint-disable-next-line global-require
11 | require('../homework/' + filename);
12 | expect(outputData).toBe(expectedOutput);
13 | });
14 | }
15 |
16 | module.exports = consoleTest;
17 |
--------------------------------------------------------------------------------
/Week3/test/step2-1.test.js:
--------------------------------------------------------------------------------
1 | const foo = require('../homework/step2-1');
2 |
3 | const mockFn = jest.fn(() => undefined);
4 |
5 | describe('step2-1', () => {
6 | test('foo calls func', () => {
7 | foo(mockFn);
8 | expect(mockFn.mock.calls.length).toBe(1);
9 | });
10 | });
11 |
--------------------------------------------------------------------------------
/Week3/test/step2-2.test.js:
--------------------------------------------------------------------------------
1 | const threeFive = require('../homework/step2-2');
2 |
3 | const mockSayThree = jest.fn(() => undefined);
4 | const mockSayFive = jest.fn(() => undefined);
5 |
6 | describe('step2-2', () => {
7 | test('12 and 15 divisible by 3', () => {
8 | threeFive(10, 15, mockSayThree, () => undefined);
9 |
10 | expect(mockSayThree.mock.calls.length).toBe(2);
11 | expect(mockSayThree.mock.calls[0][0]).toBe(12);
12 | expect(mockSayThree.mock.calls[1][0]).toBe(15);
13 | });
14 |
15 | test('10 and 15 divisible by 5', () => {
16 | threeFive(10, 15, () => undefined, mockSayFive);
17 |
18 | expect(mockSayFive.mock.calls.length).toBe(2);
19 | expect(mockSayFive.mock.calls[0][0]).toBe(10);
20 | expect(mockSayFive.mock.calls[1][0]).toBe(15);
21 | });
22 | });
23 |
--------------------------------------------------------------------------------
/Week3/test/step2-3.test.js:
--------------------------------------------------------------------------------
1 | const {
2 | repeatStringNumTimesWithFor,
3 | repeatStringNumTimesWithWhile,
4 | repeatStringNumTimesWithDoWhile,
5 | } = require('../homework/step2-3');
6 |
7 | describe('step2-3 with for-loop', () => {
8 | test('num = 3', () => {
9 | const result = repeatStringNumTimesWithFor('abc', 3);
10 | expect(result).toBe('abcabcabc');
11 | });
12 |
13 | test('num = 1', () => {
14 | const result = repeatStringNumTimesWithFor('abc', 1);
15 | expect(result).toBe('abc');
16 | });
17 |
18 | test('num = -2', () => {
19 | const result = repeatStringNumTimesWithFor('abc', -2);
20 | expect(result).toBe('');
21 | });
22 |
23 | test('num = 0', () => {
24 | const result = repeatStringNumTimesWithFor('abc', 0);
25 | expect(result).toBe('');
26 | });
27 | });
28 |
29 | describe('step2-3 with while-loop', () => {
30 | test('num = 3', () => {
31 | const result = repeatStringNumTimesWithWhile('abc', 3);
32 | expect(result).toBe('abcabcabc');
33 | });
34 |
35 | test('num = 1', () => {
36 | const result = repeatStringNumTimesWithWhile('abc', 1);
37 | expect(result).toBe('abc');
38 | });
39 |
40 | test('num = 0', () => {
41 | const result = repeatStringNumTimesWithWhile('abc', 0);
42 | expect(result).toBe('');
43 | });
44 |
45 | test('num = -2', () => {
46 | const result = repeatStringNumTimesWithWhile('abc', -2);
47 | expect(result).toBe('');
48 | });
49 | });
50 |
51 | describe('step2-3 with do-while-loop', () => {
52 | test('num = 3', () => {
53 | const result = repeatStringNumTimesWithDoWhile('abc', 3);
54 | expect(result).toBe('abcabcabc');
55 | });
56 |
57 | test('num = 1', () => {
58 | const result = repeatStringNumTimesWithDoWhile('abc', 1);
59 | expect(result).toBe('abc');
60 | });
61 |
62 | test('num = 0', () => {
63 | const result = repeatStringNumTimesWithDoWhile('abc', 0);
64 | expect(result).toBe('');
65 | });
66 |
67 | test('num = -2', () => {
68 | const result = repeatStringNumTimesWithDoWhile('abc', -2);
69 | expect(result).toBe('');
70 | });
71 | });
72 |
--------------------------------------------------------------------------------
/Week3/test/step2-4.test.js:
--------------------------------------------------------------------------------
1 | const hound = require('../homework/step2-4');
2 |
3 | describe('step2-4', () => {
4 | test('hound to be an object', () => {
5 | expect(typeof hound).toBe('object');
6 | });
7 |
8 | test('hound.name to be a string', () => {
9 | expect(typeof hound.name).toBe('string');
10 | });
11 |
12 | test('hound.color to be a string', () => {
13 | expect(typeof hound.color).toBe('string');
14 | });
15 |
16 | test('hound.numLegs to be a number', () => {
17 | expect(typeof hound.numLegs).toBe('number');
18 | });
19 | });
20 |
--------------------------------------------------------------------------------
/Week3/test/step2-5.test.js:
--------------------------------------------------------------------------------
1 | const multiplyAll = require('../homework/step2-5');
2 |
3 | describe('step2-5', () => {
4 | test('result to be product of array elements', () => {
5 | const result = multiplyAll([[1, 2], [3, 4], [5, 6, 7]]);
6 | expect(result).toBe(5040);
7 | });
8 | });
9 |
--------------------------------------------------------------------------------
/Week3/test/step2-6.test.js:
--------------------------------------------------------------------------------
1 | /* eslint-disable no-return-assign, dot-notation */
2 | const { flattenArray2d, flattenArray3d } = require('../homework/step2-6');
3 |
4 | const arr2d = [[1, 2], [3, 4], [5, 6]];
5 | const expected2d = [1, 2, 3, 4, 5, 6];
6 |
7 | const arr3d = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]];
8 | const expected3d = [1, 2, 3, 4, 5, 6, 7, 8];
9 |
10 | describe('step2-6', () => {
11 | test('flattenArray2d -> [1, 2, 3, 4, 5, 6]', () => {
12 | const result = flattenArray2d(arr2d);
13 | expect(result).toEqual(expected2d);
14 | });
15 |
16 | test('flattenArray3d -> [1, 2, 3, 4, 5, 6, 7, 8]', () => {
17 | const result = flattenArray3d(arr3d);
18 | expect(result).toEqual(expected3d);
19 | });
20 | });
21 |
--------------------------------------------------------------------------------
/Week3/test/step3-bonus.test.js:
--------------------------------------------------------------------------------
1 | const makeUnique = require(`../homework/step3-bonus`);
2 |
3 | describe('step3-bonus', () => {
4 | test('array should not contain duplicates', () => {
5 | const values = ['a', 'b', 'c', 'd', 'a', 'e', 'f', 'c'];
6 | const expected = ['a', 'b', 'c', 'd', 'e', 'f'];
7 | const result = makeUnique(values);
8 | expect(result).toEqual(expected);
9 | });
10 | });
11 |
--------------------------------------------------------------------------------
/Week3/test/step3.test.js:
--------------------------------------------------------------------------------
1 | const createBase = require(`../homework/step3`);
2 |
3 | describe('step3', () => {
4 | test('base = 6', () => {
5 | const addSix = createBase(6);
6 | const result = addSix(10);
7 | expect(result).toBe(16);
8 | });
9 |
10 | test('base = 10', () => {
11 | const addTen = createBase(10);
12 | const result = addTen(10);
13 | expect(result).toBe(20);
14 | });
15 | });
16 |
--------------------------------------------------------------------------------
/assets/array-methods-exercises.js:
--------------------------------------------------------------------------------
1 | const flowers = [
2 | { name: 'tulip', color: 'red' },
3 | { name: 'dandelion', color: 'yellow' },
4 | { name: 'rose', color: 'red' },
5 | { name: 'daisy', color: 'white' },
6 | { name: 'lily', color: 'white' },
7 | ];
8 |
9 | // Exercise 1
10 | // use `map` to make the first letter of al flowers a capital.
11 | // so 'tulip' becomes 'Tulip' etc.
12 |
13 | // Exercise 2
14 | // use `filter` to get only the flowers with a name of 4 characters
15 |
16 | // Exercise 3
17 | // use `reduce` to create an object that contains
18 | // the total number of flowers for each color
19 |
20 | // Exercise 4 (bonus)
21 | // use `some` or `every` in combination with another array method
22 | // to find out if all flowers with five letters are red
23 |
--------------------------------------------------------------------------------
/assets/call_stack_example.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/HackYourFuture/JavaScript2/8e77a7ea1bee5d6aed42d4bee5fcb6f683c4f40c/assets/call_stack_example.png
--------------------------------------------------------------------------------
/assets/callbacks.js:
--------------------------------------------------------------------------------
1 | // Made by Yash
2 | {
3 | 'use strict';
4 |
5 | // Example #1
6 | // const btn = document.getElementById('btn');
7 | // btn.addEventListener('click', () => {
8 | // console.log('CLICKED');
9 | // });
10 |
11 | // Example #2
12 | // const arr = [1,2,3,4,5];
13 | // const double = arr.map(el => el * 2);
14 | // console.log('DOUBLED', double);
15 |
16 | // Example #3
17 | // const parent = callback => {
18 | // // What's the "typeof callback"?
19 | // console.log('AT START');
20 | // setTimeout(() => {
21 | // callback();
22 | // }, 2000);
23 | // console.log('AT END');
24 | // };
25 |
26 | // const child = () => {
27 | // console.log('I AM CHILD');
28 | // };
29 |
30 | // parent(child);
31 |
32 | // Example #4 - passing arguments to callback
33 | // const target = (callback, arg) => {
34 | // console.log('AT START');
35 | // setTimeout(() => {
36 | // callback(arg);
37 | // }, 2000);
38 | // console.log('AT END');
39 | // };
40 |
41 | // const func = number => {
42 | // console.log('CALLING CHILD WITH NUMBER:', number);
43 | // };
44 |
45 | // target(func, 10);
46 | }
47 |
--------------------------------------------------------------------------------
/assets/domtree.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/HackYourFuture/JavaScript2/8e77a7ea1bee5d6aed42d4bee5fcb6f683c4f40c/assets/domtree.png
--------------------------------------------------------------------------------
/assets/hoisting.js:
--------------------------------------------------------------------------------
1 | {
2 | 'use strict'
3 |
4 | /*
5 | * Function Hoisting
6 | */
7 |
8 | // Exercise #1
9 | // abc();
10 | // function abc() {
11 | // console.log('INSIDE FUNCTION ABC');
12 | // }
13 |
14 | // xyz();
15 | // var xyz = function() {
16 | // console.log('INSIDE FUNCTION XYZ');
17 | // };
18 |
19 | // Exercise #2
20 | // function foo1() {
21 | // function bar() {
22 | // return 3;
23 | // }
24 | // return bar();
25 | // function bar() {
26 | // return 8;
27 | // }
28 | // }
29 | // console.log(foo1());
30 |
31 | // Exercise #3
32 | // function foo2(){
33 | // var bar = function() {
34 | // return 3;
35 | // };
36 | // return bar();
37 | // var bar = function() {
38 | // return 8;
39 | // };
40 | // }
41 | // console.log(foo2());
42 |
43 | // Exercise #4
44 | // console.log(foo3());
45 | // function foo3(){
46 | // var bar = function() {
47 | // return 3;
48 | // };
49 | // return bar();
50 | // var bar = function() {
51 | // return 8;
52 | // };
53 | // }
54 |
55 | // Exercise #5
56 | // function foo4(){
57 | // return bar();
58 | // var bar = function() {
59 | // return 3;
60 | // };
61 | // var bar = function() {
62 | // return 8;
63 | // };
64 | // }
65 | // console.log(foo4());
66 |
67 | /*
68 | * Variable Hoisting
69 | */
70 |
71 | // Exercise #1
72 | // arr = [10,20,30];
73 | // console.log(arr);
74 | // var arr;
75 |
76 | // console.log(obj);
77 | // var obj = { a: 10, b: 20 };
78 |
79 | // Exercise #2
80 | // console.log(num1);
81 | // let num1 = 10;
82 |
83 | /*
84 | * Variable and Function hoisting combined
85 | */
86 |
87 | // Exercise #1
88 | // function parent() {
89 | // function hoisted() {
90 | // return "I'm a function";
91 | // }
92 | // hoisted = "I'm a variable";
93 | // return hoisted();
94 | // }
95 | // console.log(parent());
96 |
97 | // Exercise #2 (Tricky)
98 | // function parent() {
99 | // var hoisted = "I'm a variable";
100 | // function hoisted() {
101 | // return "I'm a function";
102 | // }
103 | // return hoisted();
104 | // }
105 | // console.log(parent());
106 |
107 | // Exercise #3
108 | // function func() {
109 | // function foo() { };
110 | // return foo;
111 | // foo = 10;
112 | // foo = 1;
113 | // }
114 | // console.log(typeof func());
115 |
116 | // Exercise #4
117 | // function func() {
118 | // return foo;
119 | // foo = 10;
120 | // var foo = 1;
121 | // function foo() { };
122 | // }
123 | // console.log(typeof func());
124 | }
--------------------------------------------------------------------------------
/assets/javascript-sync-vs-async.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/HackYourFuture/JavaScript2/8e77a7ea1bee5d6aed42d4bee5fcb6f683c4f40c/assets/javascript-sync-vs-async.png
--------------------------------------------------------------------------------
/assets/javascript2.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/HackYourFuture/JavaScript2/8e77a7ea1bee5d6aed42d4bee5fcb6f683c4f40c/assets/javascript2.png
--------------------------------------------------------------------------------
/assets/pomodoro.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/HackYourFuture/JavaScript2/8e77a7ea1bee5d6aed42d4bee5fcb6f683c4f40c/assets/pomodoro.png
--------------------------------------------------------------------------------
/assets/randomquotegenerator.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/HackYourFuture/JavaScript2/8e77a7ea1bee5d6aed42d4bee5fcb6f683c4f40c/assets/randomquotegenerator.png
--------------------------------------------------------------------------------
/assets/scope.js:
--------------------------------------------------------------------------------
1 | // Global scope variable available throughout the application.
2 | // Try doing console.log(globalVar) in callbacks.js or closures.js
3 | const globalVar = 100;
4 |
5 | {
6 | 'use strict';
7 |
8 | // Exercise #1
9 | // const firstLocalFunction = () => {
10 | // const localVar = "I am a local variable";
11 | // console.log('INSIDE FIRST LOCAL FUNCTION', localVar, globalVar);
12 | // };
13 |
14 | // firstLocalFunction();
15 |
16 | // Exercise #2
17 | // const secondLocalFunction = () => {
18 | // // can use the same variable name here because of local scoping
19 | // const localVar = 10;
20 | // const nestedFunction = () => {
21 | // const nestedVar = "I am a nested variable";
22 | // console.log('INSIDE NESTED FUNCTION', nestedVar, localVar, globalVar);
23 | // };
24 |
25 | // // nestedVar is not visible here
26 | // nestedFunction();
27 | // };
28 |
29 | // secondLocalFunction();
30 |
31 | // localVar defined inside the functions isn't visible here
32 |
33 | // Exercise #3
34 | // const myFunction = () => {
35 | // const localVar = 10;
36 |
37 | // if (localVar === 10) {
38 | // const innerVar = 100;
39 | // console.log('INSIDE IF BLOCK', localVar, innerVar);
40 | // }
41 |
42 | // console.log(innerVar);
43 | // };
44 |
45 | // myFunction();
46 |
47 | // Exercise #4
48 | // const trickFunction = () => {
49 | // const arr = [10, 12, 15, 21];
50 | // for (var i = 0; i < arr.length; i++) {
51 | // setTimeout(function() {
52 | // console.log('Index: ' + i + ', element: ' + arr[i]);
53 | // }, 3000);
54 | // }
55 | // };
56 |
57 | // trickFunction();
58 | };
--------------------------------------------------------------------------------
/assets/scopes.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/HackYourFuture/JavaScript2/8e77a7ea1bee5d6aed42d4bee5fcb6f683c4f40c/assets/scopes.png
--------------------------------------------------------------------------------
/assets/servicequality.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/HackYourFuture/JavaScript2/8e77a7ea1bee5d6aed42d4bee5fcb6f683c4f40c/assets/servicequality.png
--------------------------------------------------------------------------------
/assets/simple-dom.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/HackYourFuture/JavaScript2/8e77a7ea1bee5d6aed42d4bee5fcb6f683c4f40c/assets/simple-dom.png
--------------------------------------------------------------------------------
/assets/submit-homework.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/HackYourFuture/JavaScript2/8e77a7ea1bee5d6aed42d4bee5fcb6f683c4f40c/assets/submit-homework.png
--------------------------------------------------------------------------------
/assets/sync-async.js:
--------------------------------------------------------------------------------
1 | const greenGrocer = {
2 | buyApples: function(quantity) {
3 | return quantity + ' apples';
4 | },
5 | buyTomatoes: function(quantity) {
6 | return quantity + ' tomatoes';
7 | },
8 | buyCauliflower: function(quantity) {
9 | return quantity + ' cauliflower';
10 | },
11 | };
12 |
13 | const cheeseShop = {
14 | buyCheese: function(type, weight) {
15 | this.cutCheese(type, weight);
16 |
17 | return weight + 'gr ' + type + ' cheese';
18 | },
19 |
20 | cutCheese: function(type, weight) {
21 | const stopTime = Date.now() + 100;
22 | while (Date.now() < stopTime);
23 | },
24 | };
25 |
26 | const bakery = {
27 | buyBread: function(breadReadyCallback, type, quantity) {
28 | setTimeout(function() {
29 | breadReadyCallback(quantity + ' ' + type);
30 | }, 1000);
31 | },
32 | };
33 |
34 | function visitGreengrocer() {
35 | console.log('=== Greengrocer ===');
36 |
37 | const beforeBuy = Date.now();
38 |
39 | const fruitsAndVegetables = [
40 | greenGrocer.buyApples(2),
41 | greenGrocer.buyTomatoes(2),
42 | greenGrocer.buyCauliflower(1),
43 | ];
44 |
45 | const timeTaken = (Date.now() - beforeBuy).toFixed(2);
46 |
47 | console.log('You bought: ', fruitsAndVegetables);
48 | console.log('This took: ' + timeTaken + 'ms\n');
49 | }
50 |
51 | function visitCheeseShop() {
52 | console.log('=== Cheese Shop ===');
53 | const beforeBuy = Date.now();
54 |
55 | const cheese = cheeseShop.buyCheese('belegen', 500);
56 |
57 | const timeTaken = (Date.now() - beforeBuy).toFixed(2);
58 |
59 | console.log('You bought: ' + cheese + '');
60 | console.log('This took: ' + timeTaken + 'ms\n');
61 | }
62 |
63 | function visitBakery() {
64 | console.log('=== Bakery ===');
65 | const beforeBuy = Date.now();
66 |
67 | const breadReady = function(bread) {
68 | const timeTaken = (Date.now() - beforeBuy).toFixed(2);
69 | console.log('--- Callback from Bakery ---');
70 | console.log('You bought: ' + bread + '');
71 | console.log('This took: ' + timeTaken + 'ms\n');
72 | };
73 |
74 | bakery.buyBread(breadReady, 'fijn volkoren', 1);
75 | console.log(`We'll call you back!\n`);
76 | }
77 |
78 | visitGreengrocer(); // ?.
79 | visitBakery(); // ?.
80 | visitCheeseShop(); // ?.
81 |
--------------------------------------------------------------------------------
/assets/tipcalculator.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/HackYourFuture/JavaScript2/8e77a7ea1bee5d6aed42d4bee5fcb6f683c4f40c/assets/tipcalculator.png
--------------------------------------------------------------------------------
/assets/weekflow.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/HackYourFuture/JavaScript2/8e77a7ea1bee5d6aed42d4bee5fcb6f683c4f40c/assets/weekflow.png
--------------------------------------------------------------------------------
/assets/wilgert.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/HackYourFuture/JavaScript2/8e77a7ea1bee5d6aed42d4bee5fcb6f683c4f40c/assets/wilgert.png
--------------------------------------------------------------------------------
/hand-in-homework-guide.md:
--------------------------------------------------------------------------------
1 | # How to hand in homework
2 |
3 | In this module you'll submit your homework only using GIT and GitHub.
4 |
5 | 1. [GitHub](https://www.github.com/HackYourFuture/JavaScript2)
6 |
7 | ## 1. GitHub homework guide
8 |
9 |
10 |
11 | Watch the video (by clicking the image) or go through the following walk-through to learn how to submit your homework:
12 |
13 | ONE TIME ONLY (START OF EVERY MODULE)
14 |
15 | 1. Create a [fork](https://help.github.com/en/articles/fork-a-repo) of the following repository: [HackYourHomework/JavaScript2](https://www.github.com/hackyourhomework/javascript2). You do this by using the `fork` option on the top right
16 | 2. Navigate to the URL of the forked repository (it should be in your personal GitHub account, under "repositories", under the name `/JavaScript2`)
17 | 3. Clone the repository, using SSH, to your local machine. You can do this by typing in `git clone ` in the command line
18 | 4. On your local machine, navigate to the folder using the command line
19 | 5. Make sure you've cloned it correctly by running `git status` and `git remote -v` from the command line
20 |
21 | EVERY WEEK
22 |
23 | 1. Create a new branch for each week you have homework. For example, for the week 1 homework for JavaScript2 create a branch called `week-1-homework-YOUR_NAME`
24 | 2. Inside the week folder, create another folder called `homework`. Create your homework files in there, while on the correct branch
25 | 3. Once you're finished, `add` and `commit` everything. Make the commit message meaningful, for example `finished project for homework week1`
26 | 4. Push the branch to your forked repository (`/JavaScript2`)
27 | 5. On the GitHub page of this repository, click on the `create pull request` button. Make sure the `base repository` is `HackYourHomework/JavaScript2`, on branch master
28 | 6. Give the pull request a title in the following format:
29 |
30 | ```markdown
31 | Homework week 1
32 | ```
33 |
34 | 7. Submit the pull request from your forked repository branch into the `master` branch of the original repository (`HackYourHomework/JavaScript2`)
35 | 8. Do a little victory dance because you did it! Good job!
36 |
37 | If you have any questions or if something is not entirely clear ¯\\\_(ツ)\_/¯, please ask/comment on Slack!
38 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "javascript2",
3 | "version": "1.0.0",
4 | "description": "HYF JavaScript2 module",
5 | "main": "index.js",
6 | "scripts": {
7 | "lint": "eslint \"**/homework/**/*.js\"",
8 | "test": "npm run lint",
9 | "test-week1": "eslint Week1/homework",
10 | "test-week2": "eslint Week2/homework && jest Week2",
11 | "test-week3": "eslint Week3/homework && jest Week3",
12 | "test-maartjes-work": "jest maartjes-work",
13 | "test-map-filter": "jest map-filter",
14 | "test-step2-1": "jest step2-1",
15 | "test-step2-2": "jest step2-2",
16 | "test-step2-3": "jest step2-3",
17 | "test-step2-4": "jest step2-4",
18 | "test-step2-5": "jest step2-5",
19 | "test-step2-6": "jest step2-6",
20 | "test-step3": "jest step3",
21 | "test-step3-bonus": "jest step3-bonus"
22 | },
23 | "repository": {
24 | "type": "git",
25 | "url": "git+https://github.com/HackYourFuture/JavaScript2.git"
26 | },
27 | "author": "HackYourFuture",
28 | "license": "ISC",
29 | "bugs": {
30 | "url": "https://github.com/HackYourFuture/JavaScript2/issues"
31 | },
32 | "homepage": "https://github.com/HackYourFuture/JavaScript2#readme",
33 | "devDependencies": {
34 | "eslint": "^5.9.0",
35 | "eslint-config-airbnb": "^17.1.0",
36 | "eslint-config-airbnb-base": "^13.1.0",
37 | "eslint-config-prettier": "^3.3.0",
38 | "eslint-plugin-import": "^2.14.0",
39 | "eslint-plugin-jest": "^21.26.0",
40 | "eslint-plugin-jsx-a11y": "^6.1.2",
41 | "eslint-plugin-prettier": "^3.0.0",
42 | "eslint-plugin-react": "^7.11.1",
43 | "jest": "^25.1.0",
44 | "prettier": "^1.15.2"
45 | }
46 | }
47 |
--------------------------------------------------------------------------------
/prettier.config.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | printWidth: 100,
3 | singleQuote: true,
4 | trailingComma: 'all',
5 | bracketSpacing: true,
6 | jsxBracketSameLine: false,
7 | tabWidth: 2,
8 | semi: true,
9 | };
10 |
--------------------------------------------------------------------------------
/test/README.md:
--------------------------------------------------------------------------------
1 | # JavaScript1 and JavaScript2 Test
2 |
3 | You’ll be doing a comprehension test. It will be about the most important JavaScript concepts you’ve learned about so far (JavaScript1 and JavaScript2).
4 |
5 | ## Practical information
6 | Practical information about the test will be shared in the class channel prior to the test. Keep an eye on it!
7 |
8 | ## Purpose of the test
9 | The purpose of this exam is to test your comprehension of JavaScript 1 and JavaScript 2 concepts.
10 | - The goal for us is to know how solid your knowledge is and if you need any extra assistance throughout the program.
11 | - The goal for you is to test how well enough you master the material so far.
12 | Like the homework you will get feedback and are expected to improve upon your weak points.
13 |
14 | ## Test material
15 | These are the most important concepts that will be tested:
16 | - `Variables`
17 | - `Data types` (`strings`, `numbers`, `arrays`, `objects`, `booleans`)
18 | - `Conditional statements` (`if`/`switch` statement)
19 | - `Loops`
20 | - `ES5 functions` and `arrow functions`
21 | - How to use JavaScript to do basic `DOM manipulations` (add, modify and remove DOM elements)
22 | - `Code commenting`
23 | - `Array functions` (`map` and `filter`)
24 | - `Callbacks`
25 |
26 | ## Preparation
27 | Advice on how to optimally prepare:
28 | - Find out 2 things about each concepts listed above: (1) how does the basic structure look and (2) what is the most common use case.
29 |
30 | - Be familiar with creating a new project repository in github. For the test you will get some files to edit and they will need to be uploaded to your github.
31 |
32 | - Ask questions through Slack to your teachers and/or your classmates
33 |
34 | - Practice for understanding (why something is the case), NOT just for repetition’s sake (and hoping ‘you will understand it one day’).
35 |
36 | - Make a summary of all the study material.
37 |
38 | - After you prepared try to make the sample questions that are in this file.
39 |
40 | ## During the test
41 | Advise on how to make a test:
42 | - **Look for low hanging fruit**. Which of the assignments is easiest for you to do? Tackle that one first.
43 | - **If you get stuck in an assignment, move on to the next one**. You can always come back later if time permits.
44 | - After finishing an assignment, read the question again to **make sure you actually gave an answer to the question**.
45 | - Before handing in the test, read it all over again to pick out the small mistakes. **Double check your work!**
46 |
47 | ## Sample questions
48 | 1. Write and call a function that creates and appends a
tag to the
of an HTML file. Make use of the already predefined DOM methods createElement() and appendChild(). The innerText of the
should be “hello HackYourFuture!”.
49 |
50 | 2. Transform the given array of strings named letters into a new array with numbers (for example: `numbers = [0, 1, 2, 3 ]` ), by creating a new function called lettersToNumbers. Log the new array to the console. Return the new array. Make use of the map() array function.
51 | `const letters = [ ‘a’ , ‘b’ , ‘c’ , ‘d’ ];`
52 |
53 |
54 | If there’s anything unclear please let us know. Also, if any of you need additional support, now is the moment to let us know as we could pair you up with someone to answer any questions you may have.
55 |
--------------------------------------------------------------------------------