From 2265d8891d572bd12541dc6f9f9fd09d392cf9fd Mon Sep 17 00:00:00 2001 From: Jonathan Yiv Date: Sun, 8 Apr 2018 14:57:58 -0400 Subject: [PATCH] Ran the course through a spelling/grammar checker --- JS101/fundamentals/fundamentals-1.md | 14 +- async-apis/APIs.md | 140 ++++++++++---------- async-apis/json.md | 6 +- async-apis/project.md | 4 +- conclusion.md | 8 +- js-in-the-real-world/es6-features.md | 14 +- js-in-the-real-world/linting.md | 36 +++-- js-in-the-real-world/ui-Interactions.md | 30 ++--- js-in-the-real-world/webpack-2.md | 8 +- main-course-introduction/introduction.md | 10 +- organizing-js/classes.md | 12 +- organizing-js/es6-modules.md | 54 ++++---- organizing-js/factory-functions.md | 162 +++++++++++------------ organizing-js/library-project.md | 36 ++--- organizing-js/objects-constructors.md | 100 +++++++------- organizing-js/oop-concepts.md | 40 +++--- organizing-js/organizing-introduction.md | 6 +- organizing-js/restaurant-project.md | 30 ++--- 18 files changed, 360 insertions(+), 350 deletions(-) diff --git a/JS101/fundamentals/fundamentals-1.md b/JS101/fundamentals/fundamentals-1.md index f8dd4c05..b2aea5f6 100644 --- a/JS101/fundamentals/fundamentals-1.md +++ b/JS101/fundamentals/fundamentals-1.md @@ -3,17 +3,17 @@ Let's dive right in! ### Learning Outcomes Look through these now and then use them to test yourself after doing the assignment: -* How do you declare a variable in javascript? +* How do you declare a variable? * What are three different ways to declare a variable? * Which one should you use when? * What are the rules for naming variables? * What are operators, operands, and operations? * What is concatenation and what happens when you add numbers and strings together? -* What are the different type of operators in Javascript? +* What are the different type of operators in JavaScript? * What is the difference between `==` and `===`? * What are operator precedence values? * What are the increment/decrement operators? -* What is the difference between prefixing and postfixing them? +* What is the difference between prefixing and post-fixing them? * What are assignment operators? * What is the "Unary +" Operator? @@ -30,11 +30,11 @@ Numbers are the building blocks of programming logic! In fact, it's hard to thi You can think of variables simply as "storage containers" for data in your code. Until recently there was only one way to declare and use a variable in Javascript (the `var` keyword) but the latest versions of JavaScript include 2 more keywords that can be used depending on the situation. The following resources will tell you what you need to know! 1. Read through [this variable tutorial](http://javascript.info/variables) as well. It covers the other methods of variable creation. __Be sure to do the Tasks__ at the end of this article! Information won't stick without practice! -2. Sidenote: It's mentioned in the above tutorial, but important enough to note specifically here. `let` and `const` are both relatively new ways to declare variables in JavaScript. In _many_ tutorials and in code across the internet you are likely to encounter `var`. Don't let it bother you! You should stick to `let` and `const` for now. There is nothing inherently wrong with `var`, but in a few small cases it's behavior is not what you would expect. In most cases `var` and `let` behave exactly the same. The precise difference will be explained later. +2. Sidenote: It's mentioned in the above tutorial, but important enough to note specifically here. `let` and `const` are both relatively new ways to declare variables in JavaScript. In _many_ tutorials and in code across the internet you are likely to encounter `var`. Don't let it bother you! You should stick to `let` and `const` for now. There is nothing inherently wrong with `var`, but in a few small cases its behavior is not what you would expect. In most cases `var` and `let` behave exactly the same. The precise difference will be explained later. ### Practice! -You can easily run your own JavaScript code from files that you create on your own computer. The simplest way to get started is to simply create an html file with the JavaScript code inside of it. Type the basic html skeleton into a file on your computer somewhere: +You can easily run your own JavaScript code from files that you create on your own computer. The simplest way to get started is to simply create an HTML file with the JavaScript code inside of it. Type the basic HTML skeleton into a file on your computer somewhere: ~~~html @@ -51,7 +51,7 @@ You can easily run your own JavaScript code from files that you create on your o ~~~ -Save and open this file up in a web browser and then open up the browser's console by right-clicking on the blank webpage and selecting "Inspect" or "Inspect Element". In the developer tools pane find and select the 'console' tab, where you should see the output of our `console.log` statement. +Save and open this file up in a web browser and then open up the browser's console by right-clicking on the blank webpage and selecting "Inspect" or "Inspect Element". In the 'Developer Tools' pane find and select the 'Console' tab, where you should see the output of our `console.log` statement. > `console.log()` is the command to print something to the developer console in your browser. Use it for all of the following exercises. @@ -71,4 +71,4 @@ Try the following exercises. 2. Set another variable `actual` to `max - 13` 3. Set another variable `percentage` to `actual / max` 4. If you type `percentage` in the console and press enter you should see a value like `0.7719` -6. Take a few minutes to keep playing around with various things in your script tag. Eventually we will learn how to actually make those numbers and things show up on the webpage, but all of this logic will remain the same, so make sure you're comfortable with it before moving on. +6. Take a few minutes to keep playing around with various things in your script tag. Eventually, we will learn how to actually make those numbers and things show up on the webpage, but all of this logic will remain the same, so make sure you're comfortable with it before moving on. diff --git a/async-apis/APIs.md b/async-apis/APIs.md index 63dbbcbd..3bc4c912 100644 --- a/async-apis/APIs.md +++ b/async-apis/APIs.md @@ -1,18 +1,18 @@ ### Introduction -One of the most powerful things a web developer can do is fetching data from a server and displaying it creatively on their site. In many cases the server solely exists for that specific site. The server could contain blog posts, user data, high scores for a game or anything else. In other cases, the server is an open service that serves data to anyone that wants to use it (ie. weather data or stock prices). In either case, the methods of accessing and then using that data are essentially the same. +One of the most powerful things a web developer can do is fetching data from a server and displaying it creatively on their site. In many cases, the server solely exists for that specific site. The server could contain blog posts, user data, high scores for a game or anything else. In other cases, the server is an open service that serves data to anyone that wants to use it (i.e. weather data or stock prices). In either case, the methods of accessing and then using that data are essentially the same. ### APIs Servers that are created for serving data for external use (in websites or apps) are often referred to as `API`s or ['Application Programming Interfaces'](https://www.youtube.com/watch?v=s7wmiS2mSXY). -There are multiple ways of requesting data from an API, but all of them basically do the same thing. For the most part, APIs are accessed through URLs, and the specifics of how to query these URLs changes based on the specific service you are using. For example the OpenWeatherMap API has several different types of data that you can request. To get the current weather in a specific location you need to request data from this URL: +There are multiple ways of requesting data from an API, but all of them basically do the same thing. For the most part, APIs are accessed through URLs, and the specifics of how to query these URLs changes based on the specific service you are using. For example, the OpenWeatherMap API has several types of data that you can request. To get the current weather in a specific location, you need to request data from this URL: ~~~ api.openweathermap.org/data/2.5/weather?q=London,uk ~~~ -You'll want to switch out the city for the location you're requesting. The specifics for using any API are usually documented on the service's website. [Check here for the OpenWeatherMap API documentation](https://openweathermap.org/current). +You'll want to switch out the city for the location you're requesting. The specifics for using any API are usually documented on the service's website. [Check here for the OpenWeatherMap API documentation](https://openweathermap.org/current). If you haven't already, go ahead and paste the weather URL above into your browser...(we'll wait). @@ -22,7 +22,7 @@ Unless the implementation of that specific API has changed, you probably get an {"code":401, "message": "Invalid API key. Please see http://openweathermap.org/faq#error401 for more info."} ~~~ -This brings us to another point about APIs. In most cases you have to sign up and get an API key to use them. Obtaining the API key is as simple as signing up on their website and using it is usually as easy as pasting it into the URL: +This brings us to another point about APIs. In most cases, you have to sign up and get an API key to use them. Obtaining the API key is as simple as signing up on their website and using it is usually as easy as pasting it into the URL: ~~~ http://api.openweathermap.org/data/2.5/weather?q=London,uk&APPID=1111111111 @@ -30,9 +30,9 @@ http://api.openweathermap.org/data/2.5/weather?q=London,uk&APPID=1111111111 (exactly how to include the key changes from service to service) -Services like the OpenWeatherMap use API keys to track who is requesting the data they serve, and how much data they are requesting. The reason they do this is so that people can't take advantage of their service. Running servers, especially large ones costs money, and while each current weather request (or whatever) is relatively cheap, if the amount of requests gets too high the cost could be significant. Imagine using that API to create an amazing weather app that gets used all over the world....you could easily have thousands of people accessing that data every minute! +Services like the OpenWeatherMap use API keys to track who is requesting the data they serve, and how much data they are requesting. The reason they do this is so that people can't take advantage of their service. Running servers, especially large ones costs money, and while each current weather request (or whatever) is relatively cheap, if the amount of requests gets too high the cost could be significant. Imagine using that API to create an amazing weather app that gets used all over the world....you could easily have thousands of people accessing that data every minute! -By signing up for a service and getting an API key you are letting the service track how much you are actually using. In many cases services are limited as to how much data they can request for free. With the weather app example, their free plan only allows you to make 60 requests per minute and also limits what types of data you can access ([details here if you're interested](https://openweathermap.org/price)). So, if your app became successful, you would probably need to pay for a better account. +By signing up for a service and getting an API key you are letting the service track how much you are actually using. In many cases services are limited as to how much data they can request for free. With the weather app example, their free plan only allows you to make 60 requests per minute and also limits what types of data you can access ([details here if you're interested](https://openweathermap.org/price)). So, if your app became successful, you would probably need to pay for a better account. Luckily for us, the majority our apps are only going to be used by us and the people that view our portfolios. So we'll get by _just fine_ with free services. @@ -46,22 +46,22 @@ Once you get a key (try this now if you like!) you can paste the URL into the br So how do we actually get the data from an API into our code? -A couple of years ago the main way to access API data in your code was using a `XMLHttpRequest`. This function still works in all browsers, but unfortunately it is not particularly nice to use. The syntax looks something like this: +A couple of years ago the main way to access API data in your code was using an `XMLHttpRequest`. This function still works in all browsers, but unfortunately, it is not particularly nice to use. The syntax looks something like this: ~~~javascript // Just getting XHR is a mess! if (window.XMLHttpRequest) { // Mozilla, Safari, ... - request = new XMLHttpRequest(); +  request = new XMLHttpRequest(); } else if (window.ActiveXObject) { // IE - try { - request = new ActiveXObject('Msxml2.XMLHTTP'); - } - catch (e) { - try { - request = new ActiveXObject('Microsoft.XMLHTTP'); - } - catch (e) {} - } +  try { +    request = new ActiveXObject('Msxml2.XMLHTTP'); +  } +  catch (e) { +    try { +      request = new ActiveXObject('Microsoft.XMLHTTP'); +    } +    catch (e) {} +  } } // Open, send. @@ -71,66 +71,66 @@ request.send(null); Ouch. That was painful. -Developers, feeling the pain of having to write that stuff out, began writing 3rd party libraries to take care of this and make it much easier to use. Some of the more popular libraries are [request](https://github.com/request/request), [axios](https://github.com/mzabriskie/axios), and [superagent](https://github.com/visionmedia/superagent), all of which have their strengths and weaknesses. +Developers, feeling the pain of having to write that stuff out, began writing 3rd party libraries to take care of this and make it much easier to use. Some of the more popular libraries are [request](https://github.com/request/request), [axios](https://github.com/mzabriskie/axios), and [superagent](https://github.com/visionmedia/superagent), all of which have their strengths and weaknesses. -More recently, however, web browsers have begun to implement a new native function for making HTTP requests, and that's the one we're going to use and stick with for now. Meet fetch: +More recently, however, web browsers have begun to implement a new native function for making HTTP requests, and that's the one we're going to use and stick with for now. Meet fetch: ~~~javascript // URL (required), options (optional) fetch('https://url.com/some/url') - .then(function(response) { +  .then(function(response) { }).catch(function(err) { - // Error :( +  // Error :( }); ~~~ -In case you've forgotten, scroll back up and look at how you would use XHR to do the same thing. While you're admiring how nice and clean that code is, notice the `.then()` and `.catch()` functions there. Do you remember what those are? (PROMISES!) +In case you've forgotten, scroll back up and look at how you would use XHR to do the same thing. While you're admiring how nice and clean that code is, notice the `.then()` and `.catch()` functions there. Do you remember what those are? (PROMISES!) -Let's change up our API for this example. We're going to walk through an example using fetch with the [giphy](https://giphy.com/) API to display a random gif on a webpage. The API requires you to sign up and get a free API key, so go ahead and [do that here](https://developers.giphy.com/docs/). +Let's change up our API for this example. We're going to walk through an example using fetch with the [giphy](https://giphy.com/) API to display a random gif on a webpage. The API requires you to sign up and get a free API key, so go ahead and [do that here](https://developers.giphy.com/docs/). -Giphy has several methods for searching and finding gifs which you can read about in their documentation. Today we're just going to use the 'translate' endpoint because it's the simplest one for our purposes. You can find the appropriate URL in their documentation by scrolling down [here](https://developers.giphy.com/docs/). What it tells us is that the correct URL is `api.giphy.com/v1/gifs/translate` and that it requires 2 parameters, your `api_key` and a `s`earch term. If you put it all together correctly (with YOUR API key) you should get something like this: +Giphy has several methods for searching and finding gifs which you can read about in their documentation. Today we're just going to use the 'translate' endpoint because it's the simplest one for our purposes. You can find the appropriate URL in their documentation by scrolling down [here](https://developers.giphy.com/docs/). What it tells us is that the correct URL is `api.giphy.com/v1/gifs/translate` and that it requires 2 parameters, your `api_key` and a `s`earch term. If you put it all together correctly (with YOUR API key) you should get something like this: ~~~javascript 'https://api.giphy.com/v1/gifs/translate?api_key=1111111&s=cats' // of course we're searching for cats ~~~ -Go ahead and try that URL (with YOUR API key) in a browser. If everything goes well you should get a relatively long string of data and no errors. +Go ahead and try that URL (with YOUR API key) in a browser. If everything goes well you should get a relatively long string of data and no errors. ### CORS -A sidenote before we start putting this into our code. For security reasons, by default, browsers restrict HTTP requests to outside sources (which is exactly what we're trying to do here). There's a very small amount of setup that we need to do to make fetching work. Learning about this is outside our scope right now, but if you want to learn a bit about it this [wikipedia article](https://en.wikipedia.org/wiki/Cross-origin_resource_sharing) is a decent starting point. +A side note before we start putting this into our code. For security reasons, by default, browsers restrict HTTP requests to outside sources (which is exactly what we're trying to do here). There's a very small amount of setup that we need to do to make fetching work. Learning about this is outside our scope right now, but if you want to learn a bit about it this [wikipedia article](https://en.wikipedia.org/wiki/Cross-origin_resource_sharing) is a decent starting point. -Whether or not you took the detour to learn all about Cross Origin Resource Sharing (CORS) the fix is simple. With fetch, you are able to easily supply a JavaScript object for options. It comes right after the URL as a second parameter to the fetch function: +Whether or not you took the detour to learn all about Cross Origin Resource Sharing (CORS) the fix is simple. With fetch, you are able to easily supply a JavaScript object for options. It comes right after the URL as a second parameter to the fetch function: ~~~javascript fetch('url.url.com/api', { - mode: 'cors' +  mode: 'cors' }) ~~~ -Simply adding the `{mode: 'cors'}` after the URL as shown above will solve our problems for now. In the future, however, you may want to look further into the implications of this restriction. +Simply adding the `{mode: 'cors'}` after the URL, as shown above, will solve our problems for now. In the future, however, you may want to look further into the implications of this restriction. ### Let's Do This -For now we're going to keep all of this in a single HTML file. So go ahead and create one with a single blank image tag and an empty script tag in the body. +For now, we're going to keep all of this in a single HTML file. So go ahead and create one with a single blank image tag and an empty script tag in the body. ~~~HTML - - DocumentDocument - - ~~~ -In the script tag, lets start by selecting the image and assigning it to a variable so that we can change the URL once we've received it from the Giphy API. +In the script tag, let's start by selecting the image and assigning it to a variable so that we can change the URL once we've received it from the Giphy API. ~~~HTML ~~~ @@ -138,26 +138,26 @@ Adding fetch with our URL from above is also relatively easy: ~~~HTML ~~~ -You should now be able to open the HTML file in your browser, and while you won't see anything on the page, you _should_ have something logged in the console. The trickiest part of this whole process is deciphering how to get to the data you desire from the server's response. In this case, inspecting the browser's console will reveal that what's being returned is _another_ Promise... to get the data we need another `.then()` function. +You should now be able to open the HTML file in your browser, and while you won't see anything on the page, you _should_ have something logged in the console. The trickiest part of this whole process is deciphering how to get to the data you desire from the server's response. In this case, inspecting the browser's console will reveal that what's being returned is _another_ Promise... to get the data we need another `.then()` function. ~~~HTML ~~~ @@ -169,40 +169,40 @@ To get to the data we need to drill down through the layers of the object until ~~~HTML ~~~ -Running the file should now log the URL of the image. All that's left to do is set the source of the image that's on the page to the URL we've just accessed: +Running the file should now log the URL of the image. All that's left to do is set the source of the image that's on the page to the URL we've just accessed: ~~~HTML ~~~ If all goes well, you should see a new image on the page every time you refresh! -If you've gotten lost along the way, check out [this jsbin project](http://jsbin.com/canofar/edit?html,output). Besides the glorious styling, this is what your version should look like. +If you've gotten lost along the way, check out [this jsbin project](http://jsbin.com/canofar/edit?html,output). Besides the glorious styling, this is what your version should look like. ### Assignment
-1. Read the fetch documentation [here](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch). It's not all that complicated to use, but we've only really scratched the surface at this point. +1. Read the fetch documentation [here](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch). It's not all that complicated to use, but we've only really scratched the surface at this point. 2. Check out [this list](https://github.com/abhishekbanthia/Public-APIs?utm_source=SitePoint&utm_medium=email&utm_campaign=Versioning#natural-language-processing) of free, open APIs and let your imagination go wild. 3. Expand on our little project here by adding a button that fetches a new image without refreshing the page. 4. Add a search box so users can search for specific gifs. You should also investigate adding a `.catch()` to the end of the promise chain in case Giphy doesn't find any gifs with the searched keyword. Add a default image, or an error message if the search fails. diff --git a/async-apis/json.md b/async-apis/json.md index 0d272455..e12a7b82 100644 --- a/async-apis/json.md +++ b/async-apis/json.md @@ -1,13 +1,13 @@ ### Introduction -JSON (JavaScript Object Notation) is a standardized format for structuring data. It is heavily based on the syntax for JavaScript objects. You will often encounter JSON formatted data when working with external servers or APIs - it is essentially the universal format for transmitting data on the web. +JSON (JavaScript Object Notation) is a standardized format for structuring data. It is heavily based on the syntax for JavaScript objects. You will often encounter JSON formatted data when working with external servers or APIs - it is essentially the universal format for transmitting data on the web. -Fortunately there isn't much to learn here. We're only including a lesson on it because some of the formatting rules can cause confusion if you aren't aware of them. Spend 10-15 minutes going through the following resources and you'll be good to go. +Fortunately, there isn't much to learn here. We're only including a lesson on it because some formatting rules can cause confusion if you aren't aware of them. Spend 10-15 minutes going through the following resources and you'll be good to go. ### Assignment
1. [This MDN tutorial]( https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/JSON) is probably all you need... 2. Read about the 2 JavaScript methods that you'll most often be using when dealing with JSON - [JSON.parse()](https://www.w3schools.com/js/js_json_parse.asp) and [JSON.stringify()](https://www.w3schools.com/js/js_json_stringify.asp). -3. Misformatted JSON is a common cause of errors. [This webpage](https://jsonformatter.curiousconcept.com/) lets you paste in JSON code and will search it for formatting errors. +3. Mis-formatted JSON is a common cause of errors. [This webpage](https://jsonformatter.curiousconcept.com/) lets you paste in JSON code and will search it for formatting errors.
diff --git a/async-apis/project.md b/async-apis/project.md index da5ff24e..e777f3e4 100644 --- a/async-apis/project.md +++ b/async-apis/project.md @@ -1,10 +1,10 @@ ### Introduction Use everything we've been discussing to create a weather forecast site using the weather API from the previous lesson. You should be able to search for a specific location and toggle displaying the data in Fahrenheit or Celsius. -You should change the look of the page based on the data, maybe by changing the color of the background or by adding images that describe the weather. (You could even use the Giphy API to find appropriate weather related gifs and display them). +You should change the look of the page based on the data, maybe by changing the color of the background or by adding images that describe the weather. (You could even use the Giphy API to find appropriate weather-related gifs and display them). 1. Set up a blank HTML document with the appropriate links to your JavaScript and CSS files. -2. Write the functions that hit the API. You're going to want functions that can take a location and return the weather data for that location. For now just console.log() the information. +2. Write the functions that hit the API. You're going to want functions that can take a location and return the weather data for that location. For now, just console.log() the information. 3. Write the functions that _process_ the JSON data you're getting from the API and return an object with only the data you require for your app. 4. Set up a simple form that will let users input their location and will fetch the weather info (still just console.log() it). 5. Display the information on your webpage! diff --git a/conclusion.md b/conclusion.md index c62ea33b..f13422b7 100644 --- a/conclusion.md +++ b/conclusion.md @@ -1,12 +1,12 @@ -This is the end! At this point you should have a deep and nuanced understanding of not just how Javascript works but how you can use it with all the other knowledge you've gained so far to build exceptional web applications. That means great information architectures, smooth-running Rails backends and delightfully useful front-ends. +This is the end! At this point, you should have a deep and nuanced understanding of not just how Javascript works but how you can use it with all the other knowledge you've gained so far to build exceptional web applications. That means great information architectures, smooth-running Rails back-ends, and delightfully useful front-ends.   -If you find something you don't know or aren't quite sure about, you should be a pro by now at Googling your way to an answer, looking at docs, and cruising through Stack Overflow posts. You've got all the tools you need to be a developer. And, really, the big secret is that you've been a web developer for a long time already. +If you find something you don't know or aren't quite sure about, you should be a pro by now at Googling your way to an answer, looking at docs, and cruising through Stack Overflow posts. You've got all the tools you need to be a developer. And, really, the big secret is that you've been a web developer for a long time already. -So where do you go from here? BUILD! Build and build and build and build (see a theme in this curriculum yet?). Use what you've learned to create great projects. Get a job so someone else pays you to build. But focus on creating interesting software and using that to drive your education. +So where do you go from here? BUILD! Build and build and build and build (see a theme in this curriculum yet?). Use what you've learned to create great projects. Get a job so someone else pays you to build. But focus on creating interesting software and using that to drive your education.   There's a whole world of additional things you can learn -- jQuery mobile to build mobile apps, D3 for data visualization, other full-stack frameworks or single-page MVC front-end frameworks... all that stuff is best learned when you've got something you want to build that requires "the perfect tool for the job." -And speaking of jobs, if you've made it this far then you've displayed the kind of capability and drive that employers are looking for. The final step is to show that to the world and get them to pay you to keep learning. Which just happens to be the subject of the next course... +And speaking of jobs, if you've made it this far then you've displayed the kind of capability and drive that employers are looking for. The final step is to show that to the world and get them to pay you to keep learning. Which just happens to be the subject of the next course... ### Additional Resources diff --git a/js-in-the-real-world/es6-features.md b/js-in-the-real-world/es6-features.md index c4973b8b..e887c784 100644 --- a/js-in-the-real-world/es6-features.md +++ b/js-in-the-real-world/es6-features.md @@ -1,19 +1,19 @@ ### Introduction We've been throwing around the term __ES6__ since our very first lessons, but we haven't taken the time to properly explain what it means or to investigate the implications of it in our code. -Put simply ES6 is a version of JavaScript that was officially released in the summer of 2015. It included _many_ new features that make writing JavaScript much easier and cleaner. If you have been following our lessons you have already been learning these new features because, well, ES6 is _just JavaScript_. +Put simply ES6 is a version of JavaScript that was officially released in the summer of 2015. It included _many_ new features that make writing JavaScript much easier and cleaner. If you have been following our lessons you have already been learning these new features because, well, ES6 is _just JavaScript_. -You have probably also come across articles talking about features in ES7 or ES8 or ES2015 or ES2017 etc. Part of the confusion here is that right after the release of ES6, the committee that makes these decisions changed the naming scheme from 'version numbers' (ES5, ES6, ES7 etc.) to 'release years' (ES2015, ES2016, ES2017 etc.) +You have probably also come across articles talking about features in ES7 or ES8 or ES2015 or ES2017 etc. Part of the confusion here is that right after the release of ES6, the committee that makes these decisions changed the naming scheme from 'version numbers' (ES5, ES6, ES7 etc.) to 'release years' (ES2015, ES2016, ES2017 etc.) - [This article](https://codeburst.io/javascript-wtf-is-es6-es8-es-2017-ecmascript-dca859e4821c) provides a nice clean explanation and timeline of the various ECMAScript releases. -- [This document](https://github.com/lukehoban/es6features) outlines all of the new features that showed up in ES6. As we've mentioned you've already been using many of these, though there are a few we haven't specifically covered yet. +- [This document](https://github.com/lukehoban/es6features) outlines all the new features that showed up in ES6. As we've mentioned you've already been using many of these, though there are a few we haven't specifically covered yet. -The _problem_ with JavaScript constantly updating and adding features is that it sometimes takes web-browsers a while to catch up and implement new features once they've been released. At the current time all modern browsers (Chrome, Firefox, Safari and Edge) support _all_ of ES6, and _most_ of ES7, but older browsers (various versions of Internet Explorer for instance) do not. This means, unfortunately, that if you write code that uses these new features it __will not run__ in browsers that do not support it. +The _problem_ with JavaScript constantly updating and adding features is that it sometimes takes web-browsers a while to catch up and implement new features once they've been released. At the current time all modern browsers (Chrome, Firefox, Safari and Edge) support _all_ of ES6, and _most_ of ES7, but older browsers (various versions of Internet Explorer for instance) do not. This means, unfortunately, that if you write code that uses these new features it __will not run__ in browsers that do not support it. For most of us, this has not been an issue because you are almost definitely using a new browser that automatically updates itself when a new version is released. But in the real world, if you're selling products to customers you can't control which browsers people will use to connect to your site. -Fortunately there _is_ solution to this problem. [Babel](http://babeljs.io/) is a tool that takes your modern JavaScript code and __transpiles__ it to code that older browsers can understand. It can be used from the command line with a simple command, and can also easily be added to your webpack configuration. With the babel-loader. +Fortunately there _is_ solution to this problem. [Babel](http://babeljs.io/) is a tool that takes your modern JavaScript code and __transpiles__ it to code that older browsers can understand. It can be used from the command line with a simple command, and can also easily be added to your webpack configuration. With the babel-loader. -In all honesty, this is not something that you are going to _need_ to worry about on every project you're starting. All of the ES6 features are present in the large majority of browsers used worldwide. But JavaScript is constantly changing, and as new features are announced and released you can use Babel to try them out, often before they're available in _any_ browser! +In all honesty, this is not something that you are going to _need_ to worry about on every project you're starting. All the ES6 features are present in the large majority of browsers used worldwide. But JavaScript is constantly changing, and as new features are announced and released, you can use Babel to try them out, often before they're available in _any_ browser! -- Follow the instructions [here](https://github.com/babel/babel-loader) to install the babel-loader and use it with webpack. If you've already got webpack up and running in a project, adding babel is a cinch! +- Follow the instructions [here](https://github.com/babel/babel-loader) to install the babel-loader and use it with webpack. If you've already got webpack up and running in a project, adding babel is a cinch! diff --git a/js-in-the-real-world/linting.md b/js-in-the-real-world/linting.md index bc41021c..b18b37ec 100644 --- a/js-in-the-real-world/linting.md +++ b/js-in-the-real-world/linting.md @@ -1,32 +1,42 @@ + +Info. Your report was run on the first 500 words of your text. To run on the full text Request a Trial or Go Premium +Report Summary +Clear Filters + spelling 5 issues found + grammar 7 issues found +Grammar Check +Checks your text for grammar errors and potential word mis-use. +More about this report ### Style Guides -Code style is important! Having a consistent set of style rules for things such as indentation or preferred quote style makes your code more maintainable and easier to read. There are several popular javascript style guides on the net that set standards for these types of things, and a little time spent reading them _will_ make you a better developer. +Code style is important! Having a consistent set of style rules for things such as indentation or preferred quote style makes your code more maintainable and easier to read. There are several popular JavaScript style guides on the net that set standards for these types of things, and a little time spent reading them _will_ make you a better developer. -1. The [Airbnb Style Guide](https://github.com/airbnb/javascript) is one of the most popular. It is also very well formatted and easy to read. +1. The [Airbnb Style Guide](https://github.com/airbnb/javascript) is one of the most popular. It is also very well formatted and easy to read. 2. Google also has their own [style guide](https://google.github.io/styleguide/jsguide.html) for JavaScript. ### Linting -The style guides we mentioned above are full of really helpful advice for formatting, organizing and composing your code. But there are a _lot_ of rules - it can be difficult to internalize them all. __Linters__ are tools that will scan your code with a set of style rules and will report any errors to you that they find. In some cases they can even auto-fix the errors! The following articles explain in more detail the benefits of using a linter while you code. +The style guides we mentioned above are full of really helpful advice for formatting, organizing and composing your code. But there are a _lot_ of rules - it can be difficult to internalize them all. __Linters__ are tools that will scan your code with a set of style rules and will report any errors to you that they find. In some cases, they can even auto-fix the errors! The following articles explain in more detail the benefits of using a linter while you code. - 1. [This article](http://mikecavaliere.com/javascript-linting-what-developers-need-to-know/) gets right to the point... start here! - 2. [This article](https://hackernoon.com/how-linting-and-eslint-improve-code-quality-fa83d2469efe) goes a little further by discussing exactly _how_ linters do what they do. + 1. [This article](http://mikecavaliere.com/javascript-linting-what-developers-need-to-know/) gets right to the point... start here! + 2. [This article](https://hackernoon.com/how-linting-and-eslint-improve-code-quality-fa83d2469efe) goes a little further by discussing exactly _how_ linters do what they do. -There are multiple options for linting your JavaScript, but the most popular (and most common in the industry) is [eslint](https://eslint.org/). Getting it installed and the initial set-up is fairly simple. +There are multiple options for linting your JavaScript, but the most popular (and most common in the industry) is [eslint](https://eslint.org/). Getting it installed and the initial set-up is fairly simple. -1. [The official 'Getting Started' page](https://eslint.org/docs/user-guide/getting-started) is a good place to start. It covers installation and basic setup. The basic way to use this tool is to simply run the `eslint` command in your terminal with a specific file. -2. Far more useful are linting plugins for your favorite text editor. Most editor plugins allow you to automatically lint your code as you are writing it, and will show the errors right in the editor, which makes resolving them _much_ simpler. We can't cover _every_ editor installation but some of the more popular are: +1. [The official 'Getting Started' page](https://eslint.org/docs/user-guide/getting-started) is a good place to start. It covers installation and basic setup. The basic way to use this tool is to simply run the `eslint` command in your terminal with a specific file. +2. Far more useful are linting plugins for your favorite text editor. Most editor plugins allow you to automatically lint your code as you are writing it, and will show the errors right in the editor, which makes resolving them _much_ simpler. We can't cover _every_ editor installation but some of the more popular are: 1. Visual Studio Code - [The Plugin](https://marketplace.visualstudio.com/items?itemName=dbaeumer.vscode-eslint) and [a tutorial](http://shripalsoni.com/blog/configure-eslint-in-visual-studio-code/). 2. Sublime Text - [The Plugin](https://github.com/roadhump/SublimeLinter-eslint) and [a tutorial](http://jonathancreamer.com/setup-eslint-with-es6-in-sublime-text/). 3. Atom - [The Plugin](https://atom.io/packages/linter-eslint) and [a tutorial](https://medium.freecodecamp.org/how-to-set-up-eslint-in-atom-to-contribute-to-freecodecamp-3467dee86e2c). - 4. Vim - [Use the ALE plugin](https://github.com/w0rp/ale). If you use vim you already know what you're getting into. ALE is a great plugin, but the setup and configuration can be a little tricky. + 4. Vim - [Use the ALE plugin](https://github.com/w0rp/ale). If you use vim you already know what you're getting into. ALE is a great plugin, but the setup and configuration can be a little tricky. ### Prettier -Prettier is _awesome_. It is similar to a linter, but serves a slightly different function. Prettier will take your JS code and then automatically format it according to a set of rules. Unlike a linter, it's not looking for style errors, but specifically targeting the layout of your code and making intelligent decisions about things like spaces, indentation levels and line-breaks. +Prettier is _awesome_. It is similar to a linter, but serves a slightly different function. Prettier will take your JS code and then automatically format it according to a set of rules. Unlike a linter, it's not looking for style errors, but specifically targeting the layout of your code and making intelligent decisions about things like spaces, indentation levels and line-breaks. 1. [This quick talk](https://www.youtube.com/watch?v=hkfBvpEfWdA) from prettier's creator is a great introduction. -2. Give it a test drive [here](https://prettier.io/playground). Go ahead and copy/paste some of your old JavaScript code into that editor and see what happens. -3. Setup is simple. [The homepage](https://prettier.io/) links to tutorials for most popular editors. +2. Give it a test drive [here](https://prettier.io/playground). Go ahead and copy/paste some of your old JavaScript code into that editor and see what happens. +3. Setup is simple. [The homepage](https://prettier.io/) links to tutorials for most popular editors. + +Using prettier makes coding faster and easier! You don't have to worry about nailing things like indentation, or remembering every semi-colon because prettier will take care of those details for you -Using prettier makes coding faster and easier! You don't have to worry about nailing things like indentation, or remembering every semi-colon because prettier will take care of those details for you diff --git a/js-in-the-real-world/ui-Interactions.md b/js-in-the-real-world/ui-Interactions.md index 4e9e967f..8e0fc065 100644 --- a/js-in-the-real-world/ui-Interactions.md +++ b/js-in-the-real-world/ui-Interactions.md @@ -1,39 +1,39 @@ ### Introduction -JavaScript is a very powerful language. It is capable of creating complex web applications that work _everywhere_. But it is just as often used on a smaller scale. JavaScript is the glue that holds even less flashy websites together- it makes dropdowns drop down and image sliders slide. +JavaScript is a very powerful language. It is capable of creating complex web applications that work _everywhere_. But it is just as often used on a smaller scale. JavaScript is the glue that holds even less flashy websites together- it makes drop-downs drop down and image sliders slide.   -Fortunately at this point you already have all the tools you need to make these items without resorting to using a bloated framework like bootstrap. (Nothing against bootstrap... you just do _not_ need it! Good for you!) +Fortunately, at this point, you already have all the tools you need to make these items without resorting to using a bloated framework like bootstrap. (Nothing against bootstrap... you just do _not_ need it! Good for you!) We aren't presenting any new content in this lesson - just giving you the chance to practice some of the techniques that you're going to be using on a daily basis as a JavaScript programmer. -> Animations are typically handled by CSS which is a little out of the scope of this lesson, but interactive stuff like this is no fun without a little motion! If you want to take a break and learn more about making stuff move [go watch this video](https://www.youtube.com/watch?v=8kK-cA99SA0). +> Animations are typically handled by CSS which is a little out of the scope of this lesson, but interactive stuff like this is no fun without a little motion! If you want to take a break and learn more about making stuff move [go watch this video](https://www.youtube.com/watch?v=8kK-cA99SA0). -### Dropdown menus +### Drop-down Menus -You know what we're talking about here. Picture a nav-bar or a button and when you click it the menu slides down nicely. As mentioned previously, you already know everything you need to create this element. Here are some things to keep in mind: +You know what we're talking about here. Picture a nav-bar or a button and when you click it the menu slides down nicely. As mentioned previously, you already know everything you need to create this element. Here are some things to keep in mind: 1. You can allow the menu to show up either on click or on hover. -2. You should hard-code the menu items into your HTML but hide/reveal them using JavaScript. You can do this either by adding a class (`visible` or something) or by manually setting the style in JS. -3. Make sure the code is reusable! You should be able to create multiple dropdowns on a page without repeating the JavaScript code. -4. If you bundle your code into a module you can [publish it to npm](https://docs.npmjs.com/getting-started/publishing-npm-packages) and then install and use it anytime you like! Nothing like publishing your own modules to make you feel like a pro 😎. +2. You should hard-code the menu items into your HTML but hide/reveal them using JavaScript. You can do this either by adding a class (`visible` or something) or by manually setting the style in JS. +3. Make sure the code is reusable! You should be able to create multiple drop-downs on a page without repeating the JavaScript code. +4. If you bundle your code into a module you can [publish it to npm](https://docs.npmjs.com/getting-started/publishing-npm-packages) and then install and use it anytime you like! Nothing like publishing your own modules to make you feel like a pro 😎. ### Mobile menus -Mobile versions of your sites are almost definitely going to need their own menu implementation. Depending on how you decided to implement your dropdown, you _could_ reuse it here, but there are tons of more inventive options out there. +Mobile versions of your sites are almost definitely going to need their own menu implementation. Depending on how you decided to implement your drop-down, you _could_ reuse it here, but there are tons of more inventive options out there. 1. [Browse the web](https://dribbble.com/search?q=mobile+menu) for [some](http://trydevkit.com/blog-post/steal-these-responsive-navigation-menu-ideas/bc8bec8d-ef4e-60bc-456c-525ed6f88db8) [inspiration](https://medium.com/@kollinz/hamburger-menu-alternatives-for-mobile-navigation-a3a3beb555b8), pick something and try to implement it! ### Image slider -Again, there's not much instruction needed here - just practice. +Again, there's not much instruction needed here - just practice.   -Create a simple image carousel. It should contain arrows on each side to advance the image forward or backwards. It should automatically move forward every 5 seconds. It should contain the little navigation circles at the bottom that indicate which slide you are on (and they should be click-able to advance to that particular slide). +Create a simple image carousel. It should contain arrows on each side to advance the image forward or backward. It should automatically move forward every 5 seconds. It should contain the little navigation circles at the bottom that indicate which slide you are on (and they should be click-able to advance to that particular slide). Don't spend too much time worrying about getting your images to display at the correct size -- it's more important to get the slider sliding. -1. This one is a little more involved than the last two, so think about how you would set up the different elements within the site. -2. Set up a very wide div which will contain the individual "slides" of each image. By appropriately positioning that div inside a container div (which acts like a picture frame), you can choose which slide is visible at any given time. -3. Once you have the slider positioned properly, build functions for "next" and "previous" which will advance to the next or previous slide accordingly. Make the transitions smooth using simple effects. +1. This one is a little more involved than the last two, so think about how you would set up the different elements within the site.   +2. Set up a very wide div which will contain the individual "slides" of each image. By appropriately positioning that div inside a container div (which acts like a picture frame), you can choose which slide is visible at any given time. +3. Once you have the slider positioned properly, build functions for "next" and "previous" which will advance to the next or previous slide accordingly. Make the transitions smooth using simple effects. 4. Set up arrow buttons which activate those functions and play with cycling through the images. -5. Add in some navigation dots at the bottom of the slides. Make a horizontal series of empty circles with CSS immediately below the slideshow. Each circle represents a slide, so whenever a new slide is activated, its corresponding circle gets filled in so you can tell where in the show you are. Make each circle link to that particular slide, so you can click on the circle and it will jump to that slide. +5. Add in some navigation dots at the bottom of the slides. Make a horizontal series of empty circles with CSS immediately below the slideshow. Each circle represents a slide, so whenever a new slide is activated, its corresponding circle gets filled in so you can tell where in the show you are. Make each circle link to that particular slide, so you can click on the circle and it will jump to that slide. 6. Add a timeout which advances the slides every 5 seconds. 7. Play around with your slideshow! diff --git a/js-in-the-real-world/webpack-2.md b/js-in-the-real-world/webpack-2.md index 5286fd72..8bea177f 100644 --- a/js-in-the-real-world/webpack-2.md +++ b/js-in-the-real-world/webpack-2.md @@ -1,9 +1,9 @@ -We've already introduced webpack in a previous lesson. It is the go-to tool across the web for bundling and compiling javascript code. There _are_ other options out there, but at this time none of them are as popular or widely used as webpack. +We've already introduced webpack in a previous lesson. It is the go-to tool across the web for bundling and compiling javascript code. There _are_ other options out there, but at this time none of them are as popular or widely used as webpack. -In our last lesson we only covered the first half of what webpack can do for you - bundling your modules. Another amazing feature is it's ability to process and manipulate your code during the compilation step. So, if you would like to you [Sass](http://sass-lang.com/) to write your CSS, webpack can compile that for you. Webpack can manage your images and compress and optimize them for use on the web. Webpack can minify and uglify your code. In this lesson we're going to complete the webpack puzzle by learning about loaders and plugins. +In our last lesson we only covered the first half of what webpack can do for you - bundling your modules. Another amazing feature is its ability to process and manipulate your code during the compilation step. So, if you would like to you [Sass](http://sass-lang.com/) to write your CSS, webpack can compile that for you. Webpack can manage your images and compress and optimize them for use on the web. Webpack can minify and uglify your code. In this lesson, we're going to complete the webpack puzzle by learning about loaders and plugins. -1. Go through the "Core Concepts" lessons at [Webpack Academy](https://webpack.academy/p/the-core-concepts). It starts off with the concepts we've already learned, but do the whole thing. Review is valuable, and this presenter explains things very clearly. Make sure you take note of the `--watch` feature! +1. Go through the "Core Concepts" lessons at [Webpack Academy](https://webpack.academy/p/the-core-concepts). It starts off with the concepts we've already learned, but do the whole thing. Review is valuable, and this presenter explains things very clearly. Make sure you take note of the `--watch` feature! 2. Go through [this tutorial](https://webpack.js.org/guides/asset-management/) to see examples of using webpack to manage your website's assets. 3. Finally, do [this tutorial](https://webpack.js.org/guides/output-management/) to learn how to let webpack manually manage your index.html and insert your bundle into the code for you! -4. You don't need to do the rest of the webpack tutorials at this time, but take a look at what's offered on the sidebar of their [guides page](https://webpack.js.org/guides/). There are several sweet features that you might want to use in future projects such as code-splitting, lazy-loading and tree-shaking. Now that you have a handle on webpack's configuration system adding these features is as easy as using the right plugins and loaders!. +4. You don't need to do the rest of the webpack tutorials at this time, but take a look at what's offered on the sidebar of their [guides page](https://webpack.js.org/guides/). There are several sweet features that you might want to use in future projects such as code-splitting, lazy-loading, and tree-shaking. Now that you have a handle on webpack's configuration system adding these features is as easy as using the right plugins and loaders!. diff --git a/main-course-introduction/introduction.md b/main-course-introduction/introduction.md index ddac1e12..efe06881 100644 --- a/main-course-introduction/introduction.md +++ b/main-course-introduction/introduction.md @@ -1,17 +1,17 @@ ### Introduction -Javascript is the future of the web. More and more of the logic is making its way to the client side in order to facilitate lightning fast user experiences. Javascript is even moving to the server side with Node.js. That's why in this course we'll be diving deep into it to make sure you come out with a good understanding of how it works. +JavaScript is the future of the web. More and more of the logic is making its way to the client side in order to facilitate lightning fast user experiences. Javascript is even moving to the server side with Node.js. That's why in this course we'll be diving deep into it to make sure you come out with a good understanding of how it works. -You've already completed the [Web Development 101 course](/courses/web-development-101/#section-the-front-end), right? Good, because now we'll be moving at warp speed into new frontiers. This section will cover a lot of ground and your brain may melt down a few times, but don't worry, that's just a flesh wound. Patch 'er up and keep going! When in doubt, build something. +You've already completed the [Web Development 101 course](/courses/web-development-101/#section-the-front-end), right? Good, because now we'll be moving at warp speed into new frontiers. This section will cover a lot of ground and your brain may meltdown a few times, but don't worry, that's just a flesh wound. Patch 'er up and keep going! When in doubt, build something. ### The Path -So how is this course set up? It starts with a deeper look at the basics, just like the [Ruby Programming course](/courses/ruby-programming) did with Ruby. You don't need to have completed the Ruby Programming course or [the Ruby on Rails course](/courses/ruby-on-rails) to understand these basics but we won't be focusing deeply on the really basic coding items so it'll move quickly. You should, however, already have completed the [Web Development 101 course](/courses/web-development-101), specifically the [Front End Section](/courses/web-development-101#section-the-front-end) before starting this course. +So how is this course set up? It starts with a deeper look at the basics, just like the [Ruby Programming course](/courses/ruby-programming) did with Ruby. You don't need to have completed the Ruby Programming course or [the Ruby on Rails course](/courses/ruby-on-rails) to understand these basics but we won't be focusing deeply on the really basic coding items so it'll move quickly. You should, however, already have completed the [Web Development 101 course](/courses/web-development-101), specifically the [Front End Section](/courses/web-development-101#section-the-front-end) before starting this course.   -The last thing you'll do is a final project which integrates everything you've learned in all the courses of this curriculum. This is the kind of project that you'll be telling employers all about and a great chance to prove that you're now, officially, a serious web developer. +The last thing you'll do is a final project which integrates everything you've learned in all the courses of this curriculum. This is the kind of project that you'll be telling employers all about and a great chance to prove that you're now, officially, a serious web developer.   ### Format -There's a lot to cover but it's been broken up into bite-sized lessons and their accompanying projects. The projects will give you a chance to apply what you've learned and to show what you're capable of. After a few of them, you'll really start getting the hang of things. +There's a lot to cover, but it's been broken up into bite-sized lessons and their accompanying projects. The projects will give you a chance to apply what you've learned and to show what you're capable of. After a few of them, you'll really start getting the hang of things.   ### In each lesson: diff --git a/organizing-js/classes.md b/organizing-js/classes.md index d72c1ad5..2e4385ca 100644 --- a/organizing-js/classes.md +++ b/organizing-js/classes.md @@ -1,16 +1,16 @@ ### Introduction -JavaScript does _not_ have classes in the same sense as other Object Oriented languages like Java or Ruby. ES6, however, _did_ introduce a syntax for object creation that uses the `class` keyword. It is basically a new syntax that does the _exact_ same thing as the object constructors and prototypes we learned about in the constructor lesson. +JavaScript does _not_ have classes in the same sense as other Object Oriented languages like Java or Ruby. ES6, however, _did_ introduce a syntax for object creation that uses the `class` keyword. It is basically a new syntax that does the _exact_ same thing as the object constructors and prototypes we learned about in the constructor lesson. -There is a little bit of controversy about using the class syntax however. Opponents argue that `class` is basically just _syntactic sugar_ over the existing prototype-based constructors and that it's dangerous and/or misleading to obscure what's _really_ going on with these objects. Despite the controversy, classes are beginning to crop up in real codebases that you are almost certainly going to encounter such as frameworks like React. +There is a bit of controversy about using the class syntax, however. Opponents argue that `class` is basically just _syntactic sugar_ over the existing prototype-based constructors and that it's dangerous and/or misleading to obscure what's _really_ going on with these objects. Despite the controversy, classes are beginning to crop up in real code bases that you are almost certainly going to encounter such as frameworks like React. -Since we've already gone fairly in depth with Constructors you don't have too much left to learn here beyond the new syntax. If you choose to use classes in your code (that's fine!) you can use them much the same way as object constructors. +Since we've already gone fairly in-depth with Constructors, you don't have too much left to learn here beyond the new syntax. If you choose to use classes in your code (that's fine!) you can use them much the same way as object constructors. ### Assignment
-1. Browse [this git repo](https://github.com/joshburgess/not-awesome-es6-classes) for the arguments _against_ using classes. The 'TL;DR' section is probably enough unless you really feel like diving down the rabbit-hole. __WE__ are not saying that classes are bad! We just wanted to point out that many people do. Those people generally recommend patterns like the Factory Functions we learned about in the previous lesson. [This article](https://medium.com/@rajaraodv/is-class-in-es6-the-new-bad-part-6c4e6fe1ee65) is a little more "bipartisan". -2. [This article](https://javascript.info/class) is probably just about all you need to start using `class` syntax confidently. "Getters and Setters" are a useful feature! -3. [The MDN docs](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes) are, as usual, a great resource for going a little deeper. Look especially at the 'extends' and 'Mixins' sections. React (and other frameworks) uses classes in this way. You create your components and make them `extend` the core React component which gives you access to all their built-in functionality. +1. Browse [this git repo](https://github.com/joshburgess/not-awesome-es6-classes) for the arguments _against_ using classes. The 'TL;DR' section is probably enough unless you really feel like diving down the rabbit-hole. __WE__ are not saying that classes are bad! We just wanted to point out that many people do. Those people generally recommend patterns like the Factory Functions we learned about in the previous lesson. [This article](https://medium.com/@rajaraodv/is-class-in-es6-the-new-bad-part-6c4e6fe1ee65) is a little more "bipartisan". +2. [This article](https://javascript.info/class) is probably just about all you need to start using `class` syntax confidently. "Getters and Setters" are a useful feature! +3. [The MDN docs](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes) are, as usual, a great resource for going a little deeper. Look especially at the 'extends' and 'Mixins' sections. React (and other frameworks) uses classes in this way. You create your components and make them `extend` the core React component which gives you access to all their built-in functionality.
### Practice diff --git a/organizing-js/es6-modules.md b/organizing-js/es6-modules.md index 43e43464..87f4fa1c 100644 --- a/organizing-js/es6-modules.md +++ b/organizing-js/es6-modules.md @@ -1,18 +1,18 @@ ### Introduction -Separate from the __module pattern__ that we discussed in an earlier lesson, "modules" is a feature that arrived with ES6. Browser support for this feature is quite slim at this point, but is slowly improving and until all modern browsers support it, we can make it work using an external module bundler. ES6 modules are starting to appear in many codebases around the net and getting them up and running will give us a chance to explore some new parts of the JavaScript ecosystem, so it's going to be a worthy excursion! +Separate from the __module pattern__ that we discussed in an earlier lesson, "modules" is a feature that arrived with ES6. Browser support for this feature is quite slim at this point, but is slowly improving and until all modern browsers support it, we can make it work using an external module bundler. ES6 modules are starting to appear in many code bases around the net and getting them up and running will give us a chance to explore some new parts of the JavaScript ecosystem, so it's going to be a worthy excursion! -Don't be fooled! We're going to cover much more than just the new module syntax in this lesson! Before we can really _use_ these modules we're going to have to learn about __npm__ and __webpack__ which are both topics that will be _very_ useful to you even beyond this lesson. In the end the modules themselves are simple to implement, so we're going to take this chance to learn about a few other things. +Don't be fooled! We're going to cover much more than just the new module syntax in this lesson! Before we can really _use_ these modules, we're going to have to learn about __npm__ and __webpack__ which are both topics that will be _very_ useful to you even beyond this lesson. In the end, the modules themselves are simple to implement, so we're going to take this chance to learn about a few other things. -### first things first +### The History of JavaScript -Why do we even need or want this stuff? What do you gain from all of this added complexity? These are good questions.. with good answers. +Why do we even need or want this stuff? What do you gain from all of this added complexity? These are good questions.. with good answers. -- Read [this article](https://medium.com/the-node-js-collection/modern-javascript-explained-for-dinosaurs-f695e9747b70) for a bit of a history lesson. It's long, but it puts what we're doing here in great perspective. You don't _have_ to code along with the examples - the tutorials we cover later will go through basically the same process. But it's good practice and going through the same process multiple times will help it stick faster. +- Read [this article](https://medium.com/the-node-js-collection/modern-javascript-explained-for-dinosaurs-f695e9747b70) for a bit of a history lesson. It's long, but it puts what we're doing here in great perspective. You don't _have_ to code along with the examples - the tutorials we cover later will go through basically the same process. But it's good practice and going through the same process multiple times will help it stick faster. - Seriously.. spend some time with that article - it really clarifies the 'WHY' of the rest of this lesson. ### npm -The __node package manager__ is a command line tool that gives you access to a gigantic repository of plugins, libraries and tools. If you have done our Fundamentals course, you will likely have encountered it when you installed the Jasmine testing framework to do our exercises. +The __node package manager__ is a command line tool that gives you access to a gigantic repository of plugins, libraries and tools. If you have done our Fundamentals course, you will probably have encountered it when you installed the Jasmine testing framework to do our exercises. 1. Take a couple minutes to watch [this video](https://docs.npmjs.com/getting-started/what-is-npm) - a great introduction to npm. 2. [This video](https://docs.npmjs.com/getting-started/installing-npm-packages-locally) teaches you how to install packages with npm. @@ -21,31 +21,31 @@ The __node package manager__ is a command line tool that gives you access to a g ### Yarn? -At some point you will probably run into [Yarn](https://yarnpkg.com/en/) - a replacement for the default `npm`. For the most part it does the same things, though it _does_ have a few more features. Recent versions of `npm` have incorporated some of the best features of Yarn, so using it won't offer you any real advantages at this point in your career. It _is_ a fine project, however, and may be worth your consideration in the future. +At some point, you will probably run into [Yarn](https://yarnpkg.com/en/) - a replacement for the default `npm`. For the most part, it does the same things though it _does_ have a few more features. Recent versions of `npm` have incorporated some of the best features of Yarn, so using it won't offer you any real advantages at this point in your career. It _is_ a fine project, however, and may be worth your consideration in the future. -### webpack +### Webpack -Webpack is simply a tool for bundling modules. There is a lot of talk across the net about how difficult and complex it is to set up and use, but at the moment our needs are few and the setup is simple enough. In fact, you can see an example of getting it up and running on the front page of [their website](https://webpack.js.org/). +Webpack is simply a tool for bundling modules. There is a lot of talk across the net about how difficult and complex it is to set up and use, but at the moment our needs are few and the setup is simple enough. In fact, you can see an example of getting it up and running on the front page of [their website](https://webpack.js.org/). -Webpack _is_ a very powerful tool, and with that power comes a decent amount of complexity - just look at the sample config file on [this page](https://webpack.js.org/configuration/) 😱. Don't let it scare you off! The basic configuration is not difficult and proficiency with webpack looks _amazing_ on resumes. +Webpack _is_ a very powerful tool, and with that power comes a decent amount of complexity - just look at the sample config file on [this page](https://webpack.js.org/configuration/) 😱. Don't let it scare you off! The basic configuration is not difficult and proficiency with webpack looks _amazing_ on resumes. To get us started we are going to refer to the official documentation. 1. Code along with the first four steps of [this tutorial](https://webpack.js.org/guides/getting-started/) ("Basic Setup" through "Using a Configuration") -Lets discuss what's going on there. After installing webpack using npm we set up a simple project that required an external library (lodash - check it out [here](https://lodash.com/) if it's new to you) using a simple `script` tag. The site lists a few reasons why this is probably _not_ ideal and then steps through using webpack to accomplish the same thing. +Let's discuss what's going on there. After installing webpack using npm we set up a simple project that required an external library (lodash - check it out [here](https://lodash.com/) if it's new to you) using a simple `script` tag. The site lists a few reasons why this is probably _not_ ideal and then steps through using webpack to accomplish the same thing. -There are a couple of key concepts to understanding how webpack works - __entry__ and __output__. In this example, we rearranged the files into a `src` and `dist` folder. Technically we could have called those folders anything, but those names are typical. `src` is our _source_ directory. In other words, `src` is where we write all of the code that webpack is going to bundle up for us. When webpack runs, it goes through all of our files looking for any `import` statements and then compiles _all_ of the code we need to run our site into a single file inside of the `dist` folder (short for _distrubution_). Our __entry__ file, then is the main application file that links (either directly or indirectly) to all of the other modules in our project. In this example it is `/src/index.js`. The __output__ file is the compiled version - `dist/bundle.js`. +There are a couple of key concepts to understanding how webpack works - __entry__ and __output__. In this example, we rearranged the files into a `src` and `dist` folder. Technically we could have called those folders anything, but those names are typical. `src` is our _source_ directory. In other words, `src` is where we write all of the code that webpack is going to bundle up for us. When webpack runs, it goes through all of our files looking for any `import` statements and then compiles _all_ of the code we need to run our site into a single file inside of the `dist` folder (short for _distrubution_). Our __entry__ file, then is the main application file that links (either directly or indirectly) to all of the other modules in our project. In this example, it is `/src/index.js`. The __output__ file is the compiled version - `dist/bundle.js`. -- browse [this document](https://webpack.js.org/concepts/) for more details. We'll talk plugins and loaders in another lesson. +- browse [this document](https://webpack.js.org/concepts/) for more details. We'll talk plugins and loaders in another lesson. ### ES6 Modules (finally!) -Now that we (sorta) understand what webpack is doing it's time to discuss the module syntax. There are only 2 components to it - __import__ and __export__. +Now that we (sorta) understand what webpack is doing it's time to discuss the module syntax. There are only 2 components to it - __import__ and __export__. - Take a moment to look at the docs for [import](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import) and [export](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/export). -Of course, the import statement is the same thing that you used during the webpack tutorial! These things are simple to use. +Of course, the import statement is the same thing that you used during the webpack tutorial! These things are simple to use. ~~~javascript // a file called functionOne.js @@ -61,11 +61,11 @@ import functionOne from './functionOne' functionOne() //this should work as expected! ~~~ -There are _many_ benefits to writing your code in modules. One of the most compelling is code reuse. If, for instance, you have written some functions that manipulate the DOM in a specific way, putting all of those into their own file as a 'module' means that you can copy that file and re-use it very easily! +There are _many_ benefits to writing your code in modules. One of the most compelling is code reuse. If, for instance, you have written some functions that manipulate the DOM in a specific way, putting all of those into their own file as a 'module' means that you can copy that file and re-use it very easily! -Other benefits include all of the benefits to wrapping your code in factory functions or using the module pattern (the module pattern and es6 modules are not the same thing.. this naming convention is frustrating). By using es6 modules you can keep different parts your code cleanly separated, which makes writing and maintaining your code much easier and less error prone. Keep in mind that you can _definitely_ export constructors, classes and factory functions from your modules. +Other benefits include all of the benefits to wrapping your code in factory functions or using the module pattern (the module pattern and ES6 modules are not the same things.. this naming convention is frustrating). By using ES6 modules you can keep different parts your code cleanly separated, which makes writing and maintaining your code much easier and less error-prone. Keep in mind that you can _definitely_ export constructors, classes and factory functions from your modules. -To pull it all together, let's write a simple module and then include it in our code. We are going to continue from where the webpack tutorial left off. Before beginning your file directory should look something like this: +To pull it all together, let's write a simple module and then include it in our code. We are going to continue from where the webpack tutorial left off. Before beginning your file directory should look something like this: ~~~ ├── dist @@ -95,28 +95,28 @@ and then in `src/index.js` import and use your new function. import myName from './myName'; function component() { - var element = document.createElement('div'); +  var element = document.createElement('div'); - // use your function! - element.innerHTML = myName('Cody'); - return element; +  // use your function! +  element.innerHTML = myName('Cody'); +  return element; } - document.body.appendChild(component()); +  document.body.appendChild(component()); ~~~ -Easy! Now, if you run `webpack` in your project directory your page should show our new function being used. +Easy! Now, if you run `webpack` in your project directory your page should show our new function being used. -There are 2 different ways to use exports in your code - named exports and default exports. Which option you use depends on what you're exporting. As a general rule if you want to export multiple functions use named exports with this pattern: +There are 2 different ways to use exports in your code: named exports and default exports. Which option you use depends on what you're exporting. As a general rule if you want to export multiple functions use named exports with this pattern: ~~~javascript const functionOne = () => 'ONE' const functionTwo = () => 'TWO' export { - functionOne, - functionTwo + functionOne, +   functionTwo } ~~~ diff --git a/organizing-js/factory-functions.md b/organizing-js/factory-functions.md index 71705b3d..af6ced42 100644 --- a/organizing-js/factory-functions.md +++ b/organizing-js/factory-functions.md @@ -1,23 +1,23 @@ -### What's wrong with constructors +### What's wrong with constructors? -Object constructors are one of about a million ways to start organizing your code. They are fairly common in the wild and are a fundamental building block of the JavaScript language. +Object constructors are one of about a million ways to start organizing your code. They are fairly common in the wild and are a fundamental building block of the JavaScript language. _However..._ -There are many people who argue _against_ using constructors at all. Their arguments boil down to the fact that if you aren't careful, it can be easy to introduce bugs into your code when using constructors. [This](https://tsherif.wordpress.com/2013/08/04/constructors-are-bad-for-javascript/) article does a pretty decent job of outlining the issues. (spoiler alert: the author ends up recommending Factory Functions) +There are many people who argue _against_ using constructors at all. Their arguments boil down to the fact that if you aren't careful, it can be easy to introduce bugs into your code when using constructors. [This](https://tsherif.wordpress.com/2013/08/04/constructors-are-bad-for-javascript/) article does a pretty decent job of outlining the issues. (spoiler alert: the author ends up recommending Factory Functions) -One of the biggest issues with constructors is that while they _look_ just like regular functions, they do not behave like regular functions at all. If you try to use a constructor function without the `new` keyword, your program will not work as expected, but it won't produce error messages that are easy to trace. +One of the biggest issues with constructors is that while they _look_ just like regular functions, they do not behave like regular functions at all. If you try to use a constructor function without the `new` keyword, your program will not work as expected, but it won't produce error messages that are easy to trace. -The main takeaway is that while constructors aren't necessarily _evil_, but they aren't the only way and they may not be the best way either. Of course this doesn't mean that time learning about them was wasted! They are a common pattern in real-world code and many tutorials that you'll come across on the net. +The main takeaway is that while constructors aren't necessarily _evil_, but they aren't the only way and they may not be the best way either. Of course, this doesn't mean that time learning about them was wasted! They are a common pattern in real-world code and many tutorials that you'll come across on the net. ### Factory Function introduction -The factory function pattern is similar to constructors, but instead of using `new` to create an object, factory functions simply set up and return the new object when you call the function. Check out this example. +The factory function pattern is similar to constructors, but instead of using `new` to create an object, factory functions simply set up and return the new object when you call the function. Check out this example. ~~~javascript const personFactory = (name, age) => { - const sayHello = () => console.log('hello!'); - return { name, age, sayHello }; +  const sayHello = () => console.log('hello!'); +  return { name, age, sayHello }; }; const jeff = personFactory('jeff', 27); @@ -31,9 +31,9 @@ for reference, here is the same thing created using the Constructor pattern: ~~~javascript const Person = function(name, age) { - this.sayHello = () => console.log('hello!'); - this.name = name; - this.age = age; +  this.sayHello = () => console.log('hello!'); +  this.name = name; +  this.age = age; }; const jeff = new Person('jeff', 27); @@ -41,7 +41,7 @@ const jeff = new Person('jeff', 27); #### Object Shorthand -A quick note about line 3 from the factory function example. In 2015 a handy new shorthand for creating objects was added into JavaScript. Without the shorthand line 3 would have looked something like this: +A quick note about line 3 from the factory function example. In 2015 a handy new shorthand for creating objects was added into JavaScript. Without the shorthand line 3 would have looked something like this: ~~~javascript return {name: name, age: age, sayHello: sayHello} @@ -68,14 +68,14 @@ console.log(name, color, number, food) // Maynard red 34 rice // if you simply turn them into an object with brackets, // the output is much easier to decipher: console.log({name, color, number, food}) - // { name: 'Maynard', color: 'red', number: 34, food: 'rice' } + // { name: 'Maynard', color: 'red', number: 34, food: 'rice' } ~~~ ### Scope and Closure From simply reading the above example you are probably already in pretty good shape to start using factory functions in your code, but before we get there it's time to do a somewhat deep dive into an incredibly important concept: __closure__. -Before we're able to make sense of closure we need to make sure you have a _really_ good grasp on __scope__ in JavaScript. Scope is the term that refers to where things like variables and functions can be used in your code. +Before we're able to make sense of closure we need to make sure you have a _really_ good grasp on __scope__ in JavaScript. Scope is the term that refers to where things like variables and functions can be used in your code.   In the following example, do you know what will be logged on the last line? @@ -83,7 +83,7 @@ In the following example, do you know what will be logged on the last line? let a = 17; const func = x => { - let a = x; +  let a = x; }; func(99); @@ -91,19 +91,19 @@ func(99); console.log(a); // ??????? ~~~ -Is it 17 or 99? Do you know why? Can you edit the code so that it prints the other value? +Is it 17 or 99? Do you know why? Can you edit the code so that it prints the other value? -The answer is 17, and the reason it's not 99 is that on line 4, the outer variable `a` is not redefined, rather a _new_ `a` is created inside the scope of that function. In the end figuring out scope in most contexts is not all that complicated, but it is _crucial_ to understanding some of the more advanced concepts that are coming up soon, so take your time to understand what's going on in the following resources. +The answer is 17, and the reason it's not 99 is that on line 4, the outer variable `a` is not redefined, rather a _new_ `a` is created inside the scope of that function. In the end, figuring out scope in most contexts is not all that complicated, but it is _crucial_ to understanding some of the more advanced concepts that are coming up soon, so take your time to understand what's going on in the following resources. -1. [This video](https://www.youtube.com/watch?v=SBwoFkRjZvE) is simple and clear! Start here. +1. [This video](https://www.youtube.com/watch?v=SBwoFkRjZvE) is simple and clear! Start here. -2. [This article](https://toddmotto.com/everything-you-wanted-to-know-about-javascript-scope/) starts simple and reiterates what the video covered, but goes deeper and is more specific about the appropriate terminology. At the end he defines __closure__ _and_ describes the __module__ pattern, both of which we'll talk about more soon. +2. [This article](https://toddmotto.com/everything-you-wanted-to-know-about-javascript-scope/) starts simple and reiterates what the video covered, but goes deeper and is more specific about the appropriate terminology. At the end, he defines __closure__ _and_ describes the __module__ pattern, both of which we'll talk about more soon. 3. The previous article is great, but there is one inaccurate statement: - > All scopes in JavaScript are created with `Function Scope` *only*, they aren’t created by `for` or `while` loops or expression statements like `if` or `switch`. New functions = new scope - that’s the rule +   > All scopes in JavaScript are created with `Function Scope` *only*, they aren’t created by `for` or `while` loops or expression statements like `if` or `switch`. New functions = new scope - that’s the rule - that statement _was_ true in 2013 when the article was written, but ES6 has rendered it incorrect. Read [this](http://wesbos.com/javascript-scoping/) article to get the scoop! +   that statement _was_ true in 2013 when the article was written, but ES6 has rendered it incorrect. Read [this](http://wesbos.com/javascript-scoping/) article to get the scoop! ### Private Variables and Functions @@ -111,9 +111,9 @@ Now that we've cemented your knowledge of scope in JavaScript take a look at thi ~~~javascript const FactoryFunction = string => { - const capitalizeString = () => string.toUpperCase(); - const printString = () => console.log(`----${capitalizeString()}----`); - return { printString }; +  const capitalizeString = () => string.toUpperCase(); +  const printString = () => console.log(`----${capitalizeString()}----`); +  return { printString }; }; const taco = FactoryFunction('taco'); @@ -124,19 +124,19 @@ taco.capitalizeString(); // ERROR!! taco.printString(); // this prints "----TACO----" ~~~ -Because of the concept of scope neither of the functions created inside of `FactoryFunction` can be accessed outside of the function itself, which is why lines 9 and 10 above fail. The only way to use either of those functions is to `return` them in the object (see line 4), which is why we can call `taco.printString()` but _not_ `taco.capitalizeString()`. The big deal here is that even though _we_ can't access the `capitalizeString()` function, `printString()` can. That is closure. +Because of the concept of scope, neither of the functions created inside of `FactoryFunction` can be accessed outside of the function itself, which is why lines 9 and 10 above fail. The only way to use either of those functions is to `return` them in the object (see line 4), which is why we can call `taco.printString()` but _not_ `taco.capitalizeString()`. The big deal here is that even though _we_ can't access the `capitalizeString()` function, `printString()` can. That is closure. -The concept of closure is the idea that functions retain their scope even if they are passed around and called outside of that scope. In this case `printString` has access to everything inside of `FactoryFunction`, even if it gets called outside of that function. +The concept of closure is the idea that functions retain their scope even if they are passed around and called outside of that scope. In this case, `printString` has access to everything inside of `FactoryFunction`, even if it gets called outside of that function. Here's another example: ~~~javascript const counterCreator = () => { - let count = 0; - return () => { - console.log(count); - count++; - }; +  let count = 0; +  return () => { +    console.log(count); +    count++; +  }; }; const counter = counterCreator(); @@ -147,37 +147,37 @@ counter(); // 2 counter(); // 3 ~~~ -In this example `counterCreator` initializes a local variable (`count`) and then returns a function. To use that function we have to assign it to a variable (line 9). Then, every time we run the function it `console.log`s `count` and increments it. As above, the function `counter` is a closure. It has access to the variable `count` and can both print and increment it, but there is no other way for our program to access that variable. +In this example, `counterCreator` initializes a local variable (`count`) and then returns a function. To use that function we have to assign it to a variable (line 9). Then, every time we run the function it `console.log`s `count` and increments it. As above, the function `counter` is a closure. It has access to the variable `count` and can both print and increment it, but there is no other way for our program to access that variable. -In the context of Factory Functions, closures allow us to create __private__ variables and functions. Private functions are functions that are used in the workings of our objects that are not intended to be used elsewhere in our program. In other words, even though our objects might only do one or two things, we are free to split our functions up as much as we want (allowing for cleaner, easier to read code) and only export the functions that the rest of the program is going to use. Using this terminology with our `printString` example from earlier, `capitalizeString` is a private function and `printString` is public. +In the context of Factory Functions, closures allow us to create __private__ variables and functions. Private functions are functions that are used in the workings of our objects that are not intended to be used elsewhere in our program. In other words, even though our objects might only do one or two things, we are free to split our functions up as much as we want (allowing for cleaner, easier to read code) and only export the functions that the rest of the program is going to use. Using this terminology with our `printString` example from earlier, `capitalizeString` is a private function and `printString` is public. The concept of private functions is very useful and should be used as often as is possible! For every bit of functionality that you need for your program, there are likely to be several supporting functions that do NOT need to be used in your program as a whole. Tucking these away and making them inaccessible makes your code easier to refactor, easier to test and easier to reason about for you and anyone else that wants to use your objects. ### Back to Factory Functions -Now that we've got the theory out of the way, let's return to factory functions. Factories are simply plain old JavaScript functions that return objects for us to use in our code. Using factories is a powerful way to organize and contain the code you're writing. For example, if we're writing any sort of game, we're probably going to want objects to describe our players and encapsulate all of the things our players can do (functions!) +Now that we've got the theory out of the way, let's return to factory functions. Factories are simply plain old JavaScript functions that return objects for us to use in our code. Using factories is a powerful way to organize and contain the code you're writing. For example, if we're writing any sort of game, we're probably going to want objects to describe our players and encapsulate all of the things our players can do (functions!) ~~~javascript const Player = (name, level) => { - let health = level * 2; - const die = () => { - // uh oh - }; - const damage = x => { - health -= x; - if (health <= 0) { - die(); - } - }; - const attack = enemy => { - if (level < enemy.level) { - damage(1); - } - if (level > enemy.level) { - enemy.damage(1); - } - }; - return {attack} +  let health = level * 2; +  const die = () => { +    // uh oh +  }; +  const damage = x => { +    health -= x; +    if (health <= 0) { +      die(); +    } +  }; +  const attack = enemy => { +    if (level < enemy.level) { +      damage(1); +    } +    if (level > enemy.level) { +      enemy.damage(1); +    } +  }; +  return {attack} }; const jimmie = Player('jim', 1); @@ -186,23 +186,23 @@ jimmie.attack(badGuy); Take a minute to look through this simplistic example and see if you can figure out what's going on. -What would happen here if we tried to call `jimmie.die()`? What if we tried to manipulate the health: `jimmie.health -= 1000`? Of course, those are things that we have NOT exposed publicly so we would get an error. This is a very good thing! Setting up objects like this makes it easier for us to use them because we've actually put some thought into how and when we are going to want to use the information. In this case, we have jimmie's health hiding as a private variable inside of the object which means we need to export a function if we want to manipulate it. In the long run this will make our code _much_ easier to reason about because all of the logic is encapsulated in an appropriate place. +What would happen here if we tried to call `jimmie.die()`? What if we tried to manipulate the health: `jimmie.health -= 1000`? Of course, those are things that we have NOT exposed publicly so we would get an error. This is a very good thing! Setting up objects like this makes it easier for us to use them because we've actually put some thought into how and when we are going to want to use the information. In this case, we have jimmie's health hiding as a private variable inside of the object which means we need to export a function if we want to manipulate it. In the long run, this will make our code _much_ easier to reason about because all of the logic is encapsulated in an appropriate place. #### Inheritance with Factories -In the constructors lesson we looked fairly deeply into the concept of Prototypes and Inheritance, or giving our objects access to the methods and properties of another Object. There are a few easy ways to accomplish this while using Factories. Check this one out: +In the constructors lesson, we looked fairly deeply into the concept of Prototypes and Inheritance, or giving our objects access to the methods and properties of another Object. There are a few easy ways to accomplish this while using Factories. Check this one out: ~~~javascript const Person = (name) => { - const sayName = () => console.log(`my name is ${name}`) - return {sayName} +  const sayName = () => console.log(`my name is ${name}`) +  return {sayName} } const Nerd = (name) => { - // simply create a person and pull out the sayName function! - const {sayName} = Person(name) - const doSomethingNerdy = () => console.log('nerd stuff') - return {sayName, doSomethingNerdy} +  // simply create a person and pull out the sayName function! +  const {sayName} = Person(name) +  const doSomethingNerdy = () => console.log('nerd stuff') +  return {sayName, doSomethingNerdy} } const jeff = Nerd('jeff') @@ -211,38 +211,38 @@ jeff.sayName() //my name is jeff jeff.doSomethingNerdy() // nerd stuff ~~~ -This pattern is _great_ because it allows you to pick and choose which functions you want to include in your new object. If you want to go ahead and lump ALL of another object in, you can certainly do that as well with `Object.assign` (read the docs for that one [here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign)). +This pattern is _great_ because it allows you to pick and choose which functions you want to include in your new object. If you want to go ahead and lump ALL of another object in, you can certainly do that as well with `Object.assign` (read the docs for that one [here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign)). ~~~javascript const Nerd = (name) => { - const prototype = Person(name) - const doSomethingNerdy = () => console.log('nerd stuff') - return Object.assign({}, prototype, {doSomethingNerdy}) +  const prototype = Person(name) +  const doSomethingNerdy = () => console.log('nerd stuff') +  return Object.assign({}, prototype, {doSomethingNerdy}) } ~~~ -- Before moving on have a look at [this](https://medium.com/javascript-scene/3-different-kinds-of-prototypal-inheritance-es6-edition-32d777fa16c9) article. In the second half of the article the author goes into some things that we aren't really talking too much about here, but you'll be rewarded if you spend some time figuring out what he's talking about. Good stuff! +- Before moving on have a look at [this](https://medium.com/javascript-scene/3-different-kinds-of-prototypal-inheritance-es6-edition-32d777fa16c9) article. In the second half of the article, the author goes into some things that we aren't really talking too much about here, but you'll be rewarded if you spend some time figuring out what he's talking about. Good stuff! ### The Module Pattern -> Quick sidenote: ES6 introduced a new feature in JavaScript called 'modules'. These are essentially a syntax for importing and exporting code between different JavaScript files. They're very powerful and we WILL be covering them later. They are _not_, however, what we're talking about here. +> Quick sidenote: ES6 introduced a new feature in JavaScript called 'modules'. These are essentially a syntax for importing and exporting code between different JavaScript files. They're very powerful and we WILL be covering them later. They are _not_, however, what we're talking about here. -Modules are actually very similar to Factory functions. The main difference is how they're created. +Modules are actually very similar to Factory functions. The main difference is how they're created. Meet a module: ~~~javascript const calculator = (() => { - const add = (a, b) => a + b; - const sub = (a, b) => a - b; - const mul = (a, b) => a * b; - const div = (a, b) => a / b; - return { - add, - sub, - mul, - div, - }; +  const add = (a, b) => a + b; +  const sub = (a, b) => a - b; +  const mul = (a, b) => a * b; +  const div = (a, b) => a / b; +  return { +    add, +    sub, +    mul, +    div, +  }; })(); calculator.add(3,5) // 8 @@ -250,10 +250,10 @@ calculator.sub(6,2) // 4 calculator.mul(14,5534) // 77476 ~~~ - The concepts are exactly the same as the factory function, however instead of creating a factory that we can use over and over again to create multiple objects, the Module pattern wraps the factory in an IIFE (Immediately Invoked Function Expression). + The concepts are exactly the same as the factory function, however, instead of creating a factory that we can use over and over again to create multiple objects, the Module pattern wraps the factory in an IIFE (Immediately Invoked Function Expression). - Read up about IIFE's in [this article](http://adripofjavascript.com/blog/drips/an-introduction-to-iffes-immediately-invoked-function-expressions.html). The concept is simple.. write a function, wrap it in parentheses and then immediately call the function by adding `()` to the end of it. -In our calculator example, the function inside the IIFE is a simple factory function like we defined before, but we can just go ahead and assign the object to the variable `calculator` since we aren't going to need to be making lots of calculators, we only need one. Just like the Factory example, we can have as many private functions and variables as we want, and they stay neatly organized, tucked away inside of our module, only exposing the functions we actually want to use in our program. +In our calculator example, the function inside the IIFE is a simple factory function like we defined before, but we can just go ahead and assign the object to the variable `calculator` since we aren't going to need to be making lots of calculators, we only need one. Just like the Factory example, we can have as many private functions and variables as we want, and they stay neatly organized, tucked away inside of our module, only exposing the functions we actually want to use in our program. -A useful side-effect of encapsulating the inner-workings of our programs into objects is __namespacing__. Namespacing is a technique that is used to avoid naming collisions in our programs. For example, it's easy to imagine scenarios where you could write multiple functions with the same name. In our calculator example, what if we had a function that added things to our HTML display, or a function that added numbers and operators to our stack as the users input them. It is conceivable that we would want to call all 3 of these functions `add` which, of course, would cause trouble in our program. If all of them were nicely encapsulated inside of an object then we would have no trouble: `calculator.add()`, `displayController.add()`, `operatorStack.add()`. +A useful side-effect of encapsulating the inner-workings of our programs into objects is __namespacing__. Namespacing is a technique that is used to avoid naming collisions in our programs. For example, it's easy to imagine scenarios where you could write multiple functions with the same name. In our calculator example, what if we had a function that added things to our HTML display or a function that added numbers and operators to our stack as the users input them. It is conceivable that we would want to call all 3 of these functions `add` which, of course, would cause trouble in our program. If all of them were nicely encapsulated inside of an object then we would have no trouble: `calculator.add()`, `displayController.add()`, `operatorStack.add()`. diff --git a/organizing-js/library-project.md b/organizing-js/library-project.md index cfb5c57e..1483c5db 100644 --- a/organizing-js/library-project.md +++ b/organizing-js/library-project.md @@ -9,30 +9,30 @@ Let's extend the 'Book' example from the previous lesson and turn it into a smal 1. If you haven't already, set up your project with skeleton HTML/CSS and JS files. 2. All of your book objects are going to be stored in a simple array, so add a function to the script (not the constructor) that can take user's input and store the new book objects into an array. Your code should look something like this: - ~~~javascript - let myLibrary = [] - - function Book() { - // the constructor... - } - - function addBookToLibrary() { - // do stuff here - } - ~~~ -3. Hook the array up to your HTML with a `render()` function that loops through the array and displays each book on the page. You can display them in some sort of table, or each on their own "card". It might help for now to manually add a few books to your array so you can see the display. -4. Add a "NEW BOOK" button that brings up a form allowing users to input the details for the new book: author, title, number of pages, whether or not it's been read and anything else you might want. +   ~~~javascript +   let myLibrary = [] + +   function Book() { +     // the constructor... +   } + +   function addBookToLibrary() { +     // do stuff here +   } +   ~~~ +3. Hook the array up to your HTML with a `render()` function that loops through the array and displays each book on the page. You can display them in some sort of table, or each on their own "card". It might help for now to manually add a few books to your array so you can see the display. +4. Add a "NEW BOOK" button that brings up a form allowing users to input the details for the new book: author, title, number of pages, whether it's been read and anything else you might want. 5. Add a button on each book's display to remove the book from the library. - 1. You will need to associate your DOM elements with the actual book objects in some way. One easy solution is giving them a data-attribute that corresponds to the index of the library array. +   1. You will need to associate your DOM elements with the actual book objects in some way. One easy solution is giving them a data-attribute that corresponds to the index of the library array. 6. Add a button on each book's display to change it's `read` status. - 1. To facilitate this you will want to create the function that toggles a book's `read` status on your `Book` prototype. +   1. To facilitate this you will want to create the function that toggles a book's `read` status on your `Book` prototype. 7. Optional -we haven't learned any techniques for actually storing our data anywhere, so when the user refreshes the page all of their books will disappear! If you want, you are capable of adding some persistence to this library app using one of the following techniques: - 1. localStorage ([docs here](https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API/Using_the_Web_Storage_API)) allows you to save data on the user's computer. The downside here is that the data is ONLY accessible on the computer that it was created on. Even so, it's pretty handy! Set up a function that saves the whole library array to localStorage every time a new book is created, and another function that looks for that array in localStorage when your app is first loaded. (make sure your app doesn't crash if the array isn't there!) - 2. Firebase ([check it out!](https://firebase.google.com/docs/?authuser=0)) is an online database that can be set up relatively easily, allowing you to save your data to a server in the cloud! Teaching you how to use it is beyond the scope of this tutorial, but it is almost definitely within your skillset. If you're interested, check out [this video](https://www.youtube.com/watch?v=noB98K6A0TY) to see what it's all about. +   1. localStorage ([docs here](https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API/Using_the_Web_Storage_API)) allows you to save data on the user's computer. The downside here is that the data is ONLY accessible on the computer that it was created on. Even so, it's pretty handy! Set up a function that saves the whole library array to localStorage every time a new book is created, and another function that looks for that array in localStorage when your app is first loaded. (make sure your app doesn't crash if the array isn't there!) +   2. Firebase ([check it out!](https://firebase.google.com/docs/?authuser=0)) is an online database that can be set up relatively easily, allowing you to save your data to a server in the cloud! Teaching you how to use it is beyond the scope of this tutorial, but it is almost definitely within your skill set. If you're interested, check out [this video](https://www.youtube.com/watch?v=noB98K6A0TY) to see what it's all about.
### Student Solutions -Send us your solution so we can show others! Submit a link below to this [file](https://github.com/TheOdinProject/javascript_curriculum/blob/master/organizing-js/library-project.md) in the Javascript Curriculum Github repo with your files in it by using any of the methods listed on the [contributing page](http://github.com/TheOdinProject/curriculum/blob/master/contributing.md). See the [Google Homepage project](/courses/web-development-101/lessons/html-css) for examples. +Send us your solution so we can show others! Submit a link below to this [file](https://github.com/TheOdinProject/javascript_curriculum/blob/master/organizing-js/library-project.md) in the Javascript Curriculum Github repo with your files in it by using any of the methods listed on the [contributing page](http://github.com/TheOdinProject/curriculum/blob/master/contributing.md). See the [Google Homepage project](/courses/web-development-101/lessons/html-css) for examples. - Add your solution below this line! - [theghall's solution](https://github.com/theghall/odin-library) - [View in Browser](https://theghall.github.io/odin-library/) diff --git a/organizing-js/objects-constructors.md b/organizing-js/objects-constructors.md index 4f13e444..b5c4520b 100644 --- a/organizing-js/objects-constructors.md +++ b/organizing-js/objects-constructors.md @@ -1,15 +1,15 @@ ### Introduction -In our JavaScript fundamentals course you should have learned the [basics of using objects](https://www.theodinproject.com/courses/web-development-101/lessons/fundamentals-part-5) to store and retrieve data. Lets start with a little refresher. +In our JavaScript fundamentals course, you should have learned the [basics of using objects](https://www.theodinproject.com/courses/web-development-101/lessons/fundamentals-part-5) to store and retrieve data. Let's start with a little refresher. -There are multiple ways to define objects but in most cases it is best to use the __object literal__ syntax as follows: +There are multiple ways to define objects but in most cases, it is best to use the __object literal__ syntax as follows: ~~~javascript const myObject = { - property: 'Value!', - otherProperty: 77, - "obnoxious property": function() { - // do stuff! - } +  property: 'Value!', +  otherProperty: 77, +  "obnoxious property": function() { +    // do stuff! + } } ~~~ @@ -23,7 +23,7 @@ myObject.property // 'Value!' myObject["obnoxious property"] // [Function] ~~~ -Which method you use will depend on context. Dot notation is cleaner and is usually preferred, but there are plenty of circumstances when it is not possible to use it. For example, `myObject."obnoxious property"` won't work because that property is a string with a space in it. Likewise, you can not use variables in dot notation: +Which method you use will depend on context. Dot notation is cleaner and is usually preferred, but there are plenty of circumstances when it is not possible to use it. For example, `myObject."obnoxious property"` won't work because that property is a string with a space in it. Likewise, you can not use variables in dot notation: ~~~javascript const variable = 'property' @@ -37,7 +37,7 @@ If you are feeling rusty on using objects, now might be a good time to go back a ### Objects as a Design Pattern -One of the simplest ways you can begin to organize your code is by simply grouping things into objects. Take these examples from a 'tic tac toe' game: +One of the simplest ways you can begin to organize your code is by simply grouping things into objects. Take these examples from a 'tic tac toe' game: ~~~javascript // example one @@ -48,41 +48,41 @@ const playerTwoMarker = "O" // example two const playerOne = { - name: "tim", - marker: "X" +  name: "tim", +  marker: "X" } const playerTwo = { - name: "jenn", - marker: "O" +  name: "jenn", +  marker: "O" } ~~~ -At first glance the first doesn't seem so bad.. and it actually takes fewer lines to write than the example using objects, but the benefits are huge! Let me demonstrate: +At first glance, the first doesn't seem so bad.. and it actually takes fewer lines to write than the example using objects, but the benefits are huge! Let me demonstrate: ~~~javascript function printName(player) { - console.log(player.name) +  console.log(player.name) } ~~~ -This is something that you just could NOT do with the example one setup. Instead, every time you wanted to print a specific player's name you would have to remember the correct variable name and then manually `console.log` it: +This is something that you just could NOT do with the example one setup. Instead, every time you wanted to print a specific player's name you would have to remember the correct variable name and then manually `console.log` it: ~~~javascript console.log(playerOneName) console.log(playerTwoName) ~~~ -Again, this isn't _that_ bad... but what if you _don't know_ which player's you want to print? +Again, this isn't _that_ bad... but what if you _don't know_ which player's name you want to print? ~~~javascript function gameOver(winningPlayer){ - console.log("Congraulations!") - console.log(winningPlayer.name + " is the winner!") +  console.log("Congraulations!") +  console.log(winningPlayer.name + " is the winner!") } ~~~ -Or, what if we aren't making a 2 player game, but something more complicated such as an online shopping site with a large inventory? In that case using objects to keep track of an item's name, price, description and other things is the only way to go. Unfortunately, in that type of situation manually typing out the contents of our objects is not feasible either. We need a cleaner way to create our objects, which brings us to... +Or, what if we aren't making a 2 player game, but something more complicated such as an online shopping site with a large inventory? In that case, using objects to keep track of an item's name, price, description and other things is the only way to go. Unfortunately, in that type of situation manually typing out the contents of our objects is not feasible either. We need a cleaner way to create our objects, which brings us to... ### Object Constructors @@ -90,8 +90,8 @@ When you have a specific type of object that you need to duplicate like our play ~~~javascript function Player(name, marker) { - this.name = name - this.marker = marker +  this.name = name +  this.marker = marker } ~~~ @@ -106,11 +106,11 @@ Just like with objects created using the Object Literal method you can add funct ~~~javascript function Player(name, marker) { - this.name = name - this.marker = marker - this.sayName = function() { - console.log(name) - } +  this.name = name +  this.marker = marker +  this.sayName = function() { +    console.log(name) +  } } const player1 = new Player('steve', 'X') @@ -123,7 +123,7 @@ player2.sayName() // logs 'also steve' ### Exercise -Write a constructor for making "book" objects. We will revisit this in the project at the end of this lesson. Your book objects should have the book's `title`, `author`, the number of `pages`, and whether or not you have `read` the book +Write a constructor for making "book" objects. We will revisit this in the project at the end of this lesson. Your book objects should have the book's `title`, `author`, the number of `pages`, and whether or not you have `read` the book Put a function into the constructor that can report the book info like so @@ -131,7 +131,7 @@ Put a function into the constructor that can report the book info like so book.info() // "The Hobbit by J.R.R. Tolkien, 295 pages, not read yet" ~~~ -note: it is almost _always_ best to `return` things rather than putting `console.log()` directly into the function. In this case, return the `info` string and log it after the function has been called: +note: it is almost _always_ best to `return` things rather than putting `console.log()` directly into the function. In this case, return the `info` string and log it after the function has been called: ~~~javascript console.log(theHobbit.info()); @@ -139,46 +139,46 @@ console.log(theHobbit.info()); ### The Prototype -Before we go much further, there's something important you need to understand about JavaScript objects. All objects in JavaScript have a `prototype`. Stated simply, the prototype is another object that the original object _inherits_ from, which is to say, the original object has access to all of it's prototype's methods and properties. +Before we go much further, there's something important you need to understand about JavaScript objects. All objects in JavaScript have a `prototype`. Stated simply, the prototype is another object that the original object _inherits_ from, which is to say, the original object has access to all of its prototype's methods and properties. -This concept is an important one, so you've got some reading to do. Make sure you really get this before moving on! +This concept is an important one, so you've got some reading to do. Make sure you really get this before moving on! -1. [This article](http://javascriptissexy.com/javascript-prototype-in-plain-detailed-language/) is a straightforward introduction and demonstration of the concept. It also covers constructors again.. good time for a review! The important bits here, once you've covered the basics are 'Prototype based inheritance' and the 'Prototype chain' -2. To go a bit deeper into both the chain and inheritance spend some time with [this great article](http://javascript.info/prototype-inheritance). As usual, doing the exercises at the end will help cement this knowledge in your mind. Don't skip them! Important note: this article makes heavy use of `__proto__` which is not generally recommended. The concepts here are what we're looking for at the moment. We will soon learn another method or two for setting the prototype. +1. [This article](http://javascriptissexy.com/javascript-prototype-in-plain-detailed-language/) is a straightforward introduction and demonstration of the concept. It also covers constructors again.. good time for a review! The important bits here, once you've covered the basics are 'Prototype-based inheritance' and the 'Prototype chain' +2. To go a bit deeper into both the chain and inheritance spend some time with [this great article](http://javascript.info/prototype-inheritance). As usual, doing the exercises at the end will help cement this knowledge in your mind. Don't skip them! Important note: this article makes heavy use of `__proto__` which is not generally recommended. The concepts here are what we're looking for at the moment. We will soon learn another method or two for setting the prototype. -If you've understood the concept of prototype then this next bit about constructors will not be confusing at all! +If you've understood the concept of the prototype then this next bit about constructors will not be confusing at all! ~~~javascript function Student(name) { - this.name = name - this.grade = grade +  this.name = name +  this.grade = grade } Student.prototype.sayName = function() { - console.log(this.name) +  console.log(this.name) } Student.prototype.goToProm = function() { - // eh.. go to prom? +  // eh.. go to prom? } ~~~ -If you're using constructors to make your objects it is best to define functions on the `prototype` of that object. Doing so means that a single instance of each function will be shared between all of the Student objects. If we declare the function directly in the constructor like we did when they were first introduced that function would be duplicated every time a new Student is created. In this example of course that wouldn't really matter much, but in a project that is creating thousands of objects it really can make a difference. +If you're using constructors to make your objects it is best to define functions on the `prototype` of that object. Doing so means that a single instance of each function will be shared between all of the Student objects. If we declare the function directly in the constructor like we did when they were first introduced that function would be duplicated every time a new Student is created. In this example, that wouldn't really matter much, but in a project that is creating thousands of objects, it really can make a difference. #### Recommended Method for Prototypal Inheritance -So far you have seen several ways of making an object inherit the prototype from another object. At this point in history the recommended way of setting the prototype of an object is `Object.create` ( [here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create) is the documentation for that method.) `Object.create` very simply returns a new object with the specified prototype and any additional properties you want to add. For our purposes you use it like so: +So far you have seen several ways of making an object inherit the prototype from another object. At this point in history, the recommended way of setting the prototype of an object is `Object.create` ( [here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create) is the documentation for that method.) `Object.create` very simply returns a new object with the specified prototype and any additional properties you want to add. For our purposes you use it like so: ~~~javascript function Student() { } Student.prototype.sayName = function() { - console.log(this.name) +  console.log(this.name) } function EighthGrader(name) { - this.name = name - this.grade = 8 +  this.name = name +  this.grade = 8 } EighthGrader.prototype = Object.create(Student.prototype) @@ -188,7 +188,7 @@ carl.sayName() // console.logs "carl" carl.grade // 8 ~~~ -You can probably figure out what's going on here. After creating the constructor for EighthGrader we set it's prototype to a new object that has a copy of `Student.prototype`. +You can probably figure out what's going on here. After creating the constructor for EighthGrader we set it's prototype to a new object that has a copy of `Student.prototype`. A warning... this doesn't work: @@ -196,27 +196,27 @@ A warning... this doesn't work: EighthGrader.prototype = Student.prototype ~~~ -because it will literally set EighthGrader's prototype to Student.prototype (i.e. not a copy), which could cause problems if you want to edit something in the future. Consider one more example: +because it will literally set EighthGrader's prototype to Student.prototype (i.e. not a copy), which could cause problems if you want to edit something in the future. Consider one more example: ~~~javascript function Student() { } Student.prototype.sayName = function() { - console.log(this.name) +  console.log(this.name) } function EighthGrader(name) { - this.name = name - this.grade = 8 +  this.name = name +  this.grade = 8 } // don't do this!!! EighthGrader.prototype = Student.prototype function NinthGrader(name) { - this.name = name - this.grade = 9 +  this.name = name +  this.grade = 9 } // noooo! not again! diff --git a/organizing-js/oop-concepts.md b/organizing-js/oop-concepts.md index bf974759..da821240 100644 --- a/organizing-js/oop-concepts.md +++ b/organizing-js/oop-concepts.md @@ -1,29 +1,29 @@ ### Introduction -By this point you will have learned and had a chance to practice the most common object-creation and organization patterns in JavaScript. But that is just the _tip_ of the iceberg. More important than learning the syntax for factory functions or modules is figuring out how to use them effectively. +By this point, you will have learned and had a chance to practice the most common object-creation and organization patterns in JavaScript. But that is just the _tip_ of the iceberg. More important than learning the syntax for factory functions or modules is figuring out how to use them effectively. -This whole series of lessons has been about the "Object Oriented Programming" paradigm (OOP). The basics of creating objects and classes are relatively straightforward. But it is not straightforward to decide what to put in each object, or when to make a new object, or when to let an object 'inherit' from another one. +This whole series of lessons has been about the "Object Oriented Programming" paradigm (OOP). The basics of creating objects and classes are relatively straightforward. But it is not straightforward to decide what to put in each object, or when to make a new object, or when to let an object 'inherit' from another one. -Luckily there are several concepts and principles that can guide us into making good decisions when it comes to our objects. This lesson is an introduction to the most important of those concepts. Keep in mind that there is not usually a very clear answer to your application design questions. Some patterns and ideas are obviously better than others, but there is often some trade-off when deciding where to put a specific function. In other words.. these principles are not _rules_- they're helpful guidelines. +Luckily there are several concepts and principles that can guide us into making good decisions when it comes to our objects. This lesson is an introduction to the most important of those concepts. Keep in mind that there is not usually a very clear answer to your application design questions. Some patterns and ideas are obviously better than others, but there is often some trade-off when deciding where to put a specific function. In other words.. these principles are not _rules_- they're helpful guidelines.   -As you read these resources it might help to go back to some of the projects you've already done and think about how what you've written measures up to the examples you see. And of course, as you move on keep these things in mind when crafting new projects +As you read these resources, it might help to go back to some projects you've already done and think about how what you've written measures up to the examples you see. And of course, as you move on keep these things in mind when crafting new projects ### Single Responsibility -One of the most important things to remember as you craft your objects is the __Single Responsibility Principle__ which states that a class (or object or module.. you get the point) should only have _one_ responsibility. Here's a really common example. Most of our code has functions to update and write things to the DOM in addition to our application logic. It's a _really_ good idea to separate out your DOM stuff from the application logic. +One of the most important things to remember as you craft your objects is the __Single Responsibility Principle__ which states that a class (or object or module.. you get the point) should only have _one_ responsibility. Here's a really common example. Most of our code has functions to update and write things to the DOM in addition to our application logic. It's a _really_ good idea to separate out your DOM stuff from the application logic. So instead of this: ~~~javascript function is_game_over() { - // game over logic goes here! +  // game over logic goes here! - if (gameOver){ - const gameOverDiv = document.createElement('div') - gameOverDiv.classList.add('game-over') - gameOverDiv.textContent = `${this.winner} won the game!` - document.body.appendChild(gameOverDiv) - } +  if (gameOver){ +    const gameOverDiv = document.createElement('div') +    gameOverDiv.classList.add('game-over') + gameOverDiv.textContent = `${this.winner} won the game!` +    document.body.appendChild(gameOverDiv) +  } } ~~~ @@ -32,17 +32,17 @@ You should extract all the DOM manipulation into it's own module and use it like ~~~javascript function is_game_over() { - // game over logic goes here! +  // game over logic goes here! - if (gameOver){ - DOMStuff.gameOver(this.winner) - } +  if (gameOver){ +    DOMStuff.gameOver(this.winner) +  } } ~~~ In fact - the function `is_game_over` shouldn't be calling the DOM function anyway that should go elsewhere (directly in the game-loop) -> The Single Responsibility Principle is the first of a commonly found set of 5 design principles called the __SOLID__ principles. Both of the following articles mention the acronym __SOLID__ before going on to talk about Single Responsibility. Single Responsibility is definitely the most relevant of the 5. Feel free to dig into the rest of the SOLID principles if you like.. but pay special attention to Single Responsibility. +> The Single Responsibility Principle is the first of a commonly found set of 5 design principles called the __SOLID__ principles. Both of the following articles mention the acronym __SOLID__ before going on to talk about Single Responsibility. Single Responsibility is definitely the most relevant of the 5. Feel free to dig into the rest of the SOLID principles if you like.. but pay special attention to Single Responsibility. 1. Read [This Article](http://aspiringcraftsman.com/2011/12/08/solid-javascript-single-responsibility-principle/). 2. [This article](https://thefullstack.xyz/solid-javascript/) hits the same topic, and also covers the rest of 'SOLID' concisely. @@ -52,9 +52,9 @@ In fact - the function `is_game_over` shouldn't be calling the DOM function anyw ### Loosely Coupled Objects -Obviously all of our objects are intended to work together to form our final application. You should take care, however, to make sure that your individual objects can stand alone as much as possible. __Tightly coupled__ objects are objects that rely so heavily on each other that removing or changing one will mean that you have to completely change another one - a real bummer. +Obviously, all of our objects are intended to work together to form our final application. You should take care, however, to make sure that your individual objects can stand alone as much as possible. __Tightly coupled__ objects are objects that rely so heavily on each other that removing or changing one will mean that you have to completely change another one - a real bummer. -This one is related pretty strongly to 'Single Responsibility' but takes a different angle. As an example, if we were writing a game and wanted to completely change how the User Interface worked, we should be able to do that without completely reworking the game logic. So we should be able to start off writing our game using primarily `console.logs()` and then add in the a bunch of `DOM` functions later without touching the game logic. +This one is related pretty strongly to 'Single Responsibility' but takes a different angle. As an example, if we were writing a game and wanted to completely change how the User Interface worked, we should be able to do that without completely reworking the game logic. So we should be able to start off writing our game using primarily `console.logs()` and then add in a bunch of `DOM` functions later without touching the game logic. 1. [This article](https://www.innoarchitech.com/scalable-maintainable-javascript-coupling/) explains it pretty well. -2. The best book we've ever read on this subject is [Practical Object Oriented Design In Ruby](http://www.poodr.com/). Unfortunately it is not free.. and not JavaScript. We feel confident in recommending it anyway. If you don't know Ruby, it is a clear enough language that you don't really need to learn it to follow the examples and the content in the book is sincerely fantastic. +2. The best book we've ever read on this subject is [Practical Object-Oriented Design In Ruby](http://www.poodr.com/). Unfortunately, it is not free.. and not JavaScript. We feel confident in recommending it anyway. If you don't know Ruby, it is a clear enough language that you don't really need to learn it to follow the examples and the content of the book is sincerely fantastic. diff --git a/organizing-js/organizing-introduction.md b/organizing-js/organizing-introduction.md index 9982a9f6..d2228557 100644 --- a/organizing-js/organizing-introduction.md +++ b/organizing-js/organizing-introduction.md @@ -1,10 +1,10 @@ ### Organizing your JavaScript code -One of the most daunting parts of JavaScript is learning how to organize your code. The reason this subject can be so overwhelming is _not_ because JavaScript is so much more complex than other languages, but because it is incredibly forgiving! Many languages force you into using specific patterns and data structures in your code but that is not true in JavaScript. +One of the most daunting parts of JavaScript is learning how to organize your code. The reason this subject can be so overwhelming is _not_ because JavaScript is so much more complex than other languages, but because it is incredibly forgiving! Many languages force you into using specific patterns and data structures in your code but that is not true in JavaScript. -In the beginning this is a great thing! For example, if you just want to make a simple button on your webpage do something you can set that up in a couple lines of code. However, as your program becomes more complex, it can become hard to maintain unless you take care to organize your code and because JavaScript is such a flexible language how you do that is entirely up to you. For many coders making decisions about design patterns is crippling so we're here to help. +In the beginning, this is a great thing! For example, if you just want to make a simple button on your webpage do something you can set that up in a couple lines of code. However, as your program becomes more complex, it can become hard to maintain unless you take care to organize your code and because JavaScript is such a flexible language how you do that is entirely up to you. For many coders making decisions about design patterns is crippling so we're here to help. -This lesson series is going to cover a few of the most common design patterns that occur in modern JavaScript code, will discuss some of the pros and cons of each pattern and will give you a chance to practice using each pattern in a project. +This lesson series is going to cover a few of the most common design patterns that occur in modern JavaScript code, will discuss some pros and cons of each pattern and will give you a chance to practice using each pattern in a project. The patterns we'll be covering in this series are: diff --git a/organizing-js/restaurant-project.md b/organizing-js/restaurant-project.md index 1be9f377..05c53bd0 100644 --- a/organizing-js/restaurant-project.md +++ b/organizing-js/restaurant-project.md @@ -1,27 +1,27 @@ ### Introduction -Lets use what we've learned and take a chance to continue practicing DOM manipulation - dynamically rendering a simple restaurant homepage! By the end of it we are going to be using only JavaScript to generate the entire contents of the website! +Let's use what we've learned and take a chance to continue practicing DOM manipulation - dynamically rendering a simple restaurant homepage! By the end, we are going to be using only JavaScript to generate the entire contents of the website! ### Assignment
1. Start the project the same way you began the webpack tutorial project. - 1. run `npm init` in your project directory to generate a `package.json` file - 2. run `npm install --save-dev webpack` to install webpack to the node_modules directory of your project. - - Quick tip: the `node_modules` folder can get _really_ big. It is customary to add a `.gitignore` file to your project so that you don't have to sync the contents of `node_modules` to github. The dependencies that are stored there can be installed from your package.json by running `npm install`, so you don't need to sync them. - 3. Create a `src` and `dist` directory with the following contents: - 1. an `index.js` file in `src` - 2. an `index.html` file in `dist`. Go ahead and link the `bundle.js` file in a script tag. `bundle.js` is the file that will be generated by webpack. - 4. create a `webpack.config.js` file that looks just like our file from the tutorial. +   1. run `npm init` in your project directory to generate a `package.json` file +   2. run `npm install --save-dev webpack` to install webpack to the node_modules directory of your project. +      - Quick tip: the `node_modules` folder can get _really_ big. It is customary to add a `.gitignore` file to your project so that you don't have to sync the contents of `node_modules` to github. The dependencies that are stored there can be installed from your package.json by running `npm install`, so you don't need to sync them. +   3. Create a `src` and `dist` directory with the following contents: +      1. an `index.js` file in `src` +      2. an `index.html` file in `dist`. Go ahead and link the `bundle.js` file in a script tag. `bundle.js` is the file that will be generated by webpack. +   4. create a `webpack.config.js` file that looks just like our file from the tutorial. 2. Set up an HTML skeleton inside of `dist/index.html` with single `
`. -3. Inside of `src/index.js` write a simple console.log or alert statement and then run `webpack`. Load up `dist/index.html` in a browser to make sure everything is working correctly. - - Quick tip #2: if you run `webpack --watch` you will not have to rerun webpack every time you make a change. +3. Inside of `src/index.js` write a simple console.log or alert statement and then run `webpack`. Load up `dist/index.html` in a browser to make sure everything is working correctly. +   - Quick tip #2: if you run `webpack --watch` you will not have to rerun webpack every time you make a change. 4. Create a bare-bones home page for a restaurant. Include an image, headline, and some copy about how wonderful the restaurant is. It’s okay to hard-code these into the HTML for now just to see how they look on the page. -5. Now remove those elements from the HTML (so leave only the ``, ``, and `
` tags) and instead create them by using Javascript only, e.g. by appending each new element to the `div#content`once the page is first loaded. Since we're all set up to write our code in multiple files write this initial page-load function inside of it's own module and then import and call it inside of `index.js` +5. Now remove those elements from the HTML (so leave only the ``, ``, and `
` tags) and instead create them by using Javascript only, e.g. by appending each new element to the `div#content`once the page is first loaded. Since we're all set up to write our code in multiple files write this initial page-load function inside of it's own module and then import and call it inside of `index.js` 6. Next, set up your restaurant site to use tabbed browsing to access the Contact and Menu pages. [Look at #7 on this hongkiat post](http://www.hongkiat.com/blog/50-nice-clean-css-tab-based-navigation-scripts/) for visual inspiration. - 1. Put the contents of each 'tab' inside of it's own module. Each module will export a function that creates a div element, adds the appropriate content and styles to that element and then appends it to the DOM - 2. Write the tab-switching logic inside of `index.js`. You should have event listeners for each tab that wipes out the current contents and then runs the correct 'tab module' to populate it again. -7. If you are using GitHub pages to host your completed page you need to do a tiny bit more work to get it to show up. After running `webpack` the full bundled version of your site is available in the `dist` folder, but GH pages is looking for an index.html in the root directory of your project. - 1. Simply follow the instructions on [this gist](https://gist.github.com/cobyism/4730490). EZPZ! +   1. Put the contents of each 'tab' inside of it's own module. Each module will export a function that creates a div element, adds the appropriate content and styles to that element and then appends it to the DOM +   2. Write the tab-switching logic inside of `index.js`. You should have event listeners for each tab that wipes out the current contents and then runs the correct 'tab module' to populate it again. +7. If you are using GitHub pages to host your completed page you need to do a tiny bit more work to get it to show up. After running `webpack` the full bundled version of your site is available in the `dist` folder, but GH pages is looking for an index.html in the root directory of your project. +   1. Simply follow the instructions on [this gist](https://gist.github.com/cobyism/4730490). EZPZ! ### Student Solutions To add your solution to the list below, edit this [file](https://github.com/TheOdinProject/javascript_curriculum/blob/master/organizing-js/restaurant-project.md) (located on The Odin Project's "curriculum" github repository). See the section on [Contributing](http://github.com/TheOdinProject/curriculum/blob/master/contributing.md) for more instructions.