diff --git a/README.md b/README.md index 613167863..f8db165f4 100644 --- a/README.md +++ b/README.md @@ -4,24 +4,24 @@ Here you can find course content and homework for the JavaScript 1,2 and 3 modules -|Week|Topic|Read|Homework|Review| -|----|-----|----|--------|------| -|0.|Preparation for your first JavaScript session|[Pre-reading](/Week0/README.md)|-|-| -|1.|Git Session with Unmesh|[Reading Week 1](/Week1/README.md) | [Homework Week 1](/Week1/MAKEME.md)|[Review](/Week1/REVIEW.md)| -|2.|• Intro JavaScript (What is it, where can you use it for)
• Variables [var, let, const]
• Basic Data types [Strings, Numbers, Arrays, Booleans]
• Operators
• Naming conventions|[Reading Week 2](/Week2/README.md)|[Homework Week 2](/Week2/MAKEME.md)|[Review](/master/Week2/REVIEW.md)| -|3.|• Git work flow :smiling_imp:
• Advanced data types [Objects]
• Conditions
• Statements vs Expressions
• Loops (for/while)
• Functions
• Scope|[Reading Week 3](/Week3/README.md)|[Homework Week 3](/Week3/MAKEME.md)|[Review](/Week3/REVIEW.md)| -|4.|• Capturing user input
• Events • Basic DOM manipulations[img src, innerHTML]
• Code debugging using the browser
• Code commenting
• Structuring code files |[Reading Week 4](/Week4/README.md)|[Homework Week 4](/Week4/MAKEME.md)|Review| -|5.|• Functions + JSON/Arrays
• Array Manipulations
• JSON
• Map and filter
• Arrow functions |[Reading Week 5](/Week5/README.md)|[Homework Week 5](/Week5/MAKEME.md)|[Review](/Week5/REVIEW.MD)| -|6.|• Closures
• Callbacks|[Reading Week 6](/Week6/README.md)|[Homework Week 6](/Week6/MAKEME.md)|[Review](/Week6/REVIEW.md)| -|7.|• Object Oriented Programming
• Code flow (order of execution)
• Async VS Sync|[Reading Week 7](/Week7/README.md)|[Homework Week 7](/Week7/MAKEME.md)|[Review](/Week7/REVIEW.md)| -|8.|• Structure for a basic SPA
• XHTTP Requests
• API calls|[Reading Week 8](/Week8/README.md)|[Homework Week 8](/Week8/MAKEME.md)|Review| -|9.|• (re)writing data structures (in JSON)
• Promises|[Reading Week 9](/Week9/README.md)|[Homework Week 9](/Week9/MAKEME.md)|[Review](/Week9/REVIEW.md)| +|Week|Topic|Read|Homework| +|----|-----|----|--------| +|0.|Preparation for your first JavaScript session|[Pre-reading](/Week0/README.md)|-| +|1.|Git Session with Unmesh|[Reading Week 1](/Week1/README.md) | [Homework Week 1](/Week1/MAKEME.md)| +|2.|• Intro JavaScript (What is it, where can you use it for)
• [Variables (var, let, const)](fundamentals/variables.md)
• [Basic Data types (Strings, Numbers, Arrays, Booleans)](fundamentals/values.md)
• [Operators](fundamentals/operators.md)
• [Naming conventions](fundamentals/naming_conventions.md)|[Reading Week 2](/Week2/README.md)|[Homework Week 2](/Week2/MAKEME.md)| +|3.|• Git work flow :smiling_imp:
• [Advanced data types (objects)](fundamentals/objects.md)
• [Conditional execution](fundamentals/conditional_execution.md)
• [Statements vs Expressions](fundamentals/statements_expressions.md)
• [Loops (for/while)](fundamentals/loops.md)
• [Functions](fundamentals/functions.md)
• [Scope](fundamentals/scope.md)|[Reading Week 3](/Week3/README.md)|[Homework Week 3](/Week3/MAKEME.md)| +|4.|• Capturing user input
• Events
• [Basic DOM manipulations (img src, innerHTML)](fundamentals/DOM_manipulation.md)
• Code debugging using the browser
• [Code commenting](fundamentals/code_commenting.md)
• Structuring code files |[Reading Week 4](/Week4/README.md)|[Homework Week 4](/Week4/MAKEME.md)| +|5.|• Functions + JSON/Arrays
• [Array Manipulations](fundamentals/array_manipulation.md)
• JSON
• [Map and filter](fundamentals/map_filter.md)
• Arrow functions |[Reading Week 5](/Week5/README.md)|[Homework Week 5](/Week5/MAKEME.md)| +|6.|• [Closures](fundamentals/scope_closures_this.md)
• Callbacks|[Reading Week 6](/Week6/README.md)|[Homework Week 6](/Week6/MAKEME.md)| +|7.|• Object Oriented Programming
• Code flow (order of execution)
• Async vs Sync|[Reading Week 7](/Week7/README.md)|[Homework Week 7](/Week7/MAKEME.md)| +|8.|• Structure for a basic SPA (Single Page Application)
• [XMLHttpRequests](fundamentals/XMLHttpRequest.md)
• API calls|[Reading Week 8](/Week8/README.md)|[Homework Week 8](/Week8/MAKEME.md)| +|9.|• (re)writing data structures (in JSON)
• [Promises](fundamentals/promises.md)|[Reading Week 9](/Week9/README.md)|[Homework Week 9](/Week9/MAKEME.md)| __Kind note:__ We expect you to __always__ come prepared to the class on Sunday. ### Overall -A good understanding of all the above mentioned topics. Want to check your Knowledge? Go through the [JavaScript Fundamentals README](/fundamentals) and research/ ask for help (Slack!) with the concepts that are not entirely clear. +A good understanding of all the above mentioned topics. Want to check your Knowledge? Go through the [JavaScript Fundamentals README](fundamentals/README.md) and research/ ask for help (Slack!) with the concepts that are not entirely clear. diff --git a/Week2/MAKEME.md b/Week2/MAKEME.md index 8c1e02a24..62cd4e05e 100644 --- a/Week2/MAKEME.md +++ b/Week2/MAKEME.md @@ -3,8 +3,8 @@ ``` Topics discussed in class this week: • Intro JavaScript (What is it, where can you use it for) -• Variables [var, let, const] -• Basic Data types [Strings, Numbers, Arrays, Booleans] +• Variables (var, let, const) +• Basic Data types (Strings, Numbers, Arrays, Booleans) • Operators ``` @@ -12,20 +12,20 @@ Topics discussed in class this week: ## Before you start with the homework: -1. Go through the review of [week 1](https://github.com/HackYourFuture/JavaScript/blob/master/Week1/REVIEW.md) +1. Review the [Git course material](https://github.com/HackYourFuture/Git) of last week. 2. Watch: [What is programming](https://www.khanacademy.org/computing/computer-programming/programming/intro-to-programming/v/programming-intro) Just watch the 2 min video, you do not have to do the entire JavaScript course (It could be useful later on though). -3. Please watch the following parts of the course, [Programming Foundations Fundamentals](https://www.lynda.com/Programming-Foundations-tutorials/Welcome/83603/90426-4.html) on Lynda.com (if you don't have access to Lynda yet ask Gijs): -
0. Introduction - 1. Programming Basics - 2. Core Programming Syntax - 3. Variables and Data Types +3. Please watch the following parts of the course, [Programming Foundations Fundamentals](https://www.lynda.com/Programming-Foundations-tutorials/Welcome/83603/90426-4.html) on Lynda.com (if you don't have access to Lynda yet ask Gijs): + 0\. Introduction + 1\. Programming Basics + 2\. Core Programming Syntax + 3\. Variables and Data Types ## Step 2: Feedback _Deadline Wednesday_ -Provide feedback on the HTML-CSS assignments (week 3) of one of your fellow students. You will be assigned to one of the assignments by the class lead of this week. +Provide feedback on the Git assignments (week 1) of one of your fellow students. You will be assigned to one of the assignments by the class lead of this week. ## Step 3: JavaScript @@ -42,14 +42,16 @@ Ciao, mondo! // Italian Hola, mundo! // Spanish ``` -2\. Consider the following code: +2\. Consider the following code: + ``` console.log('I'm awesome'); ``` -2\.1 Copy the code in your `.js` file and run it. You will see that you will get a SyntaxError. Find a solution for this error, Hint read the error message carefully, it also gives an indication of where the problem is. -3\. Declare a variable `x` and initialize it with an integer. -3\.1 First, _declare_ your variable `x`. +Copy the code in your `.js` file and run it. You will see that you will get a SyntaxError. Find a solution for this error. Hint: read the error message carefully, it also gives an indication of where the problem is. + +3\. Declare a variable `x` and initialize it with an integer, using these exact steps: +3\.1 First, _declare_ your variable `x` (do not initialize it yet). 3\.2 Add a console.log statement that explains that explains in words what _you think_ the value of `x` is, like in this example: ```js // TODO -> here you initialize your variable @@ -57,7 +59,7 @@ console.log('I'm awesome'); ``` 3\.3 Add a console.log statement that logs the value of `x`. 3\.4 Now _initialize_ your variable `x` with an integer. -3\.5 Now add a console.log statement that explains what _you think_ the value of `x` is. +3\.5 Next, add a console.log statement that explains what _you think_ the value of `x` is. 3\.6 Add a console.log statement that logs the value of `x`. Steps to be taken: @@ -85,7 +87,7 @@ console.log('I'm awesome'); // TODO -> log the actual value of the string to the console ``` -5\. How do you round the number 7.25, to the nearest integer? +5\. How do you round the number 7.25, to the nearest integer (i.e., whole number)? 5\.1 Declare a variable `z` and assign the number 7.25 to it. 5\.2 Console.log `z`. 5\.3 Declare another variable `a` that has the value of z but rounded to the nearest integer. @@ -94,16 +96,16 @@ console.log('I'm awesome'); 5\.6 Console.log the highest value. 6\. *Arrays!* -6\.1 Declare an empty array. +6\.1 Declare an empty array. Make sure that the name you choose indicates 'plurality', because an array is capable of containing more than one element. (See [Naming conventions](../fundamentals/naming_conventions.md).) 6\.2 Write a console.log statement that explains in words what you think the value of the array is. 6\.3 Console.log your array. -6\.4 Create an array that has your favorite animals inside (you can decide on how to call it yourself, but read on a bit here and see if you can find a good name that exactly describes what this variable will hold). +6\.4 Create an array that has your favorite animals inside (see if you can find a good name that exactly describes what this variable will hold). 6\.5 Log your array. -6\.6 Add a statement that adds Daan's favorite animal (baby pig) to the *existing array*. +6\.6 Add a statement that adds Daan's favorite animal ('baby pig') to the *existing array*. 6\.7 Log your new array! 7\. *More strings* -7\.1 Let's consider the following string: `let myString = "this,is,a,test"`. +7\.1 Let's consider the following string: `let myString = "this is a test"`. 7\.2 Add the string to your file and console.log it. 7\.3 Find a way to get the length of `myString`. 7\.4 Console.log the length of `myString`. @@ -115,6 +117,9 @@ console.log('I'm awesome'); let foo = 3; console.log('The value of my variable foo is: ' + foo); ``` + + (Curious to know what a `foo` is? Check [this article](https://en.wikipedia.org/wiki/Metasyntactic_variable) on WikiPedia.) + 8\.3 Now write a console.log statement wherein you first explain in words what you think the _type_ of your variables is. 8\.4 Now use `typeof` to log the actual _type_ of your variables. 8\.5 Now compare the types of your different variables with one another. @@ -126,7 +131,7 @@ For example: let x = 9; let y = 'Hello'; -if () { +if (...) { console.log('SAME TYPE'); } // TODO -> add a way of giving feedback if your variables don't have the same type @@ -150,7 +155,7 @@ On freeCodeCamp.com please do the [Basic JavaScript](https://www.freecodecamp.co _Deadline Sunday morning_ -Go trough the reading material in the [README.md](/Week1/README.md) to prepare for your next class +Go trough the reading material in the [README.md](/Week2/README.md) to prepare for your next class ### How to hand in Homework: ``` @@ -163,4 +168,9 @@ Go trough the reading material in the [README.md](/Week1/README.md) to prepare f ### Hint If you solve the FreeCodeCamp challenges and they are new concepts to you and you would like to take a look at them later on in the program, Copy your answers from FCC in a `.js` file and upload them to Github in a repository for future reference. In this way you build your own little documentation, if you look back at them first try to understand what it does before you run them. -:star: Additional resources and review: [here](/Week1/REVIEW.md):star: +:star: Additional resources and review: :star: + +- [Variables](../fundamentals/variables.md) +- [Basic value types](../fundamentals/values.md) +- [Operators](../fundamentals/operators.md) +- [Naming conventions](../fundamentals/naming_conventions.md) diff --git a/Week2/README.md b/Week2/README.md index 6bb3ed5c5..d2c736fd6 100644 --- a/Week2/README.md +++ b/Week2/README.md @@ -35,7 +35,12 @@ Please watch the following parts of the course, [Programming Foundations Fundame - Check out this video of Daan to see how we use Git Workflow to hand in Homework (from now on): https://www.youtube.com/watch?v=-o0yomUVVpU&index=2&list=PLVYDhqbgYpYUGxRdtQdYVE5Q8h3bt6SIA ### Review -- Go through the review of [week 1](/Week1/REVIEW.md) -- Go through the review of [week 2](/Week2/REVIEW.md) + +Review the topics of week 2: + +- [Variables](../fundamentals/variables.md) +- [Values](../fundamentals/values.md) +- [Operators](../fundamentals/operators.md) +- [Naming conventions](../fundamentals/naming_conventions.md) _Please go through the material and come to class prepared!_ diff --git a/Week2/REVIEW.md b/Week2/REVIEW.md deleted file mode 100644 index abc3580fb..000000000 --- a/Week2/REVIEW.md +++ /dev/null @@ -1,38 +0,0 @@ -# REVIEW JavaScript week 2 - -``` -This review covers: -• Intro JavaScript (What is it, where can you use it for) -• Variables [var, let, const] -• Basic value types [Strings, Numbers, Arrays, Booleans] -• Operators -• Naming conventions -``` - -## Variables - -A "variable" is a place where you can store information, such as a string, or a number. A variable has a _name_ (that you choose) and a _value_. New variables in JavaScript are declared using one of three keywords: `let`, `const`, or `var`. - -[Read more...](../fundamentals/variables.md) - -## Values - -Values are the "things" that you assign to a variable. All values have a type. In our example above, the variable `x` is assigned a value of type `number`. JavaScript supports the following types: - -[Read more...](../fundamentals/values.md) - -## Operators - -- Comparison operators (equality, relational) -- Arithmetic operators -- Logical operators -- `typeof` operator -- Assignment operators - -[Read more...](../fundamentals/operators.md) - -## Naming conventions - -In programming you will need to come up with appropriate names for your variables and functions. - -[Read more...](../fundamentals/naming_conventions.md) diff --git a/Week3/MAKEME.md b/Week3/MAKEME.md index 095b3f425..70f60b71c 100644 --- a/Week3/MAKEME.md +++ b/Week3/MAKEME.md @@ -16,28 +16,43 @@ Topics discussed in class this week: _Deadline Monday_ -Provide feedback to step 1 and step 3 of the homework of last week to one of your fellow students. You will be assigned to one of the assignments by the class lead of this week. +Provide feedback to the homework of last week to one of your fellow students. You will be assigned to one of the assignments by the class lead of this week. ## Step 1: Recap/Read - Have a look at [The Secret Life of JavaScript Primitives](https://javascriptweblog.wordpress.com/2010/09/27/the-secret-life-of-javascript-primitives/) -- Go through the review of [last week](https://github.com/HackYourFuture/JavaScript/blob/master/Week1/REVIEW.md) -- Go through the review of [this week](https://github.com/HackYourFuture/JavaScript/blob/master/Week2/REVIEW.md) +- Review the topics of last week: + - [Variables](../fundamentals/variables.md) + - [Values](../fundamentals/values.md) + - [Operators](../fundamentals/operators.md) + - [Naming conventions](../fundamentals/naming_conventions.md) + +- Go through the topics of this week: + - Git work flow + - [Advanced data types (Objects)](../fundamentals/objects.md) + - [Conditional execution](../fundamentals/conditional_execution.md) + - [Statements vs Expressions](../fundamentals/statements_expressions.md) + - [Loops (for/while)](../fundamentals/loops.md) + - [Functions](../fundamentals/functions.md) + - [Scope](../fundamentals/scope.md) + ## Step 2: Watch -1. If you haven't done already, watch: [What is programming](https://www.khanacademy.org/computing/computer-programming/programming/intro-to-programming/v/programming-intro) Just watch the 2 min video, you do not have to do the entire JavaScript course (It could be useful later on though). -2. Please watch the following parts of the course, [Programming Foundations Fundamentals](https://www.lynda.com/Programming-Foundations-tutorials/Welcome/83603/90426-4.html) on Lynda.com (if you don't have access to Lynda yet ask Gijs): -
4. Writing Conditional Code -
5. Modular Code -
6. Iteration: Writing Loops -
7. More About Strings -
8. Collections -
11. When Things Go Wrong +1. If you haven't done already, watch: [What is programming](https://www.khanacademy.org/computing/computer-programming/programming/intro-to-programming/v/programming-intro) +Just watch the 2 min video, you do not have to do the entire JavaScript course (It could be useful later on though). + +2. Please watch the following parts of the course, [Programming Foundations Fundamentals](https://www.lynda.com/Programming-Foundations-tutorials/Welcome/83603/90426-4.html) on Lynda.com (if you don't have access to Lynda yet ask Gijs): +
**4. Writing Conditional Code** +
**5. Modular Code** +
**6. Iteration: Writing Loops** +
**7. More About Strings** +
**8. Collections** +
**11. When Things Go Wrong** ## Step 3: Rover the Robot -Go and try out this cool game: http://hyf-robot.herokuapp.com/index.html, there are different levels, see how far you can get! +Go and try out this cool game: [roverjs.com](http://roverjs.com), written by one of our HYF teachers, Joost Lubach. There are different levels, see how far you can get! ## Step 4: String and Array challenges @@ -52,17 +67,18 @@ In each assignment write at least two `console.log` statements to verify if your 1\.1 Let's consider the following string: `let myString = "hello,this,is,a,difficult,to,read,sentence"` 1\.2 Add the string to your file and console.log it. 1\.4 Console.log the length of `myString`. -1\.5 The comma's make that the sentence is quite hard to read. Find a way to remove the comma's from the sting and replace them with a spaces +1\.5 The commas make that the sentence is quite hard to read. Find a way to remove the comma's from the sting and replace them with a spaces 1\.6 Console.log `myString` to see if you succeeded. -2\. **Arrays!** -consider the following array: +2\. **Arrays!** + +Consider the following array: ```js let favoriteAnimals = ['blowfish', 'capricorn', 'giraffe']; ``` -2\.1 Add a statement that adds Mauro's favorite animal (turtle) to the existing array +2\.1 Add a statement that adds Mauro's favorite animal ('turtle') to the existing array 2\.2 Log your new array! 2\.3 Now add Jim's favorite animal to the array, its a 'meerkat', but make sure it will be placed after 'blowfish' and before 'capricorn'. 2\.4 Write a console.log statement that explains in words _you think_ the new value of the array is. @@ -103,7 +119,7 @@ let favoriteAnimals = ['blowfish', 'capricorn', 'giraffe']; 10. Use the list of vehicles to write an advertisement. So that it prints something like: `"Amazing Joe's Garage, we service cars, motorbikes, caravans and bikes."`. (Hint: use a `for` loop.) -> Hint, the output should be correct English with all the punctuation in place (that's the challenge). So plurals for the vehicle types, commas followed by a single space, the word and to replace the final comma and closed off by a period. + > Hint, the output should be correct English with all the punctuation in place (that's the challenge). So plurals for the vehicle types, commas followed by a single space, the word and to replace the final comma and closed off by a period. 11. What if you add one more vehicle to the list, can you have that added to the advertisement without changing the code for question 10? @@ -171,7 +187,7 @@ Please make sure you REALLY understand the exercises below: _Deadline Sunday morning_ -Go trough the reading material in the [README.md](/Week2/README.md) to prepare for your next class +Go through the reading material in the [README.md](/Week2/README.md) to prepare for your next class ``` How to hand in your homework: @@ -180,5 +196,3 @@ How to hand in your homework: • Your hyf-javascript1/week2 should now contain all your homework files. • Place the link to your repository folder in Trello. ``` - -:star: Additional resources and review: [here](/Week2/REVIEW.md):star: \ No newline at end of file diff --git a/Week3/REVIEW.md b/Week3/REVIEW.md deleted file mode 100644 index 24f0c60ec..000000000 --- a/Week3/REVIEW.md +++ /dev/null @@ -1,44 +0,0 @@ -# REVIEW JavaScript week 3 - -``` -This review covers: -• Git work flow -• Advanced data types [Objects] -• Conditions -• Statements vs Expressions -• Loops (for/while) -• Functions -• Scope -``` - -## Recap Logical operators - -* AND `&&` -* OR `||` -* NOT `!` - -[Read more...](../fundamentals/operators.md#logical-operators) - -## Typeof - -`typeof` always returns the data type in a string. - -[Read more...](../fundamentals/operators.md#typeof-operator) - -## Objects - -Variables that are objects also contain a list of things, but instead of them being in some specific order, they can be assigned to words, called "keys". Instead of "elements" the things that are inside objects are called "properties". - -[Read more...](../fundamentals/objects.md) - -## Functions - -A function is a reusable piece of code. Functions are *very* important in JavaScript, to the extent that some people call JavaScript a "function-oriented" language. As mentioned above, variables can be of type function. In fact, *every function is a variable*. - -[Read more...](../fundamentals/functions.md) - -## Statements & expressions - -Most programming languages that you'll encounter in real life are called "imperative" programming languages. JavaScript is such an imperative programming language. Imperative is another word for command-like. That is, you give the computer a bunch of commands after each other. First do this, then do that, etc. - -[Read more...](../fundamentals/statements_expressions.md) diff --git a/Week4/REVIEW.md b/Week4/REVIEW.md deleted file mode 100644 index 39b9298f5..000000000 --- a/Week4/REVIEW.md +++ /dev/null @@ -1,17 +0,0 @@ -# REVIEW JavaScript week 4 - -``` -This review covers: -• Capturing user input -• Events -• Basic DOM manipulations[img src, innerHTML] -• Code debugging using the browser -• Code commenting -• Structuring code files -``` - -## Code Commenting - -First the straightforward part: how do we place comments in our code? - -[Read more...](../fundamentals/code_commenting.md) \ No newline at end of file diff --git a/Week5/REVIEW.md b/Week5/REVIEW.md deleted file mode 100644 index 002b8664b..000000000 --- a/Week5/REVIEW.md +++ /dev/null @@ -1,26 +0,0 @@ -# REVIEW JavaScript week 5 - -``` -This review covers: -• Functions + JSON/Arrays -• Array Manipulations -• JSON -• Map and filter -• Arrow functions -``` - -## Array Manipulations - -As we know by now, arrays are collections of values. - -As we will see, there are often many ways to achieve the same thing when working arrays. Over time, you will add different techniques to your mental toolbox to achieve the result you want quickly. - -[Read more...](../fundamentals/array_manipulation.md) - -## Map and filter - -The array methods **map()** and **filter()** are best understood by looking at how they could be implemented if we were to write them ourselves. In the next few sections we will present simplified versions of the native implementations. We have prefixed the method names with `my` to distinguish them from the built-in versions. - -[Read more...](../fundamentals/map_filter.md) - - diff --git a/Week6/REVIEW.md b/Week6/REVIEW.md deleted file mode 100644 index 9e3ce913e..000000000 --- a/Week6/REVIEW.md +++ /dev/null @@ -1,15 +0,0 @@ -# REVIEW week 6 - -``` -This review covers: -• Closures -• Scope -• Callbacks -``` - -## Scope, closures and 'this' - -Scope, closure and 'this' are about *context*. - -[Read more...](../fundamentals/scope_closures_this.md) - diff --git a/Week7/MAKEME.md b/Week7/MAKEME.md index 920818735..183643c0e 100644 --- a/Week7/MAKEME.md +++ b/Week7/MAKEME.md @@ -73,7 +73,7 @@ Staff { // Initialize the objects // by pick your favorite movie from http://www.imdb.com/ // and make sure that the following actions work. -console.log(InstanceMovie.getStarts().map(actor => `${actor.getName()} ${actor.getAge}`)); +console.log(InstanceMovie.getStars().map(actor => `${actor.getName()} ${actor.getAge()}`)); const director = InstanceMovie.getDirector(); console.log(`Director: ${director.getName()}`); // Be creative with this let's see what you come up with :-) diff --git a/Week7/REVIEW.md b/Week7/REVIEW.md deleted file mode 100644 index d5512bed7..000000000 --- a/Week7/REVIEW.md +++ /dev/null @@ -1,12 +0,0 @@ -# REVIEW JavaScript week 7 - -``` -This review covers: -• Object Oriented Programming -• Code flow (order of execution) -• Async VS Sync -``` - -## Object Oriented Programming - - diff --git a/Week8/REVIEW.md b/Week8/REVIEW.md deleted file mode 100644 index d5f31c619..000000000 --- a/Week8/REVIEW.md +++ /dev/null @@ -1,8 +0,0 @@ -# REVIEW JavaScript week 8 - -``` -This review covers: -• Structure for a basic SPA -• XMLHttpRequests -• API calls -``` \ No newline at end of file diff --git a/Week9/README.md b/Week9/README.md index f06fb7955..f1306a2a4 100644 --- a/Week9/README.md +++ b/Week9/README.md @@ -5,7 +5,7 @@ Next week you will start with Node :balloon: ``` ### Refresher -- :star:Timir wrote a really nice javaScript REVIEW that explains which concepts are most important to know in JavaScript when you continue your coding journey to Node, this is a __MUST__ read: https://github.com/HackYourFuture/JavaScript/blob/master/Week9/MAKEME.md :star: +- :star:Timir wrote a really nice javaScript REVIEW that explains which concepts are most important to know in JavaScript when you continue your coding journey to Node, this is a __MUST__ read: [Timir's JavaScript Review](fundamentals/javascript_review.md) :star: - https://forum.freecodecamp.com/t/javascript-callback-functions/14658/2 http://www.learn-js.org/en/Callbacks diff --git a/Week9/REVIEW.md b/Week9/REVIEW.md deleted file mode 100644 index 48c9cbd68..000000000 --- a/Week9/REVIEW.md +++ /dev/null @@ -1,24 +0,0 @@ -# REVIEW JavaScript week 9 - -``` -This review covers: -• (re)writing data structures (in JSON) -• Promises -``` - -## Promises - -Why is a JavaScript ES6 `promise` called a 'promise'? Here is a snippet from the *Oxford Dictionary of English* definition of 'promise': - -> **promise** |ˈprɒmɪs|
-noun
-1 a declaration or assurance that one will do something or that a particular thing will happen - -[Read more...](../fundamentals/promises.md) - -### JavaScript review - -You'll need to know the following before starting the Node class (remember Node is just JavaScript in a different environment - and you KNOW JS already - right?!?!) - -[Read more...](../fundamentals/javascript_review.md) - diff --git a/Week1/assets/box.png b/fundamentals/assets/box.png similarity index 100% rename from Week1/assets/box.png rename to fundamentals/assets/box.png diff --git a/fundamentals/conditional_execution.md b/fundamentals/conditional_execution.md new file mode 100644 index 000000000..291f366e4 --- /dev/null +++ b/fundamentals/conditional_execution.md @@ -0,0 +1,185 @@ +# Conditional execution + +The normal order of execution of statements in a computer program is in straight-line order, from top to bottom. However, sometimes it is desirable to execute one or more statements _conditionally_, i.e. depending on whether some condition – determined by the state of your program – holds true. + +## The `if` statement + +In its simplest form the `if` statement looks like this: + +```js +if (condition) { + // one or more statements that will be executed + // if, and only if the condition holds true +} +``` + +Here, `condition` is a boolean expression that resolves to either `true` or `false` (or, more precisely, any expression that is 'truthy' or 'falsy', as will be explained later). + +The statements within the curly braces `{` and `}` will be executed if the condition holds true, otherwise these statements will be skipped (i.e. ignored). + +An example: + +```js +if (distance < 10) { + console.log('I will take the bike.'); +} +``` + +Here, the condition is the boolean expression `distance > 10`, which is either `true` or `false`. + +It is also possible to add a statement block to be executed if (and only if) the condition does **not** hold true, using an `else` clause. + +```js +if (distance < 10) { + console.log('I will take the bike.'); +} else { + console.log('I will go by car.'); +} +``` + +A condition can take more complex forms, using `&&` (logical AND) and `||` (logical OR) operators: + +```js +if (distance < 10 && !raining) { + console.log('I will take the bike.'); +} else { + console.log('I will go by car.'); +} +``` + +In the example above `raining` is a boolean variable (either `true` or `false`), and the exclamation mark is the logical NOT operator that negates the boolean value (if it was `true` the result after negation is false and vice versa). + +For more complex decisions you can concatenate multiple conditions using `else if` clauses. + +```js +if (distance < 1) { + console.log('I will walk.'); +} else if (distance < 10) { + console.log('I will take the bike.'); +} else if (distance < 50) { + console.log('I will go by car.'); +} else { + console.log('I will take the train.'); +} +``` + +The statement block inside an `if`, `else` or `else if` may itself contain nested `if` statements, as in this example: + +```js +if (distance < 10) { + if (raining) { + console.log('I will go public transportation.'); + } else { + console.log('I will walk.'); + } +} else { + console.log('I will go by car.'); +} +``` + +> As (nested) `if` statements can become quite complex it is very important that you indent your source code so that there can be no confusion about which statement blocks are executed for each condition, as was done in the examples. + +>More information on MDN: [if...else](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/if...else) + +## The conditional (ternary) operator + +This operator can be used as a shortcut for an `if` statement when dealing with expressions. + +The general format is: + +```js +condition ? expr1 : expr2 +``` + +('ternary' means: _composed of three parts_) + +It is often used in combination with an assignment, as in this example: + +```js +const conditionOfCar = age < 1 ? 'new' : 'used'; +``` + +The `conditionOfCar` variable will be assigned the string `'new'` if the `age < 1` condition holds true, otherwise it is assigned the string `'used'`. + +It is **not** recommended to use the conditional operator if you do not intend to use its value: + +```js +// Don't do this: it's yucky code +age < 1 ? console.log('new') : console.log('used'); +``` + +>More information on MDN: [Conditional (ternary) Operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator) + +## The switch statement + +The `switch` statement can sometimes be a useful alternative to a concatenation of `if` statements. This is the case when the condition is an expression that can be decomposed into a number of distinct values or _cases_, as shown in the example below. + +```js +const hyfModule = 'JavaScript-1'; + +switch (hyfModule) { + case 'HTML/CSS': + console.log('In this module you will learn HTML and CSS.'); + break; + case 'JavaScript-1': + console.log('In this module you will learn Git and JavaScript basics.'); + break; + case 'JavaScript-2': + console.log('In this module you will learn about JavaScript in the browser with HTML and CSS.'); + break; + case 'JavaScript-3': + console.log('In this module you will learn about Async and API calls.'); + break; + case 'Node': + console.log('This module is about building server and CLI applications using Node.'); + break; + case 'Database': + console.log('In this module is about Relational and Non-Relational Data and Database Systems.'); + break; + case 'React': + console.log('In this module you will to build Single Page Applications using React.'); + break; + case 'Project': + console.log('In this final module you will do your graduation project.'); + break; + default: + console.log('This module is unknown: ' + hyfModule); +}} +``` + +Depending on the value of the expression specified in the `switch` clause, one of the `case` statement blocks is executed. Each statement block should end with a `break` statement to ensure that a `case` doesn't 'fall through' into the next `case`. + +The `default` statement at the end is executed when none of the preceding cases hold true. The `default` statement is not strictly required, but is a best practice to always specify one. + +>More information on MDN: [switch](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/switch) + +## truthy, falsy + +**truthy**: 'sort of' `true` +**falsy**: 'sort of' `false` + +From MDN: + +In JavaScript, a **truthy** value is a value that is considered true when evaluated in a Boolean context. All values are truthy unless they are defined as **falsy**. + +**falsy** values are: + +- `false` +- `0` +- `""` +- `null` +- `undefined` +- `NaN` + +The example below will print `x is undefined` because `undefined` is **falsy**. + +```js +let x; +if (x) { + console.log('x is defined'); +} else { + console.log('x is undefined'); +} +``` + +>More information on MDN: [Truthy](https://developer.mozilla.org/en-US/docs/Glossary/Truthy), [Falsy](https://developer.mozilla.org/en-US/docs/Glossary/Falsy) \ No newline at end of file diff --git a/fundamentals/javascript_review.md b/fundamentals/javascript_review.md index 74d0772af..31f34fa5f 100644 --- a/fundamentals/javascript_review.md +++ b/fundamentals/javascript_review.md @@ -2,14 +2,14 @@ You'll need to know the following before starting the Node class (remember Node is just JavaScript in a different environment - and you KNOW JS already - right?!?!) -``` +``` From Jason: -jason [9:11 AM] +jason [9:11 AM] @timirkaria the most important topics will be sync/async and ajax. That and basic syntax (named and anonymous functions, callbacks, scope) should be sufficient! ``` ### AJAX -Stands for *A*syncrhonous *J*avascript *A*nd *X*ml (think of XML as the old JSON) but now it's AJA*J* but that doesn't sound as good. +Stands for *A*synchronous *J*avascript *A*nd *X*ml (think of XML as the old JSON) but now it's AJA*J* but that doesn't sound as good. So here's an example of a SYNCHRONOUS request (it waits for the request to come back before continuing) @@ -29,7 +29,7 @@ console.log('Made the request') ``` -And here's an example of an ASYNCHRONOUS version of the same request as above. Look carefully at the output. +And here's an example of an ASYNCHRONOUS version of the same request as above. Look carefully at the output. ```js var SECRET_MESSAGE_URL = 'https://gist.githubusercontent.com/tkaria/08325583e7411f7de6b80871780fd917/raw/61dae2869ae5013652bbeba1da2487097d8869b1/SecretMessage.txt' @@ -52,16 +52,16 @@ xhr.send(null); console.log('Made the request'); ``` -### What's happening here? +### What's happening here? As always - read the docs first... -`https://developer.mozilla.org/en/docs/Web/API/XMLHttpRequest` +`https://developer.mozilla.org/en/docs/Web/API/XMLHttpRequest` Create a new request and open it (lines 2 and 3) -Tell the request object what function to call when when the contents of the request are loaded. Inside the ANONYMOUS function which takes a parameter `e` we check the response code from the request (this is just HTTP stuff - nothing special). If the reponse code is good (200) then we print what we got. +Tell the request object what function to call when when the contents of the request are loaded. Inside the ANONYMOUS function which takes a parameter `e` we check the response code from the request (this is just HTTP stuff - nothing special). If the response code is good (200) then we print what we got. -More interesting is the order of the print statements. In the first example we saw the message `Received the response` **BEFORE** we saw the `Made the request` message because the program waited to get the response and print it before continuing to run. +More interesting is the order of the print statements. In the first example we saw the message `Received the response` **BEFORE** we saw the `Made the request` message because the program waited to get the response and print it before continuing to run. -In this case we see the `Made the request` message before we see the response because the program keeps running while waiting for the response. When the response is finally received it is printed before writing the `Received the response` to the console. +In this case we see the `Made the request` message before we see the response because the program keeps running while waiting for the response. When the response is finally received it is printed before writing the `Received the response` to the console. Note that we used an anonymous function here - it has no name. There's nothing special about an anonymous function. We could equally use a named function in the above example: @@ -80,7 +80,7 @@ function NOT_ANONYMOUS_ON_LOAD_FUNCTION(parameter) { } } xhr.open("GET", SECRET_MESSAGE_URL, true); -xhr.onload = NOT_ANONYMOUS_ON_LOAD_FUNCTION; // Note: we are not CALLING the function - there are no () +xhr.onload = NOT_ANONYMOUS_ON_LOAD_FUNCTION; // Note: we are not CALLING the function - there are no () // We'll leave the error function the way it is and you can change it to a named function xhr.onerror = function (e) { console.error(xhr.statusText); @@ -90,14 +90,14 @@ console.log('Made the request'); ``` -### The big idea: +### The big idea: -#### Sync / Async -Make requests without waiting for the response and just get "notified" when the response happens. That's the asyncrhonous part - don't wait for it and stop everything else just let me know when it happens. How can the computer let you know? You tell it what to do when the async function is ready (has something to say - success or failure) +#### Sync / Async +Make requests without waiting for the response and just get "notified" when the response happens. That's the asynchronous part - don't wait for it and stop everything else just let me know when it happens. How can the computer let you know? You tell it what to do when the async function is ready (has something to say - success or failure) #### Named and anonymous functions -Some functions have names and some don't. Sometimes you just want to use a function to pass it to another function so you don't need to name it. It never needs to be called outside of the function that you're passing it to so it doesn't need a name. -The simplest asynchonous function that you will see all over the place is called `setTimeout` (right now you should be reaching for a new tab and typing `MDN setTimeout` into Google). Be patient when running the below - it takes 3 seconds... +Some functions have names and some don't. Sometimes you just want to use a function to pass it to another function so you don't need to name it. It never needs to be called outside of the function that you're passing it to so it doesn't need a name. +The simplest asynchronous function that you will see all over the place is called `setTimeout` (right now you should be reaching for a new tab and typing `MDN setTimeout` into Google). Be patient when running the below - it takes 3 seconds... For example (using a named function): ```js @@ -130,20 +130,20 @@ console.log('After timeoutFunction'); What to do when the result of an async request is returned. Remember that requests can succeed as well as fail. Plan for (AND TEST) both. #### Scope -I think we covered this pretty well with our discussion of closures in the last class but let me know if you need more. +I think we covered this pretty well with our discussion of closures in the last class but let me know if you need more. ## Recap -Read this - you may not understand it all but please read it before you read anything else about closures. The reason is that this is source material - this is the primary documentation. It is written very technically and in a bit of a boring way but there's a reason (as we talked about in class). The reason is to be clear so the language is precise and technical. It's OK if you don't get it now but just read it and it will stay in the back of your head. +Read this - you may not understand it all but please read it before you read anything else about closures. The reason is that this is source material - this is the primary documentation. It is written very technically and in a bit of a boring way but there's a reason (as we talked about in class). The reason is to be clear so the language is precise and technical. It's OK if you don't get it now but just read it and it will stay in the back of your head. https://developer.mozilla.org/en/docs/Web/JavaScript/Closures -Please TYPE these exercises - do NOT copy and paste. BEFORE you run them please make a guess in your head about what will happen. +Please TYPE these exercises - do NOT copy and paste. BEFORE you run them please make a guess in your head about what will happen. ```js function init() { var name = 'Mozilla'; // name is a local variable created by init function displayName() { // displayName() is the inner function, a closure - alert(name); // use variable declared in the parent function + alert(name); // use variable declared in the parent function } - displayName(); + displayName(); } init(); ``` @@ -152,10 +152,10 @@ init(); function init() { var name = 'Mozilla'; // name is a local variable created by init function displayName() { // displayName() is the inner function, a closure - alert(name); // use variable declared in the parent function + alert(name); // use variable declared in the parent function } } -displayName(); +displayName(); ``` ```js @@ -163,7 +163,7 @@ var name = 'Hack your future' function init() { var name = 'Mozilla'; // name is a local variable created by init function displayName() { // displayName() is the inner function, a closure - alert(name); // use variable declared in the parent function + alert(name); // use variable declared in the parent function } displayName(); } @@ -174,37 +174,37 @@ init(); var name = 'Hack your future' function init(name) { function displayName(name) { // displayName() is the inner function, a closure - alert(name); // use variable declared in the parent function + alert(name); // use variable declared in the parent function } displayName(name); } init('Hack your future again') ``` -Now read this: http://stackoverflow.com/questions/11488014/asynchronous-process-inside-a-javascript-for-loop +Now read this: http://stackoverflow.com/questions/11488014/asynchronous-process-inside-a-javascript-for-loop -And try out the examples - please make SURE you understand what is happening. Ask questions if you do not. +And try out the examples - please make SURE you understand what is happening. Ask questions if you do not. Same instructions as above but now for Arrow functions (remember this is not intended to confuse you - it's just code). ### Arrow functions https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions/Arrow_functions -Then read this. +Then read this. http://stackoverflow.com/questions/22939130/when-should-i-use-arrow-functions-in-ecmascript-6/28135120#28135120 -This is a normal function: +This is a normal function: ```js function sayHello(name) { return 'Hello ' + name; } ``` -Same as above with arrow (fat arrow) notation - shorthand notation. This is easy to mess up. Notice no return. +Same as above with arrow (fat arrow) notation - shorthand notation. This is easy to mess up. Notice no return. ```js var sayHello2 = (name) => 'Hello ' + name; ``` -Same as above with arrow (fat arrow) notation - shorthand notation. Better - easier to read - with return. +Same as above with arrow (fat arrow) notation - shorthand notation. Better - easier to read - with return. ```js var sayHello2 = (name) => {return 'Hello ' + name;} ``` @@ -216,7 +216,7 @@ function Person(firstName) { } ``` -Looks the same but what happens? See if you can figure out why from reading the documentation. +Looks the same but what happens? See if you can figure out why from reading the documentation. ```js var Person = (firstName) => {this.firstName = firstName} ``` @@ -232,7 +232,7 @@ for (i = 0; i < 3; i++) { } ``` -### Make the above function do what we think it should do. +### Make the above function do what we think it should do. ### Return examples ```js @@ -247,7 +247,7 @@ function f2(x) { } ``` -### Static members +### Static members http://odetocode.com/blogs/scott/archive/2015/02/02/static-members-in-es6.aspx ### Closures examples @@ -256,7 +256,7 @@ https://jsfiddle.net/78dg25ax/?utm_source=website&utm_medium=embed&utm_campaign= ### Why closures are helpful with async code: http://stackoverflow.com/questions/13343340/calling-an-asynchronous-function-within-a-for-loop-in-javascript -### Promises +### Promises http://stackoverflow.com/questions/13343340/calling-an-asynchronous-function-within-a-for-loop-in-javascript https://www.youtube.com/watch?v=WBupia9oidU diff --git a/fundamentals/loops.md b/fundamentals/loops.md new file mode 100644 index 000000000..319417b34 --- /dev/null +++ b/fundamentals/loops.md @@ -0,0 +1,169 @@ +# Loops + +A loop is a programming construct to perform a repetitive action. Often (but not always) the repetitive action involves accessing or manipulating the individual elements of an array. + +We will use the array of month names given below to illustrate the various types of loop constructs available in JavaScript. In the examples we will print out the names of the individual months using a `console.log` statement. + +```js +const months = [ + 'January', 'February', 'March', 'April', 'May', 'June', + 'July', 'August', 'September', 'October', 'November', 'December' +]; +``` + +## while + +The `while` loop is probably the simplest one of the bunch. Its general syntax is: + +```js +while (cond) { + // statement block to be repeated +} +``` + +The loop 'body' (i.e., the statement block including the curly braces) is executed while the condition `cond` holds true. In order for this while loop to execute at least once and to finish in finite time two preconditions must be fulfilled: + +1. The condition `cond` should initially hold true. +2. Some code inside the code block must eventually cause the condition to become false. + +Applied to our `months` array the while loop would look like this: + +```js +const months = [ + ... +]; + +let index = 0; +const len = months.length; // 12 + +while (index < len) { + console.log(months[index]); + index += 1; +} +``` + +In this example the two preconditions mentioned earlier are met: + +1. The condition `index < len` initially holds true because `index` is initialized to `0` and we know that `len` is fixed at the value of `12` (hence the use of `const` rather than `let`). +2. Because the value of `index` is incremented by one each time the loop body is executed there will be a point in time when the loop condition becomes false. This will happen when the value `index` has become `12` and `index < len` no longer holds true. + +If precondition 2 is **not** met then your loop will execute forever. This is what is commonly referred to as an _infinite loop_. Your code will appear to 'hang' when this happens, and you will need to somehow terminate the program and fix the problem (e.g., press Ctrl-C when running in Node). + +More info on MDN: [while](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/while) + +## do...while + +This is a variation of the while loop discussed above. Its general syntax is: + +```js +do { + // statement block to be repeated +} while (cond); +``` + +The do...while loop is executed at least once, because the loop condition is evaluated at the _end_ of the loop rather than at the _beginning_ as is the case with the regular `while` loop. + +Applied to our 'months' example the code would look like this: + +```js +const months = [ + ... +]; + +let index = 0; +const len = months.length; + +do { + console.log(months[index]); + index += 1; +} while (index < len) +``` + +We recommend that you do not use the `do...while` loop, exactly for the reason that the loop body is executed at least once without taking the loop condition into account. It is always possible to rewrite a `do...while` loop into a regular `while` loop that strictly meets the two preconditions mentioned earlier. + +More info on MDN: [do...while](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/do...while) + +## for + +The `for` loop is the most used loop construct that you will come across and that you are likely to use most in your own code. It exists in a number of variations in JavaScript that we will cover one by one below. The syntax of the most generic form is as follows: + +```js +for ([initialization]; [condition]; [final-expression]) { + // statement block to be repeated +} +``` + +Let's first look at an example: + +```js +const months = [ + ... +]; + +const len = months.length; + +for (let index = 0; index < len; index++) { + console.log(months[index]); +} +``` + +The `for` statement combines three parts of the loop construct in a single statement. Those three parts are separated by semicolons and, enclosed within parentheses, directly follow the `for` keyword. + +1. The first part is the for loop initialization of a loop 'index' variable, here called `index`. (Often you will see one letter variable names, such as `i` for the loop index.). This part is executed only once. +2. The second part is the loop condition, and is evaluated for every loop [iteration](http://www.dictionary.com/browse/iteration). The loop body is executed while this condition holds true. Note that this condition is tested at the beginning of the loop (like `while` above) and **not** at the end (like `do...while`). +3. The last part is where the loop index variable is updated, in this case incremented by one (`index++` is short for `index += 1`, which in itself is short for `index = index + 1`). This update is effectively done at the end of the loop (in the example, after the console.log has been executed). + +More info on MDN: [for](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for) + +## for...of + +The `for...of` loop construct is relatively new and very well suited for use with arrays. It was introduced with the ES6 variant of JavaScript. Its general syntax is: + +```js +for (variable of iterable) { + // statement block to be repeated +} +``` + +Here, `iterable` can be a couple of things, but most of the time it is just an array variable. Let's again look at an example. + +```js +const months = [ + ... +]; + +for (const month of months) { + console.log(month); +} +``` + +With this `for` loop variant, the array is considered a collection of elements (you can _iterate_ through a collection: it is 'iterable'). Each time the loop body is executed the loop variable receives the next value of the array (in the example, starting with `'January'` and ending with `'December'`). + +This now allows us to write very elegant and short code. No need to mess around with a loop index variable, array lengths etc. If you need to use a `for` loop involving arrays, this will often be your first choice. + +More on MDN: [for...of](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of) + +## for..in + +This loop variant is for use with JavaScript objects only. It existed before the `for...of` loop variant became available. + +We will discuss the `for...in` variant in more detail the part of the curriculum where we deal with Objects. Here, we will suffice to say that the `for...in` loop construct can easily be rewritten as a `for...of` loop, as follows: + +```js +const obj = { + a: 10, + b: 'test' +} + +// for...in +for (const key in obj) { + console.log(obj[key]) +} + +// equivalent for...of +for (const key of Object.keys(obj)) { + console.log(obj[key]) +} +``` + +More info on MDN: [for...in](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in) diff --git a/fundamentals/map_filter.md b/fundamentals/map_filter.md index f4451981c..899227e1b 100644 --- a/fundamentals/map_filter.md +++ b/fundamentals/map_filter.md @@ -120,7 +120,7 @@ The key to understanding the **reduce()** method is in the line: accumulator = reducerFn(accumulator, this[i], i, this); ``` -In the case we don't need the current loop index and the subject array in the reducer function (which is oftent the case), we can simplify this to: +In the case we don't need the current loop index and the subject array in the reducer function (which is often the case), we can simplify this to: ```js accumulator = reducerFn(accumulator, this[i]); diff --git a/fundamentals/promises.md b/fundamentals/promises.md index 38cfa37d8..0ee3cbe9d 100644 --- a/fundamentals/promises.md +++ b/fundamentals/promises.md @@ -25,7 +25,7 @@ getJSON(HYFReposApiEndpoint) Listing 1. Asynchronous XMLHttpRequest using a promise -The `getchJSON()` function call in Listing 1 returns a `promise` that resolves to some value converted from JSON data received from some remote API end point. The `fetchJSON()` function does the same, using a more modern browser Web API. +The `getJSON()` function call in Listing 1 returns a `promise` that resolves to some value converted from JSON data received from some remote API end point. The `fetchJSON()` function does the same, using a more modern browser Web API. ## What is a promise? @@ -58,7 +58,7 @@ A promise object exposes a `.then()` method through which you can obtain its ful somePromise.then(onFulfilled, onRejected) ``` -The `.then()` method takes two **optional** functions (technically they could be called *callbacks*), the first one dealing with the 'happy' scenario (the promise is fullfilled) and the second one dealing with the error case (the promise is rejected). If you are only interested in the success case you can leave out the second callback: +The `.then()` method takes two **optional** functions (technically they could be called *callbacks*), the first one dealing with the 'happy' scenario (the promise is fulfilled) and the second one dealing with the error case (the promise is rejected). If you are only interested in the success case you can leave out the second callback: ```js somePromise.then(onFulfilled) @@ -76,7 +76,7 @@ or you can use a second method exposed by a promise object, which is just a shor somePromise.catch(onRejected) ``` -It is important to understand that the `.then()` method returns a new promise that resolves to the return value of the `onFulfilled` callback (if specified) in case of the 'happy' scenario or the return value of the `onRejected` callback (if specified) in case of an error. If the return value of these functions is a plain JavaScript value, the new promise is immediately fulfilled with that value. If the return value is yet another promise then that promise itself is the fulfilment value. If the function does not return a value, the new promise is immediately fulfilled with the value `undefined`. +It is important to understand that the `.then()` method returns a new promise that resolves to the return value of the `onFulfilled` callback (if specified) in case of the 'happy' scenario or the return value of the `onRejected` callback (if specified) in case of an error. If the return value of these functions is a plain JavaScript value, the new promise is immediately fulfilled with that value. If the return value is yet another promise then that promise itself is the fulfillment value. If the function does not return a value, the new promise is immediately fulfilled with the value `undefined`. Because `.then()` (and `.catch`) return new promises, you can chain them together such that your code can be read as: do *this*, then do *that* and then *that*, etc.: @@ -94,8 +94,8 @@ Listing 2. Chaining of `then` and `catch` Let's analyze the code snippet of Listing 2 a bit more in light of what we have discussed up until now. 1. The `getJSON(HYFReposApiEndpoint)` function call returns a promise that will be fulfilled with an array of objects, describing the GitHub repositories of the HackYourFuture organisation. -2. In the first `.then()` the arrow function `res => getHtmlRepoList(res)` takes the place of `onFulfilled` from the discussion above. The *array-of-objects* from step 1 is passed as the `res` parameter and subsequently passed on to the `getHtmlReposList(res)` function call. This function in its turn returns a string of HTML tags, which becomes the fulfilment value of the new promise returned by the first `.then()`. -3. In the second `.then()` the arrow function `html => renderList($repoList, html)` uses the HTML string (the fulfilment value of the first `.then()`) to render the repo data to DOM. +2. In the first `.then()` the arrow function `res => getHtmlRepoList(res)` takes the place of `onFulfilled` from the discussion above. The *array-of-objects* from step 1 is passed as the `res` parameter and subsequently passed on to the `getHtmlReposList(res)` function call. This function in its turn returns a string of HTML tags, which becomes the fulfillment value of the new promise returned by the first `.then()`. +3. In the second `.then()` the arrow function `html => renderList($repoList, html)` uses the HTML string (the fulfillment value of the first `.then()`) to render the repo data to DOM. 4. The callback function from `.catch()` is only called when one of the promises in the chain is rejected. Otherwise is not called at all. See also: diff --git a/fundamentals/scope.md b/fundamentals/scope.md new file mode 100644 index 000000000..8dcf51dcb --- /dev/null +++ b/fundamentals/scope.md @@ -0,0 +1,119 @@ +# Scope + +## What is scope? + +Definition from [Dictionary.com](http://www.dictionary.com/browse/scope): + +> noun +1\. extent or range of view, outlook, application, operation, effectiveness, etc.: + +If you imagine yourself as the computer that is executing your JavaScript code, you can think of scope as meaning: + +> what you can see from where your are + +In this case the 'things' that you are looking for are variables and functions. When we say, "What's in scope?", we mean "Which variables and functions can be accessed from the current point of execution in your code?" As it happens, in JavaScript there are three types of scope to consider. + +## Global scope + +Variables and functions defined at global scope are visible from any point of execution in your code. Sometimes that's a good thing (or even essential), but more often it's bad. Let's dive right in. + +```js +a = 10; // don't do this +console.log(a); +``` + +In this example we have assigned the value `10` to a variable that we forgot to declare (we forgot to use `let`, `const` or `var`). The JavaScript engine tries to be helpful and defines a variable `a` for us in **global** scope. More recently, the JavaScript community considered this friendliness to be a mistake and with ES5 introduced `strict` mode: place the string `'use strict';` at the top of your file. + +```js +'use strict'; +a = 10; // produces: ReferenceError: a is not defined +console.log(a); +``` + +You can correct this by declaring your variable with `var`: + +```js +'use strict'; +var a = 10; +console.log(a); +``` + +This still puts the variable `a` into the global scope. So why is global scope a problem? Because you cannot be sure that the variable names you choose do not conflict with names already present in global scope (global scope is a busy place). It is best to apply the principle of 'need to know'. Only expose your variables to other parts in the JavaScript ecosystem that need to know about them. This is where local scope and block scope come in. + +## Local scope + +When you declare a function in JavaScript the function body represents a new, local scope, distinct from global scope. Variables defined in the function body are visible only inside that function: from the outside, you can't look in. + +```js +'use strict'; + +function myFunction() { + const a = 10; + console.log(a); +} + +myFunction(); + +// console.log(a); <= this would produce: ReferenceError: a is not defined +``` + +But from the inside you can look out. In the example below the variable `b` is visible from inside the function body. + +```js +'use strict'; + +const b = 'Hello'; + +function myFunction() { + const a = 10; + console.log(a); + console.log(b); +} + +myFunction(); +``` + +You might think that the variable `b` is in global scope. Actually, variables declared with either `let` or `const` have block scope, as will be discussed next. Note however that the function `myFunction` still resides in global scope. There is a way to even get `myFunction` out of global scope by using, what is called, an **IIFE**. See further down below. + +## Block scope + +The keywords `let` and `const` were introduced in ES6 as alternative to the older `var` keyword and we recommend that you use these newer keywords instead of `var`. They adhere to the rules for block scope, whereas `var` is completely oblivious of the concept. + +A new block scope (sometimes called _lexical_ scope) is created whenever you create a block of code inside a pair of curly braces. Variables defined with `let` and `const` at the file level (i.e., not inside a function) are considered to be in a (file-level) block scope. That's why the variable `b` in the previous code snippet is not in global scope. Had we replaced `const b` with `var b` then variable `b` _would be_ in global scope. + +## Guidance + +Following the principle of 'need to know', it is best to define variables at the point of need, i.e. just before you need to access these variables. This will either be in the same scope of the code where you access the variable, or, in case you need to access the variable from multiple places, the closest scope that is common to the points of need. + +Sometimes however, you cannot avoid global scope. This is for instance the case when you want to access the [DOM](https://developer.mozilla.org/en-US/docs/Glossary/DOM) in the browser. As you will learn, you can create an HTML element (e.g. an `h1` element) in JavaScript using this code: + +```js +const h1 = document.createElement('h1'); +``` + +The `document` object resides in global scope, conveniently provided there by the browser for access by any piece of JavaScript that needs to manipulate the DOM. + +## IFFE + +We were left with the issue that functions defined at the file level still end up in global scope. The traditional method of solving this in JavaScript is to use an Immediately Invoked Function Expression (IIFE). We present it here for info. When you build web applications with modern tools such as React and Node, you do not need to use IFFEs. + +To use an IFFE you must wrap all of your JavaScript code in a function body of an anonymous function (i.e., a function with no name) and immediately call that function (as indicated by the empty set of parentheses on the last line). This creates a local scope for your code. Now even the `myFunction` function is in local scope. + +```js +(function () { + 'use strict'; + + const b = 'Hello'; + + function myFunction() { + const a = 10; + console.log(a); + console.log(b); + } + + myFunction(); +})(); +``` + +More info on MDN: [IFFE](https://developer.mozilla.org/en-US/docs/Glossary/IIFE) +