diff --git a/README.md b/README.md index 1d088ef..9175e47 100644 --- a/README.md +++ b/README.md @@ -6,6 +6,6 @@ The material in this repository is divided by topic. * SQL * Rails * HTML/CSS -* JavaScript +* [JavaScript](/javascript/Open_JavaScript_Overview.md) * React * Full-Stack Project diff --git a/javascript/Open_JavaScript_Overview.md b/javascript/Open_JavaScript_Overview.md new file mode 100644 index 0000000..ab4c23b --- /dev/null +++ b/javascript/Open_JavaScript_Overview.md @@ -0,0 +1,190 @@ +# JavaScript + +## Topics Covered + +- [Getting started](#getting-started) +- [JavaScript Fundamentals](#javascript-fundamentals) +- [The Event Loop](#the-event-loop) +- [Object-oriented JavaScript](#object-oriented-javascript) +- [jQuery](#jquery) +- [AJAX](#ajax) +- [JavaScript DOM API](#javascript-dom-api) + + +## Notes + +JavaScript is the fourth module in the App Academy Full Stack Developer +Curriculum. + +As with all future modules, any "Bonus" projects are to be completed after the +standard projects for each day are completed. Sometimes that could mean going +back to the previous day's "Bonus" projects if you otherwise finish early. +Additional Resources are readings, videos, or articles that are not required, +but will serve to deepen your understanding of a topic. They will be denoted +with a specific icon in your task menu. + +## Getting started +- [ ] 1. [Setting up a Development Environment (Phase 3)](../course/readings/dev-setup.md#phase-3-frontend-development) +## JavaScript Fundamentals +- [ ] 1. [Intro to JS Video](https://player.vimeo.com/video/169645510) +- [ ] 2. [Object-Oriented JS: Intro](https://player.vimeo.com/video/169806088) +- [ ] 3. [Object-Oriented JS: Demo](https://player.vimeo.com/video/169804475) +- [ ] 4. [Closures and Callbacks](https://player.vimeo.com/video/169898573) +- [ ] 5. [Debugging JS in VSCode](readings/vs-code-node-debugger.md) +- [ ] 6. [Intro to JS](readings/js-intro.md) +- [ ] 7. [Syntax and Useful Methods](readings/syntax-and-methods.md) +- [ ] 8. [Data Types](readings/data-types.md) +- [ ] 9. [Variables](readings/variables.md) +- [ ] 10. [Functions](readings/functions-js.md) +- [ ] 11. [Closures and Scope](readings/closures.md) +- [ ] 12. [this and that](readings/this-and-that.md) +- [ ] 13. [ES6 Arrow Functions](readings/fat-arrows.md) +- [ ] 14. [Javascript Fundamentals Quiz](quizzes/js_fundamentals.md) +- [ ] 15. [Intro JavaScript Problems (Part 1)](homeworks/intro_js_problems/part_i.md) +- [Solution](https://assets.aaonline.io/fullstack/javascript/homeworks/intro_js_problems/solution.zip) +- [ ] 16. [Intro JavaScript Problems (Part 2)](homeworks/intro_js_problems/part_ii.md) +- [Solution](https://assets.aaonline.io/fullstack/javascript/homeworks/intro_js_problems/solution.zip) +- [ ] 17. [Object Oriented JS: Continued](readings/object-oriented-js.md) +- [ ] 18. [Function Invocation, briefly](readings/function-invocation-briefly.md) +- [ ] 19. [Codecademy JS Curriculum](https://www.codecademy.com/learn/introduction-to-javascript) +- [ ] 20. [jQuery Fundamentals: Javascript Basics](http://jqfundamentals.com/chapter/javascript-basics) +- [ ] 21. [MDN Guide](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide) +- [ ] 22. [MDN Documentation](readings/mdn-js.md) +- [ ] 23. [CSS Positioning](../html-css/lecture_readings/css_positioning.md) +- [ ] 24. [CSS Pseudo Content](../html-css/lecture_readings/css_pseudo_content.md) +- [ ] 25. [Intro to JS & Variables Lecture](https://player.vimeo.com/video/337414181) +- [ ] 26. [Functions Lecture](https://player.vimeo.com/video/337415731) +- [ ] 27. [Hoisting Lecture](https://player.vimeo.com/video/337417596) +- [ ] 28. [Closures Lecture](https://player.vimeo.com/video/337417926) +- [ ] 29. [Callbacks Lecture](https://player.vimeo.com/video/337418311) +- [ ] 30. [Intro JavaScript Exercises](projects/intro_js_exercises/README.md) +- [Solution](https://assets.aaonline.io/fullstack/javascript/projects/intro_js_exercises/solution.zip) +- [ ] 31. [CSS Friends Part 2](../html-css/micro-projects/css_friends_combined/css_friends_1/README.md#phase-2-thumbs) +- [Solution](https://assets.aaonline.io/fullstack/html-css/micro-projects/combined-css-friends/css-friends-pt2/solution.zip) +- [ ] 32. [JS: Reversi](projects/js_reversi/README.md) +- [Solution](https://assets.aaonline.io/fullstack/javascript/projects/js_reversi/solution.zip) +## The Event Loop +- [ ] 1. [Arguments](readings/arguments.md) +- [ ] 2. [Function Invocation, in-depth](readings/function-invocation-in-depth.md) +- [ ] 3. [Intro to Callbacks: File I/O](readings/intro-to-callbacks.md) +- [ ] 4. [Event Loop Visualization](http://latentflip.com/loupe) +- [ ] 5. [ES6 Class Syntax](readings/es6-classes.md) +- [ ] 6. [Node Module Pattern](readings/module-pattern.md) +- [ ] 7. [Chrome Dev Tools](readings/chrome_dev_tools.md) +- [ ] 8. [Ruby, ES5 & ES6 Comparison Chart](https://appacademy.github.io/curriculum/language_comparison/index.html) +- [ ] 9. [Event Loop Quiz](quizzes/event_loop.md) +- [ ] 10. [Callbacks and Function Calls](homeworks/callbacks_and_functions/README.md) +- [Solution](https://assets.aaonline.io/fullstack/javascript/homeworks/callbacks_and_functions/solution.js) +- [ ] 11. [Writing Clean Code](readings/indentation.md) +- [ ] 12. [Crockford](http://javascript.crockford.com/code.html) +- [ ] 13. [jQuery](http://contribute.jquery.org/style-guide/js/) +- [ ] 14. [AirBnB](https://github.com/airbnb/javascript) +- [ ] 15. [Tagging Template Literals (Bonus)](readings/tagged-templates.md) +- [ ] 16. [Call & Apply](https://player.vimeo.com/video/337176717) +- [ ] 17. [Bind pt. 1](https://player.vimeo.com/video/337181208) +- [ ] 18. [Bind pt. 2](https://player.vimeo.com/video/337186583) +- [ ] 19. [Async Behavior](https://player.vimeo.com/video/337189725) +- [ ] 20. [Intro to Callbacks Exercises](projects/functions_exercises/README.md) +- [Solution](https://assets.aaonline.io/fullstack/javascript/projects/functions_exercises/solution.zip) +- [ ] 21. [Towers of Hanoi: JS Edition](projects/hanoi_node/README.md) +- [Solution](https://assets.aaonline.io/fullstack/javascript/projects/hanoi_node/solution.zip) +- [ ] 22. [Tic-Tac-Toe: JS Edition](projects/ttt_node/README.md) +- [Solution](https://assets.aaonline.io/fullstack/javascript/projects/ttt_node/solution.zip) +## Object-oriented JavaScript +- [ ] 1. [Prototype Chain and Inheritance](https://player.vimeo.com/video/162131042) +- [ ] 2. [Inheritance Demo](https://player.vimeo.com/video/162115223) +- [ ] 3. [JS in Browser](https://player.vimeo.com/video/162115224) +- [ ] 4. [Prototypal Inheritance](readings/prototypal-inheritance.md) +- [ ] 5. [Modules in the Browser](readings/browser-modules.md) +- [ ] 6. [Basic Canvas Driving](https://joshondesign.com/p/books/canvasdeepdive/chapter01.html) +- [ ] 7. [Webpack Tutorial](https://webpack.js.org/guides/getting-started/) +- [ ] 8. [Intro to Canvas](homeworks/canvas_practice/README.md) +- [Solution](https://assets.aaonline.io/fullstack/javascript/homeworks/canvas_practice/solution.js) +- [ ] 9. [Canvas Demo: DrunkenCircles](demos/drunken_circles/README.md) +- [ ] 10. [LGBT Workplace Fact Sheet](http://outandequal.org/2017-workplace-equality-fact-sheet/) +- [ ] 11. [It is Bigger Than Microaggressions](https://modelviewculture.com/pieces/it-is-bigger-than-microaggressions) +- [ ] 12. [LGBT Minorities Face Job Discrimination](http://fortune.com/2017/06/25/lgbtq-employment-discrimination/) +- [ ] 13. [Out in Tech](https://www.geekwire.com/2015/out-in-tech-what-its-like-to-be-lgbt-in-an-industry-struggling-with-diversity) +- [ ] 14. [Transitioning in the Digital Age](https://modelviewculture.com/pieces/transitioning-in-the-digital-age) +- [ ] 15. [Asynchronous Client-Side Code](readings/asynchronous-js.md) +- [ ] 16. [Client-Side JavaScript](readings/client-side-javascript.md) +- [ ] 17. [Object Oriented Javascript Quiz](quizzes/object_oriented_js.md) +- [ ] 18. [myBind Solutions](https://player.vimeo.com/video/332499533) +- [ ] 19. [Currying Solutions](https://player.vimeo.com/video/332501585) +- [ ] 20. [Prototypal Inheritance Lecture](https://player.vimeo.com/video/332504701) +- [ ] 21. [Webpack Lecture](https://player.vimeo.com/video/332503425) +- [ ] 22. [Canvas Intro Lecture](https://player.vimeo.com/video/332502700) +- [ ] 23. [arguments Exercise Problems](projects/arguments_exercises/README.md) +- [Solution](https://assets.aaonline.io/fullstack/javascript/projects/arguments_exercises/solution.zip) +- [ ] 24. [Prototypal Inheritance Exercises](projects/inherits_exercises/README.md) +- [Solution](https://assets.aaonline.io/fullstack/javascript/projects/inherits_exercises/solution.zip) +- [ ] 25. [Flappy Bird](projects/flappy_bird/README.md) +- [Solution](https://assets.aaonline.io/fullstack/javascript/projects/flappy_bird/solution.zip) +- [ ] 26. [Asteroids](projects/asteroids/README.md) +- [Solution](https://assets.aaonline.io/fullstack/javascript/projects/asteroids/prototypal_syntax_solution.zip) +## jQuery +- [ ] 1. [The Document Object Model](readings/document-object-model.md) +- [ ] 2. [jQuery I: Selection and Manipulation](readings/jquery-01-selection-and-manipulation.md) +- [ ] 3. [jQuery II: Events](readings/jquery-02-events.md) +- [ ] 4. [jQuery III: Ready](readings/jquery-03-ready.md) +- [ ] 5. [jQuery IV: All the Ways](readings/jquery-04-all-the-ways.md) +- [ ] 6. [jQuery V: Data Attributes](readings/jquery-05-data-attributes.md) +- [ ] 7. [backbone-14: jQuery Event Delegation](https://player.vimeo.com/video/85221706) +- [ ] 8. [jQuery VI: Event Delegation](readings/jquery-06-event-delegation.md) +- [ ] 9. [jQuery Quiz](quizzes/jquery.md) +- [ ] 10. [Wacky jQuery](homeworks/wacky_painter/README.md) +- [ ] 12. [ES6 Prototypal Inheritance](readings/new-prototypal-inheritance.md) +- [ ] 13. [jQuery Documentation](http://api.jquery.com/) +- [ ] 14. [jQuery Fundamentals (Ch 2-4)](http://jqfundamentals.com/) +- [ ] 15. [jQuery - Intro & Selector Functions](https://player.vimeo.com/video/337661679) +- [ ] 16. [jQuery - Events](https://player.vimeo.com/video/337661180) +- [ ] 17. [jQuery - Form Submission & DOM Insertion](https://player.vimeo.com/video/337660471) +- [ ] 18. [jQuery.data Function](https://player.vimeo.com/video/337656355) +- [ ] 19. [jQuery Towers of Hanoi](projects/hanoi_jquery/README.md) +- [Solution](https://assets.aaonline.io/fullstack/javascript/projects/hanoi_jquery/solution.zip) +- [ ] 20. [jQuery Snake](projects/snake/README.md) +- [Solution](https://assets.aaonline.io/fullstack/javascript/projects/snake/solution.zip) +## AJAX +- [ ] 1. [AJAX Video Lecture](https://player.vimeo.com/video/162860823) +- [ ] 2. [AJAX Demo](https://player.vimeo.com/video/162764008) +- [ ] 3. [AJAX Demo: code](https://assets.aaonline.io/fullstack/javascript/demos/chat_demo/chat_demo.zip) +- [ ] 4. [Basic AJAX](readings/basic-ajax.md) +- [ ] 5. [AJAX Remote Forms](readings/ajax-remote-forms.md) +- [ ] 6. [Using Rails as an API](readings/rails-api.md) +- [ ] 7. [Promises](readings/promises.md) +- [ ] 8. [AJAX Quiz](quizzes/ajax.md) +- [ ] 9. [Your First AJAX Request](homeworks/first_ajax/README.md) +- [Solution](https://assets.aaonline.io/fullstack/javascript/homeworks/first_ajax/solution.zip) +- [ ] 10. [jQuery Fundamentals: AJAX](http://jqfundamentals.com/chapter/ajax-deferreds) +- [ ] 11. [Simple AJAX Example](readings/simple-ajax-example.md) +- [ ] 12. [Intro & First Request](https://player.vimeo.com/video/340062966) +- [ ] 14. [Webpack & AJAX on Rails](https://player.vimeo.com/video/340065552) +- [ ] 15. [AJAX Forms](https://player.vimeo.com/video/340064662) +- [ ] 16. [ApiUtil & Promises](https://player.vimeo.com/video/340063851) +- [ ] 17. [AJAX Twitter](projects/ajax_twitter/README.md) +- [Solution](https://assets.aaonline.io/fullstack/javascript/projects/ajax_twitter/solution.zip) +## JavaScript DOM API +- [ ] 1. [DOM Data Types](readings/dom_types.md) +- [ ] 2. [Events](readings/events.md) +- [ ] 3. [jQuery VII: Triggering](readings/jquery-07-triggering.md) +- [ ] 4. [Event Propagation](readings/event-propagation.md) +- [ ] 5. [DOM Content Loaded](readings/dom-content-loaded.md) +- [ ] 6. [DOM Manipulation](readings/selecting-and-manipulating-elements.md) +- [ ] 7. [History and Location](readings/history-location.md) +- [ ] 8. [Vanilla JavaScript](readings/vanilla_javascript.md) +- [ ] 9. [Vanilla JavaScript Quiz](quizzews/js_dom_api.md) +- [ ] 10. [Vanilla DOM Manipulation](homeworks/vanilla-dom/README.md) +- [Solution](https://assets.aaonline.io/fullstack/javascript/homeworks/vanilla-dom/solution.js) +- [ ] 11. [Non-technical Overview of JavaScript](readings/js-nontech.md) +- [ ] 12. [localStorage Documentation](https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage) +- [ ] 13. [localStorage Simple Examples](https://blog.logrocket.com/the-complete-guide-to-using-localstorage-in-javascript-apps-ba44edb53a36) +- [ ] 14. [Throttling and Debouncing Overview](https://css-tricks.com/debouncing-throttling-explained-examples/) +- [ ] 15. [Technical Overview of Browsers](../html-css/readings/browser_tech.md) +- [ ] 16. [Browser TicTacToe](projects/browser-ttt/README.md) +- [Solution](https://assets.aaonline.io/fullstack/javascript/projects/browser-ttt/solution.zip) +- [ ] 17. [Pocket Projects](projects/pocket_projects/README.md) +- [Solution](https://assets.aaonline.io/fullstack/javascript/projects/pocket_projects/solution.zip) +- [ ] 18. [jQuery Lite](projects/jquery_lite/README.md) +- [Solution](https://assets.aaonline.io/fullstack/javascript/projects/jquery_lite/solution.zip) +- [ ] 19. [Mail](projects/mail/README.md) +- [Solution](https://assets.aaonline.io/fullstack/javascript/projects/mail/solution.zip) diff --git a/javascript/quizzes/ajax.md b/javascript/quizzes/ajax.md index e0c7cd2..8faa126 100644 --- a/javascript/quizzes/ajax.md +++ b/javascript/quizzes/ajax.md @@ -1,28 +1,32 @@ # AJAX Quiz - - -

What is the response data type of an AJAX request?

- XML - JSON - YAML - text - The type specified by the request - You can specify what type of response you want! -
-
- - - -

What is the default request type in an AJAX request?

- GET - POST - PATCH - PUT - DELETE - Yep, it's GET! -
-
+What is the response data type of an AJAX request? +- [ ] XML +- [ ] JSON +- [ ] YAML +- [ ] text +- [ ] The type specified by the request + +
Answer: + +The type specified by the request
+
Explanation: + +You can specify what type of response you want!
+ +What is the default request type in an AJAX request? +- [ ] GET +- [ ] POST +- [ ] PATCH +- [ ] PUT +- [ ] DELETE + +
Answer: + +GET
+
Explanation: + +Yep, it's GET!
```js const fetchSuccess = kittens => { @@ -33,26 +37,30 @@ const fetchKittens = () => fetch("/kittens"); fetchKittens().then(fetchSuccess); ``` - - -

After making the above AJAX request, when will `fetchSuccess` be called?

- Whenever the request receives a response - After the request is made, but before a response is received - When the request receives a response with a 300-level status code - When the request receives a response with a 200-level status code - Never - `fetchSuccess` will be invoked when the AJAX call has resolved (returned a response with a 200-level status code). -
-
- - - -

True or False: An AJAX request is an HTTP request.

- False - True - Yep! An AJAX request dispatches an HTTP request. -
-
+After making the above AJAX request, when will `fetchSuccess` be called? +- [ ] Whenever the request receives a response +- [ ] After the request is made, but before a response is received +- [ ] When the request receives a response with a 300-level status code +- [ ] When the request receives a response with a 200-level status code +- [ ] Never + +
Answer: + +When the request receives a response with a 200-level status code
+
Explanation: + +`fetchSuccess` will be invoked when the AJAX call has resolved (returned a response with a 200-level status code).
+ +True or False: An AJAX request is an HTTP request. +- [ ] False +- [ ] True + +
Answer: + +True
+
Explanation: + +Yep! An AJAX request dispatches an HTTP request.
```js 1. promise.then(firstFulfilled).then(secondFulfilled).catch(rejected) @@ -62,16 +70,18 @@ fetchKittens().then(fetchSuccess); 3. promise.then(firstFulfilled, rejected).catch(error) ``` - - -

In what cases will `rejected` run?

- `rejected` will run in 2 and 3 if `promise` fails but not in 1. - `rejected` will run in 1 and 2 if `secondFulfilled` fails. - All three will run `rejected` if either `promise` or `firstFulfilled` fail. - All three will run `rejected` if `promise` fails. - In all three of the above scenarios the rejected callback will run if the promise fails! In Case 1, `catch` will run the callback given to it if any of the promise objects are rejected. In Case 2, after `promise` is complete, `firstFulfilled` will get invoked if the `promise` returned a status of resolved. `rejected` will get invoked if the `promise` returned a status of `rejected`. Case 3 is the same explanation as Case 2! In Cases 2 and 3, `rejected` will run ONLY if `promise` fails. Once `promise` succeeds, `firstFulfilled` (passed as the "Success Callback", i.e., the first argument to the `.then`) will run and `rejected` (passed as the "Rejected Callback", i.e., the second argument to the `.then`) will not. There has to be an error callback (second argument) in the next `.then` to catch `firstFulfilled` failing or a `.catch` anywhere later in the chain. So in Case 2 if `firstFulfilled` fails nothing will catch it, but in Case 3, `error` would catch it. -
-
+In what cases will `rejected` run? +- [ ] `rejected` will run in 2 and 3 if `promise` fails but not in 1. +- [ ] `rejected` will run in 1 and 2 if `secondFulfilled` fails. +- [ ] All three will run `rejected` if either `promise` or `firstFulfilled` fail. +- [ ] All three will run `rejected` if `promise` fails. + +
Answer: + +All three will run `rejected` if `promise` fails.
+
Explanation: + +In all three of the above scenarios the rejected callback will run if the promise fails! In Case 1, `catch` will run the callback given to it if any of the promise objects are rejected. In Case 2, after `promise` is complete, `firstFulfilled` will get invoked if the `promise` returned a status of resolved. `rejected` will get invoked if the `promise` returned a status of `rejected`. Case 3 is the same explanation as Case 2! In Cases 2 and 3, `rejected` will run ONLY if `promise` fails. Once `promise` succeeds, `firstFulfilled` (passed as the "Success Callback", i.e., the first argument to the `.then`) will run and `rejected` (passed as the "Rejected Callback", i.e., the second argument to the `.then`) will not. There has to be an error callback (second argument) in the next `.then` to catch `firstFulfilled` failing or a `.catch` anywhere later in the chain. So in Case 2 if `firstFulfilled` fails nothing will catch it, but in Case 3, `error` would catch it.
```js function getAnswers(questions) { @@ -85,16 +95,18 @@ function getAnswers(questions) { } ``` - - -

Consider the above function that takes in an array of questions and returns an array of corresponding answers. If `rl.question` is an asynchronous function that waits for user input, what is the problem with the code above?

- `rl.question` needs to be inside a `.then`. - Nothing: it will run without error. - `answer` will always be a Promise instead of the actual answer. - It will produce a `Syntax Error` because `await` is an `Unexpected reserved word`. - It will produce a `Syntax Error` because `getAnswers` is not designated as an `async` function. `await` can only be used inside `async` functions (and in a few top-level situations). -
-
+Consider the above function that takes in an array of questions and returns an array of corresponding answers. If `rl.question` is an asynchronous function that waits for user input, what is the problem with the code above? +- [ ] `rl.question` needs to be inside a `.then`. +- [ ] Nothing: it will run without error. +- [ ] `answer` will always be a Promise instead of the actual answer. +- [ ] It will produce a `Syntax Error` because `await` is an `Unexpected reserved word`. + +
Answer: + +It will produce a `Syntax Error` because `await` is an `Unexpected reserved word`.
+
Explanation: + +It will produce a `Syntax Error` because `getAnswers` is not designated as an `async` function. `await` can only be used inside `async` functions (and in a few top-level situations).
```js async function asyncPrint() { @@ -110,13 +122,15 @@ function printThings() { printThings(); ``` - - -

If you run the code above, in what order will the `console.log`s appear?

- First! Second! Third! - First! Third! Second! - Second! First! Third! - It will produce an error because `asyncPrint` is not designated as an `async` function when it is invoked inside `printThings`. - `await` only pauses the internal execution of the function in which it is invoked, so the use of `await` in `asyncPrint` will NOT effectively turn `printThings` into a synchronous function. When `asyncPrint` hits the `await`, it will pause its internal execution and cede control back to `printThings` while its Promise resolves. Once the Promise resolves, then `asyncPrint` will resume executing any subsequent code, although there's nothing left to execute after the `await` in `asyncPrint`. In other words, the `await` isn't really doing anything useful here. -
-
+If you run the code above, in what order will the `console.log`s appear? +- [ ] First! Second! Third! +- [ ] First! Third! Second! +- [ ] Second! First! Third! +- [ ] It will produce an error because `asyncPrint` is not designated as an `async` function when it is invoked inside `printThings`. + +
Answer: + +First! Third! Second!
+
Explanation: + +`await` only pauses the internal execution of the function in which it is invoked, so the use of `await` in `asyncPrint` will NOT effectively turn `printThings` into a synchronous function. When `asyncPrint` hits the `await`, it will pause its internal execution and cede control back to `printThings` while its Promise resolves. Once the Promise resolves, then `asyncPrint` will resume executing any subsequent code, although there's nothing left to execute after the `await` in `asyncPrint`. In other words, the `await` isn't really doing anything useful here.
diff --git a/javascript/quizzes/event_loop.md b/javascript/quizzes/event_loop.md index d428500..8603c98 100644 --- a/javascript/quizzes/event_loop.md +++ b/javascript/quizzes/event_loop.md @@ -13,16 +13,18 @@ const catAging = cat.ageOneYear; catAging(); ``` - - -

Consider the above code. Assuming we run the code in the browser, what is the value of `this` when we call `catAging`?

- `window` - `cat` - `undefined` - `catAging` will throw an error - you cannot save a function as a constant. - We are creating a POJO on the window assigned to the variable named `cat`. Our POJO has an attribute called `ageOneYear`. Because the context of `this` inside of the POJO will be the window, the conext of `this` will also be the window inside of the `ageOneYear` function. -
-
+Consider the above code. Assuming we run the code in the browser, what is the value of `this` when we call `catAging`? +- [ ] `window` +- [ ] `cat` +- [ ] `undefined` +- [ ] `catAging` will throw an error - you cannot save a function as a constant. + +
Answer: + +`window`
+
Explanation: + +We are creating a POJO on the window assigned to the variable named `cat`. Our POJO has an attribute called `ageOneYear`. Because the context of `this` inside of the POJO will be the window, the conext of `this` will also be the window inside of the `ageOneYear` function.
@@ -35,30 +37,32 @@ reader.question("What is your name?", function (answer) { console.log("Last program line"); ``` - - -

Consider the above code. `reader.question` is an asynchronous function. In what order are the above statements logged?

- "What is your name?", `Hello ${ answer }!`, "Last program line" - `Hello ${ answer }!`, "Last program line", "What is your name?" - "Last program line", "What is your name?", `Hello ${ answer }!` - "What is your name?", "Last program line", `Hello ${ answer }!` - Because `reader.question` will not invoke the callback given to it (which console logs `Hello ${answer}!`) until the user enters an answer. Because `reader.question` is asynchronous, JS doesn't wait around for that answer before continuing to execute the rest of the code. Therefore, `"Last program line"` will be printed before the answer the user types in will be logged. -
-
+Consider the above code. `reader.question` is an asynchronous function. In what order are the above statements logged? +- [ ] "What is your name?", `Hello ${ answer }!`, "Last program line" +- [ ] `Hello ${ answer }!`, "Last program line", "What is your name?" +- [ ] "Last program line", "What is your name?", `Hello ${ answer }!` +- [ ] "What is your name?", "Last program line", `Hello ${ answer }!` + +
Answer: +"What is your name?", "Last program line", `Hello ${ answer }!`
+
Explanation: +Because `reader.question` will not invoke the callback given to it (which console logs `Hello ${answer}!`) until the user enters an answer. Because `reader.question` is asynchronous, JS doesn't wait around for that answer before continuing to execute the rest of the code. Therefore, `"Last program line"` will be printed before the answer the user types in will be logged.
- - -

Which of the following is NOT executed asynchronously?

- `reader.question` - `Array.prototype.forEach` - `window.setInterval` - `window.setTimeout` - `forEach` will go ahead and start iterating and JS will not move on to other code until the `forEach` is complete. -
-
+Which of the following is NOT executed asynchronously? +- [ ] `reader.question` +- [ ] `Array.prototype.forEach` +- [ ] `window.setInterval` +- [ ] `window.setTimeout` + +
Answer: + +`Array.prototype.forEach`
+
Explanation: + +`forEach` will go ahead and start iterating and JS will not move on to other code until the `forEach` is complete.
```javascript @@ -73,16 +77,18 @@ const Dog = require('./dog.js'); const dog = new Dog(); ``` - - -

Why will the above code throw an error?

- `dog.js` fails to export the `Dog` constructor function. - `animals.js` should import an instance of `Dog` rather than the `Dog` constructor function. - `animals.js` should save `Dog` to a variable. - The above code will work as expected. - If we don't export the `Dog` function, JS will not know what to assign to `Dog` inside of our `animals.js` file. -
-
+Why will the above code throw an error? +- [ ] `dog.js` fails to export the `Dog` constructor function. +- [ ] `animals.js` should import an instance of `Dog` rather than the `Dog` constructor function. +- [ ] `animals.js` should save `Dog` to a variable. +- [ ] The above code will work as expected. + +
Answer: + +dog.js` fails to export the `Dog` constructor function.
+
Explanation: + +If we don't export the `Dog` function, JS will not know what to assign to `Dog` inside of our `animals.js` file.
@@ -100,17 +106,18 @@ require("./dog"); const dog = new Dog(); ``` - - -

Why will the above code throw an error?

- `dog.js` should export the object `{ Dog: Dog }`. - `dog.js` should export an instance of Dog rather than the Dog constructor function. - `animals.js` should save `require("./dog")` as the constant `Dog`. - The above code will work as expected. - Simply requiring the `dog.js` file will not make the `Dog` constructor function available to us. We need to assign the code that we are importing to a constant `Dog` to be able to invoke the constructor function. -
-
+Why will the above code throw an error? +- [ ] `dog.js` should export the object `{ Dog: Dog }`. +- [ ] `dog.js` should export an instance of Dog rather than the Dog constructor function. +- [ ] `animals.js` should save `require("./dog")` as the constant `Dog`. +- [ ] The above code will work as expected. + +
Answer: + +`animals.js` should save `require("./dog")` as the constant `Dog`.
+
Explanation: +Simply requiring the `dog.js` file will not make the `Dog` constructor function available to us. We need to assign the code that we are importing to a constant `Dog` to be able to invoke the constructor function.
```javascript @@ -133,13 +140,15 @@ const Dumbo = { Dumbo.greet.call(RyanHall); ``` - - -

Consider the above code. What is logged to the console?

- "phHRRRRRRR my name is Ryan Hall" - "phHRRRRRRR my name is Dumbo" - "Hi, I'm Dumbo, how can I help you?" - "Hi, I'm Ryan Hall, how can I help you?" - `call` is being invoked on the `Dumbo` `greet` method. `greet` gets invoked, but with the new context of `RyanHall`. Therefore `"phHRRRRRRR my name is Ryan Hall"` will get logged to the console because we are invoking `Dumbo`'s `greet` method but `RyanHall` is the new context of `this`. -
-
\ No newline at end of file +Consider the above code. What is logged to the console? +- [ ] "phHRRRRRRR my name is Ryan Hall" +- [ ] "phHRRRRRRR my name is Dumbo" +- [ ] "Hi, I'm Dumbo, how can I help you?" +- [ ] "Hi, I'm Ryan Hall, how can I help you?" + +
Answer: + +"phHRRRRRRR my name is Ryan Hall"
+
Explanation: + +`call` is being invoked on the `Dumbo` `greet` method. `greet` gets invoked, but with the new context of `RyanHall`. Therefore `"phHRRRRRRR my name is Ryan Hall"` will get logged to the console because we are invoking `Dumbo`'s `greet` method but `RyanHall` is the new context of `this`.
\ No newline at end of file diff --git a/javascript/quizzes/jquery.md b/javascript/quizzes/jquery.md index fc6b4c5..b1c4dc1 100644 --- a/javascript/quizzes/jquery.md +++ b/javascript/quizzes/jquery.md @@ -1,16 +1,20 @@ # jQuery Quiz - - -

What is the difference between `document.getElementById("cat")` and `$('#cat')`?

- `document.getElementById("cat")` returns an HTML element and `$('#cat')` returns a jQuery object - `$('#cat')` executes more quickly than `document.getElementById("cat")` - No difference - You need to have JQuery loaded in order to run `$('#cat')`, and you don't for `document.getElementById("cat")` - `document.getElementById` is Vanilla Javascript and will return an HTML Element. `$()` is jquery and will return a jquery object. To use `$()` you have to load jQuery. -
-
+What is the difference between `document.getElementById("cat")` and `$('#cat')`? +- [ ] `document.getElementById("cat")` returns an HTML element and `$('#cat')` returns a jQuery object +- [ ] `$('#cat')` executes more quickly than `document.getElementById("cat")` +- [ ] No difference +- [ ] You need to have JQuery loaded in order to run `$('#cat')`, and you don't for `document.getElementById("cat")` + +
Answer: + +- `document.getElementById("cat")` returns an HTML element and `$('#cat')` returns a jQuery object +- You need to have JQuery loaded in order to run `$('#cat')`, and you don't for `document.getElementById("cat")`
+ +
Explanation: + +`document.getElementById` is Vanilla Javascript and will return an HTML Element. `$()` is jquery and will return a jquery object. To use `$()` you have to load jQuery.
@@ -20,17 +24,19 @@ $('ul.test').on('click', 'li', () => { }) ``` - - -

The above code is part of a script loaded by an html page. Assume that the html page and the rest of the script are syntactically correct and bug-free. What do these lines of code do?

- they alert "!!!" when an `li` inside of a `ul` with class `test` is clicked - they fail silently - they alert "!!!" when an `li` is clicked - they alert "!!!" when an `li` inside of a `ul` is clicked - they alert "!!!" when a `ul` is clicked - We are setting up and event listener on a `ul` with a class `test`. It is listening for the "click" event on a child `li` element. When the click happens, the callback will be invoked which will alert "!!!" -
-
+The above code is part of a script loaded by an html page. Assume that the html page and the rest of the script are syntactically correct and bug-free. What do these lines of code do? +- [ ] they alert "!!!" when an `li` inside of a `ul` with class `test` is clicked +- [ ] they fail silently +- [ ] they alert "!!!" when an `li` is clicked +- [ ] they alert "!!!" when an `li` inside of a `ul` is clicked +- [ ] they alert "!!!" when a `ul` is clicked + +
Answer: + +they alert "!!!" when an `li` inside of a `ul` with class `test` is clicked
+
Explanation: + +We are setting up and event listener on a `ul` with a class `test`. It is listening for the "click" event on a child `li` element. When the click happens, the callback will be invoked which will alert "!!!"
@@ -40,40 +46,46 @@ $( () => { }); ``` - - -

The above code is in a .js file that is loaded by a website. When will the alert happen?

- When the file is fully loaded - When the document has loaded, including its dependencies - As soon as it is interpreted or compiled - When a user clicks anywhere on the page - We do not specify an element on the page, therefore the callback will be invoked as soon as the document and its dependencies have loaded. This is shorthand for the `$(document).ready(cb)` which will only execute `cb` once the page DOM is "ready" to receive JS code to execute. -
-
- - - - - -

If you wanted to select all of the `ul`s of class `abc`, how would you do so using jQuery?

- `$('ul').class('abc')` - `document.getElementById(abc)` - `$('ul.abc')` - `$('ul>abc')` - The `.` inside of a string given to the `$()` as an argument signifies that we are looking for an element based on the class name given. So `$('.hello')` would mean we are looking for elements with a class name of `hello`. `$('li.hello')` would mean we are looking for `li` elements that has a class name of `hello`. -
-
- - - - - -

Fill in the blanks: ______ is the way to access a data attribute that has been set with ______.

- `$li.data("number");`, `$li.data("number", number);` - `$li.data("number", idx);`, `$li.data("number");` - `$li.data("test");`, `$li.data("testing", idx);` - `$li.attr("number", idx);`, `$li.data("number", idx);` - `$li.data("number", idx);`, `$li.data("number", idx);` - `$li.data("number");` will allow us to see what the `"number"` attribute is set to and `$li.data("number", number);` will set the `"number"` attribute to some `number`. -
-
\ No newline at end of file +The above code is in a .js file that is loaded by a website. When will the alert happen? +- [ ] When the file is fully loaded +- [ ] When the document has loaded, including its dependencies +- [ ] As soon as it is interpreted or compiled +- [ ] When a user clicks anywhere on the page + +
Answer: + +When the document has loaded, including its dependencies
+
Explanation: + +We do not specify an element on the page, therefore the callback will be invoked as soon as the document and its dependencies have loaded. This is shorthand for the `$(document).ready(cb)` which will only execute `cb` once the page DOM is "ready" to receive JS code to execute.
+ + + +If you wanted to select all of the `ul`s of class `abc`, how would you do so using jQuery? +- [ ] `$('ul').class('abc')` +- [ ] `document.getElementById(abc)` +- [ ] `$('ul.abc')` +- [ ] `$('ul>abc')` + +
Answer: + +`$('ul.abc')`
+
Explanation: + +The `.` inside of a string given to the `$()` as an argument signifies that we are looking for an element based on the class name given. So `$('.hello')` would mean we are looking for elements with a class name of `hello`. `$('li.hello')` would mean we are looking for `li` elements that has a class name of `hello`.
+ + + +Fill in the blanks: ______ is the way to access a data attribute that has been set with ______. +- [ ] `$li.data("number");`, `$li.data("number", number);` +- [ ] `$li.data("number", idx);`, `$li.data("number");` +- [ ] `$li.data("test");`, `$li.data("testing", idx);` +- [ ] `$li.attr("number", idx);`, `$li.data("number", idx);` +- [ ] `$li.data("number", idx);`, `$li.data("number", idx);` + +
Answer: + +`$li.data("number");`, `$li.data("number", number);`
+
Explanation: + +`$li.data("number");` will allow us to see what the `"number"` attribute is set to and `$li.data("number", number);` will set the `"number"` attribute to some `number`.
\ No newline at end of file diff --git a/javascript/quizzes/js_dom_api.md b/javascript/quizzes/js_dom_api.md index 406abcf..d9574e1 100644 --- a/javascript/quizzes/js_dom_api.md +++ b/javascript/quizzes/js_dom_api.md @@ -23,17 +23,19 @@ ``` - - -

When mousing over the `Leopold` `li` element, what are the `currentTarget` and `target`, respectively?

- `ul.joycean-corgis` and `
  • Leopold
  • `
    - `
  • Leopold
  • ` and `ul.joycean-corgis`
    - `ul.joycean-corgis` and `ul.joycean-corgis` - `
  • Leopold
  • ` and `
  • Leopold
  • `
    - There's only a `delegateTarget` and a `currentTarget` - `target` will be the element that triggered the event - in this case, the `
  • ` element that was moused over. `currentTarget` is the element that the event listener is assigned to, which is the `ul.joycean-corgis` - - +When mousing over the `Leopold` `li` element, what are the `currentTarget` and `target`, respectively? +- [ ] `ul.joycean-corgis` and `
  • Leopold
  • ` +- [ ] `
  • Leopold
  • ` and `ul.joycean-corgis` +- [ ] `ul.joycean-corgis` and `ul.joycean-corgis` +- [ ] `
  • Leopold
  • ` and `
  • Leopold
  • ` +- [ ] There's only a `delegateTarget` and a `currentTarget` + +
    Answer: + +`ul.joycean-corgis` and `
  • Leopold
  • `
    +
    Explanation: + +`target` will be the element that triggered the event - in this case, the `
  • ` element that was moused over. `currentTarget` is the element that the event listener is assigned to, which is the `ul.joycean-corgis`
  • @@ -59,17 +61,19 @@ ``` - - -

    The code is the same as in question 1. When mousing over `Leopold` `li` element, what element(s) generate(s) the event?

    - `ul.joycean-corgis` and `
  • Leopold
  • `
    - `
  • Leopold
  • `
    - `ul.joycean-corgis` - the `aside` - No element generates the event. - The `
  • ` is the element that was moused over and is therefore the element that generates the event. - - +The code is the same as in question 1. When mousing over `Leopold` `li` element, what element(s) generate(s) the event? +- [ ] `ul.joycean-corgis` and `
  • Leopold
  • ` +- [ ] `
  • Leopold
  • ` +- [ ] `ul.joycean-corgis` +- [ ] the `aside` +- [ ] No element generates the event. + +
    Answer: + +`
  • Leopold
  • `
    +
    Explanation: + +The `
  • ` is the element that was moused over and is therefore the element that generates the event.
  • @@ -92,17 +96,19 @@ ``` - - -

    This code has a different `script`. What would be the `currentTarget`, `target`, and `delegateTarget`, respectively, when mousing over `Leopold` `li` element?

    - `
  • Leopold
  • `, `
  • Leopold
  • `, `
  • Leopold
  • `
    - `ul.joycean-corgis`, `
  • Leopold
  • `, `ul.joycean-corgis`
    - `
  • Leopold
  • `, `
  • Leopold
  • `, `ul.joycean-corgis`
    - `ul.joycean-corgis`, NONE, `ul.joycean-corgis` - `ul.joycean-corgis`, `ul.joycean-corgis`, `ul.joycean-corgis` - We are mousing over `
  • Leopold
  • ` therefore that is the `target`. The event listener is assigned to the `'li'` elements that are children to `ul.joycean-corgis`, therefor the `currentTarget` is the `'li'` that was moused over (`
  • Leopold
  • `). The `delegateTarget` will be the element that the event listener was originally attached, `'ul.joycean-corgis'`.
    -
    -
    +This code has a different `script`. What would be the `currentTarget`, `target`, and `delegateTarget`, respectively, when mousing over `Leopold` `li` element? +- [ ] `
  • Leopold
  • `, `
  • Leopold
  • `, `
  • Leopold
  • ` +- [ ] `ul.joycean-corgis`, `
  • Leopold
  • `, `ul.joycean-corgis` +- [ ] `
  • Leopold
  • `, `
  • Leopold
  • `, `ul.joycean-corgis` +- [ ] `ul.joycean-corgis`, NONE, `ul.joycean-corgis` +- [ ] `ul.joycean-corgis`, `ul.joycean-corgis`, `ul.joycean-corgis` + +
    Answer: + +`
  • Leopold
  • `, `
  • Leopold
  • `, `ul.joycean-corgis`
    +
    Explanation: + +We are mousing over `
  • Leopold
  • ` therefore that is the `target`. The event listener is assigned to the `'li'` elements that are children to `ul.joycean-corgis`, therefor the `currentTarget` is the `'li'` that was moused over (`
  • Leopold
  • `). The `delegateTarget` will be the element that the event listener was originally attached, `'ul.joycean-corgis'`.
    @@ -137,28 +143,32 @@ ``` - - -

    In what order would the alerts appear if you were to click on the text "Labyrinth"?

    - 'Nom Nom', 'Uh Oh', 'Escape!' - 'Escape!', 'Uh Oh', 'Nom Nom' - 'Escape!', 'Uh Oh' - 'Uh Oh', 'Escape!' - No events are triggered - The event will start at the element that we clicked on and then bubble up. -
    -
    - - - - - -

    What's the data type of the return value of `window.history`?

    - String - Array - Hash - NaN - Object - Everything in JS is an object! `window.history` is an object with different properties like `length`. -
    -
    \ No newline at end of file +In what order would the alerts appear if you were to click on the text "Labyrinth"? +- [ ] 'Nom Nom', 'Uh Oh', 'Escape!' +- [ ] 'Escape!', 'Uh Oh', 'Nom Nom' +- [ ] 'Escape!', 'Uh Oh' +- [ ] 'Uh Oh', 'Escape!' +- [ ] No events are triggered + +
    Answer: + +'Uh Oh', 'Escape!'
    +
    Explanation: + +The event will start at the element that we clicked on and then bubble up.
    + + + +What's the data type of the return value of `window.history`? +- [ ] String +- [ ] Array +- [ ] Hash +- [ ] NaN +- [ ] Object + +
    Answer: + +Object
    +
    Explanation: + +Everything in JS is an object! `window.history` is an object with different properties like `length`.
    \ No newline at end of file diff --git a/javascript/quizzes/js_fundamentals.md b/javascript/quizzes/js_fundamentals.md index 1a5aa71..99e4da8 100644 --- a/javascript/quizzes/js_fundamentals.md +++ b/javascript/quizzes/js_fundamentals.md @@ -1,17 +1,19 @@ ## Javascript Fundamentals Quiz `1 * 34 + '0' - 100` - - -

    What does the above code evaluate to in Node?

    - `"240"` - `-66` - `240` - `NaN` - The code will throw an error; you cannot add or subtract a string with an integer. - `1 * 34` evaluates to 34. `34 + '0'` coerces the number `34` into the string `'34'` and then adds the two strings together giving you `'340'`. Subtracting `100` off of the string `'340'` coerces the string `'340'` into a number and then subtracts 100 giving us `240`. -
    -
    +What does the above code evaluate to in Node? +- [ ] `"240"` +- [ ] `-66` +- [ ] `240` +- [ ] `NaN` +- [ ] The code will throw an error; you cannot add or subtract a string with an integer. + +
    Answer: + +`240`
    +
    Explanation: + +`1 * 34` evaluates to 34. `34 + '0'` coerces the number `34` into the string `'34'` and then adds the two strings together giving you `'340'`. Subtracting `100` off of the string `'340'` coerces the string `'340'` into a number and then subtracts 100 giving us `240`.
    @@ -21,17 +23,19 @@ function isStringZero (item) { } ``` - - -

    We want the above function to return true only if the item is equal to the string `"0"`. - Why will the code not work?

    - The code will throw an error because `item` is not declared as a `var` - Because the `==` operation is used instead of `===`, `isStringZero` will return true for the integer 0. - The code will throw an error because javascript does not have a `==` operator. - The function will work as expected. - Double equals (`==`) does not check for type matching. JS will attempt to coerce the two things into a common type before comparing them. Tripe equals (`===`) will verify that the two things being compared have the same type without doing any coercing. -
    -
    +We want the above function to return true only if the item is equal to the string `"0"`. + Why will the code not work? +- [ ] The code will throw an error because `item` is not declared as a `var` +- [ ] Because the `==` operation is used instead of `===`, `isStringZero` will return true for the integer 0. +- [ ] The code will throw an error because javascript does not have a `==` operator. +- [ ] The function will work as expected. + +
    Answer: + +Because the `==` operation is used instead of `===`, `isStringZero` will return true for the integer 0.
    +
    Explanation: + +Double equals (`==`) does not check for type matching. JS will attempt to coerce the two things into a common type before comparing them. Tripe equals (`===`) will verify that the two things being compared have the same type without doing any coercing.
    @@ -51,16 +55,18 @@ function printNSkip3(n) { } ``` - - -

    We want a function that prints each number from 0 to `n`, except those which are divisible by 3. Why will the above function not work as planned?

    - The function will not actually skip numbers divisible by 3 since the `break` will only break out of the `if` statement. - The `break` statement will break out of the entire while loop and should be replaced with `continue`, so that it instead carries on to the next iteration. - There is a syntax error in the `if` statement - javascript `if` statements must include an `else` clause. - The function will work as expected. - `break` kicks us out of the loop completely instead of simply skipping an iteration! -
    -
    +We want a function that prints each number from 0 to `n`, except those which are divisible by 3. Why will the above function not work as planned? +- [ ] The function will not actually skip numbers divisible by 3 since the `break` will only break out of the `if` statement. +- [ ] The `break` statement will break out of the entire while loop and should be replaced with `continue`, so that it instead carries on to the next iteration. +- [ ] There is a syntax error in the `if` statement - javascript `if` statements must include an `else` clause. +- [ ] The function will work as expected. + +
    Answer: + +The `break` statement will break out of the entire while loop and should be replaced with `continue`, so that it instead carries on to the next iteration.
    +
    Explanation: + +`break` kicks us out of the loop completely instead of simply skipping an iteration!
    @@ -78,16 +84,18 @@ function testFn () { } ``` - - -

    What is logged when we run `testFn`?

    - "ramen", "ramen" - "ramen", "pizza" - "pizza", "pizza" - The code will throw an error because `favoriteFood` was defined using `const` and cannot be overwritten in the scope of the function. - When the first `console.log` runs, JS will look inside of the current scope for a variable called `favoriteFood`. One exists in that scope itself so the `"ramen"` gets printed out. When the second `console.log` runs, JS does the same thing and finds a `favoriteFood` variable that is set to `"pizza"`. -
    -
    +What is logged when we run `testFn`? +- [ ] "ramen", "ramen" +- [ ] "ramen", "pizza" +- [ ] "pizza", "pizza" +- [ ] The code will throw an error because `favoriteFood` was defined using `const` and cannot be overwritten in the scope of the function. + +
    Answer: + +"ramen", "pizza"
    +
    Explanation: + +When the first `console.log` runs, JS will look inside of the current scope for a variable called `favoriteFood`. One exists in that scope itself so the `"ramen"` gets printed out. When the second `console.log` runs, JS does the same thing and finds a `favoriteFood` variable that is set to `"pizza"`.
    ```js @@ -114,17 +122,21 @@ function testFn () { [1,2,3,4,5].forEach((el) => console.log(el)); ``` - - -

    Which of the following are valid ways to iterate over and print out each element in an array?

    - A - B - C - D - E - `forEach` takes a callback as an argument. The callback needs to take an argument for the element in the array well be looking at. There are no blocks in JS! -
    -
    +Which of the following are valid ways to iterate over and print out each element in an array? +- [ ] A +- [ ] B +- [ ] C +- [ ] D +- [ ] E + +
    Answer: + +- B +- D +- E
    +
    Explanation: + +`forEach` takes a callback as an argument. The callback needs to take an argument for the element in the array well be looking at. There are no blocks in JS!
    @@ -145,12 +157,16 @@ function dogTrick(dogName, trickVerb) { }; ``` - - -

    Consider the above code. The anonymous function that prints out the dog trick is a:

    - closure - function that captures `dogName` and `trickVerb` - callback - The anonymous function passed into the invokation of `times` closes over and captures the `dogName` and `trickVerb` arguments so that JS knows what they are inside of a new context. The function is also a callback because it is being passed in as an argument. The `times` function will handle invoking the function that we are passing in. -
    -
    +Consider the above code. The anonymous function that prints out the dog trick is a: +- [ ] closure +- [ ] function that captures `dogName` and `trickVerb` +- [ ] callback + +
    Answer: + +- closure +- function that captures `dogName` and `trickVerb` +- callback
    +
    Explanation: + +The anonymous function passed into the invokation of `times` closes over and captures the `dogName` and `trickVerb` arguments so that JS knows what they are inside of a new context. The function is also a callback because it is being passed in as an argument. The `times` function will handle invoking the function that we are passing in.
    diff --git a/javascript/quizzes/object_oriented_js.md b/javascript/quizzes/object_oriented_js.md index 2b1daaa..8ed8588 100644 --- a/javascript/quizzes/object_oriented_js.md +++ b/javascript/quizzes/object_oriented_js.md @@ -11,15 +11,17 @@ colors("red", "orange", "yellow", "green", "blue", "purple"); ``` - - -

    What will the above code output?

    - "red", "orange", "yellow", "green", "blue", "purple" - "yellow", "green", "blue", "purple" - "red", "orange" - `...moreColors` will grab the "rest" of the arguments given to the function invokation. In this case, `color1` will be "red", `color2` will be "orange", and `moreColors` will be an array of `["yellow", "green", "blue", "purple"]` -
    -
    +What will the above code output? +- [ ] "red", "orange", "yellow", "green", "blue", "purple" +- [ ] "yellow", "green", "blue", "purple" +- [ ] "red", "orange" + +
    Answer: + +"yellow", "green", "blue", "purple"
    +
    Explanation: + +`...moreColors` will grab the "rest" of the arguments given to the function invokation. In this case, `color1` will be "red", `color2` will be "orange", and `moreColors` will be an array of `["yellow", "green", "blue", "purple"]`
    @@ -33,17 +35,19 @@ const bunnyNames = ["Peter", "Bancroft", "Hopper"]; ``` - - -

    Consider the above code. What is a correct way to pass `bunnyNames` to the `bunnies` function?

    - `bunnies(...bunnyNames);` - `bunnyNames.bunnies();` - `bunnies().bind(bunnyNames);` - `bunnies(*bunnyNames);` - `bunnies(bunnyNames.join(", "));` - Since `bunnies` takes three separate arguments and `bunnyNames` is an array, we need to get all of the items in the array to be passed indivually into `bunnies`. For this, we can use the Spread Operator to "spread" out the array. -
    -
    +Consider the above code. What is a correct way to pass `bunnyNames` to the `bunnies` function? +- [ ] `bunnies(...bunnyNames);` +- [ ] `bunnyNames.bunnies();` +- [ ] `bunnies().bind(bunnyNames);` +- [ ] `bunnies(*bunnyNames);` +- [ ] `bunnies(bunnyNames.join(", "));` + +
    Answer: + +`bunnies(...bunnyNames);`
    +
    Explanation: + +Since `bunnies` takes three separate arguments and `bunnyNames` is an array, we need to get all of the items in the array to be passed indivually into `bunnies`. For this, we can use the Spread Operator to "spread" out the array.
    @@ -56,17 +60,19 @@ }; ``` - - -

    Which of the above lines of code will complete the `inherits` function?

    - `this.__proto__ = Surrogate.prototype;` - `Parent.prototype = new Surrogate();` - `this.prototype = new Surrogate();` - `parent.__proto__ = this.prototype;` - Nothing, the function works as-is - We need to set the prototype of `this` based on the inheritance we have created with Surrogate. We assign `this.prototype` to a an instance of Surrogate so that *A)* we don't have create an instance of the Parent in case that constructor is an expensive one or there are specific arguments required that we would have to worry about and *B)* so that we are able to write fuctions on our own class and not have them also added to the Parent class (which would happen if we were to just set `self.prototype = Parent.prototype`). -
    -
    +Which of the above lines of code will complete the `inherits` function? +- [ ] `this.__proto__ = Surrogate.prototype;` +- [ ] `Parent.prototype = new Surrogate();` +- [ ] `this.prototype = new Surrogate();` +- [ ] `parent.__proto__ = this.prototype;` +- [ ] Nothing, the function works as-is + +
    Answer: + +`this.prototype = new Surrogate();`
    +
    Explanation: + +We need to set the prototype of `this` based on the inheritance we have created with Surrogate. We assign `this.prototype` to a an instance of Surrogate so that *A)* we don't have create an instance of the Parent in case that constructor is an expensive one or there are specific arguments required that we would have to worry about and *B)* so that we are able to write fuctions on our own class and not have them also added to the Parent class (which would happen if we were to just set `self.prototype = Parent.prototype`).
    @@ -82,33 +88,37 @@ ctx.fillRect(10, 10, 100, 100); ``` - - -

    What is the correct way set the rectangle's fill color to yellow?

    - `ctx.color = "yellow";` - `ctx.color = yellow;` - `ctx.fillStyle = "yellow";` - `ctx.fillStyle = yellow;` - `ctx.fillColor = "yellow";` - `ctx.fillColor = yellow;` - `fillStyle` is the attribute we need to set and it accepts strings for the colors. -
    -
    +What is the correct way set the rectangle's fill color to yellow? +- [ ] `ctx.color = "yellow";` +- [ ] `ctx.color = yellow;` +- [ ] `ctx.fillStyle = "yellow";` +- [ ] `ctx.fillStyle = yellow;` +- [ ] `ctx.fillColor = "yellow";` +- [ ] `ctx.fillColor = yellow;` + +
    Answer: + +`ctx.fillStyle = "yellow";`
    +
    Explanation: +`fillStyle` is the attribute we need to set and it accepts strings for the colors.
    - - -

    What is webpack?

    - a module bundler - a transpiler - Chrome devtools extension - a lightweight JavaScript server - an asynchronous function - Yep! It's a bundler to allow us to use different files for our code but get it all bundled up into one file that the browser is able to handle. -
    -
    + +What is webpack? +- [ ] a module bundler +- [ ] a transpiler +- [ ] Chrome devtools extension +- [ ] a lightweight JavaScript server +- [ ] an asynchronous function + +
    Answer: + +a module bundler
    +
    Explanation: + +Yep! It's a bundler to allow us to use different files for our code but get it all bundled up into one file that the browser is able to handle.
    @@ -137,16 +147,18 @@ Dog.prototype.bark = function() { }; ``` - - -

    When defining a method that can be called on any instance of the `Dog` class, which of these two options is preferable and why?

    - `I` is preferable because it encapsulates all Dog methods within the Dog object. - `II` is preferable because it does not create a new version of the `bark` function for each dog instance that is created. - `I` is preferable because it can be called directly on a dog (e.g. `fido.bark()`), whereas `II` must be called on the dog's prototype (e.g. `dog.prototype.bark()`). - They are both equally good. - `I` would create a whole new version of the `bark` method every time we create a new instance of a Dog. -
    -
    +When defining a method that can be called on any instance of the `Dog` class, which of these two options is preferable and why? +- [ ] `I` is preferable because it encapsulates all Dog methods within the Dog object. +- [ ] `II` is preferable because it does not create a new version of the `bark` function for each dog instance that is created. +- [ ] `I` is preferable because it can be called directly on a dog (e.g. `fido.bark()`), whereas `II` must be called on the dog's prototype (e.g. `dog.prototype.bark()`). +- [ ] They are both equally good. + +
    Answer: + +`II` is preferable because it does not create a new version of the `bark` function for each dog instance that is created.
    +
    Explanation: + +`I` would create a whole new version of the `bark` method every time we create a new instance of a Dog.
    @@ -154,13 +166,15 @@ Dog.prototype.bark = function() { let ernest = new Dog("ernest", "corgi mix"); ``` - - -

    Consider the above. What does `ernest.__proto__` point to?

    - `dog.proto` - `Dog.proto` - `Dog.__proto__` - `Dog.prototype` - `__proto__` is a property that points to the object used in the lookup chain. In this case, it will be the `Dog.prototype` object. -
    -
    \ No newline at end of file +Consider the above. What does `ernest.__proto__` point to? +- [ ] `dog.proto` +- [ ] `Dog.proto` +- [ ] `Dog.__proto__` +- [ ] `Dog.prototype` + +
    Answer: + +`Dog.prototype`
    +
    Explanation: + +`__proto__` is a property that points to the object used in the lookup chain. In this case, it will be the `Dog.prototype` object.
    \ No newline at end of file diff --git a/javascript/quizzes_originals/ajax.md b/javascript/quizzes_originals/ajax.md new file mode 100644 index 0000000..e0c7cd2 --- /dev/null +++ b/javascript/quizzes_originals/ajax.md @@ -0,0 +1,122 @@ +# AJAX Quiz + + + +

    What is the response data type of an AJAX request?

    + XML + JSON + YAML + text + The type specified by the request + You can specify what type of response you want! +
    +
    + + + +

    What is the default request type in an AJAX request?

    + GET + POST + PATCH + PUT + DELETE + Yep, it's GET! +
    +
    + +```js +const fetchSuccess = kittens => { + /* ... */ +}; +const fetchKittens = () => fetch("/kittens"); + +fetchKittens().then(fetchSuccess); +``` + + + +

    After making the above AJAX request, when will `fetchSuccess` be called?

    + Whenever the request receives a response + After the request is made, but before a response is received + When the request receives a response with a 300-level status code + When the request receives a response with a 200-level status code + Never + `fetchSuccess` will be invoked when the AJAX call has resolved (returned a response with a 200-level status code). +
    +
    + + + +

    True or False: An AJAX request is an HTTP request.

    + False + True + Yep! An AJAX request dispatches an HTTP request. +
    +
    + +```js +1. promise.then(firstFulfilled).then(secondFulfilled).catch(rejected) + +2. promise.then(firstFulfilled, rejected).then(secondFulfilled) + +3. promise.then(firstFulfilled, rejected).catch(error) +``` + + + +

    In what cases will `rejected` run?

    + `rejected` will run in 2 and 3 if `promise` fails but not in 1. + `rejected` will run in 1 and 2 if `secondFulfilled` fails. + All three will run `rejected` if either `promise` or `firstFulfilled` fail. + All three will run `rejected` if `promise` fails. + In all three of the above scenarios the rejected callback will run if the promise fails! In Case 1, `catch` will run the callback given to it if any of the promise objects are rejected. In Case 2, after `promise` is complete, `firstFulfilled` will get invoked if the `promise` returned a status of resolved. `rejected` will get invoked if the `promise` returned a status of `rejected`. Case 3 is the same explanation as Case 2! In Cases 2 and 3, `rejected` will run ONLY if `promise` fails. Once `promise` succeeds, `firstFulfilled` (passed as the "Success Callback", i.e., the first argument to the `.then`) will run and `rejected` (passed as the "Rejected Callback", i.e., the second argument to the `.then`) will not. There has to be an error callback (second argument) in the next `.then` to catch `firstFulfilled` failing or a `.catch` anywhere later in the chain. So in Case 2 if `firstFulfilled` fails nothing will catch it, but in Case 3, `error` would catch it. +
    +
    + +```js +function getAnswers(questions) { + count = 0 + responses = [] + while (count < questions.length) { + answer = await rl.question(questions[count++]); + responses.push(answer); + } + responses +} +``` + + + +

    Consider the above function that takes in an array of questions and returns an array of corresponding answers. If `rl.question` is an asynchronous function that waits for user input, what is the problem with the code above?

    + `rl.question` needs to be inside a `.then`. + Nothing: it will run without error. + `answer` will always be a Promise instead of the actual answer. + It will produce a `Syntax Error` because `await` is an `Unexpected reserved word`. + It will produce a `Syntax Error` because `getAnswers` is not designated as an `async` function. `await` can only be used inside `async` functions (and in a few top-level situations). +
    +
    + +```js +async function asyncPrint() { + await setTimeout(() => console.log("Second!"), 0); +} + +function printThings() { + console.log("First!"); + asyncPrint(); + console.log("Third!"); +} + +printThings(); +``` + + + +

    If you run the code above, in what order will the `console.log`s appear?

    + First! Second! Third! + First! Third! Second! + Second! First! Third! + It will produce an error because `asyncPrint` is not designated as an `async` function when it is invoked inside `printThings`. + `await` only pauses the internal execution of the function in which it is invoked, so the use of `await` in `asyncPrint` will NOT effectively turn `printThings` into a synchronous function. When `asyncPrint` hits the `await`, it will pause its internal execution and cede control back to `printThings` while its Promise resolves. Once the Promise resolves, then `asyncPrint` will resume executing any subsequent code, although there's nothing left to execute after the `await` in `asyncPrint`. In other words, the `await` isn't really doing anything useful here. +
    +
    diff --git a/javascript/quizzes_originals/event_loop.md b/javascript/quizzes_originals/event_loop.md new file mode 100644 index 0000000..d428500 --- /dev/null +++ b/javascript/quizzes_originals/event_loop.md @@ -0,0 +1,145 @@ +# Event Loop Quiz + +```javascript +const cat = { + age: 5, + + ageOneYear () { + this.age += 1; + } +}; + +const catAging = cat.ageOneYear; +catAging(); +``` + + + +

    Consider the above code. Assuming we run the code in the browser, what is the value of `this` when we call `catAging`?

    + `window` + `cat` + `undefined` + `catAging` will throw an error - you cannot save a function as a constant. + We are creating a POJO on the window assigned to the variable named `cat`. Our POJO has an attribute called `ageOneYear`. Because the context of `this` inside of the POJO will be the window, the conext of `this` will also be the window inside of the `ageOneYear` function. +
    +
    + + + +```javascript + +reader.question("What is your name?", function (answer) { + console.log(`Hello ${ answer }!`); +}); + +console.log("Last program line"); +``` + + + +

    Consider the above code. `reader.question` is an asynchronous function. In what order are the above statements logged?

    + "What is your name?", `Hello ${ answer }!`, "Last program line" + `Hello ${ answer }!`, "Last program line", "What is your name?" + "Last program line", "What is your name?", `Hello ${ answer }!` + "What is your name?", "Last program line", `Hello ${ answer }!` + Because `reader.question` will not invoke the callback given to it (which console logs `Hello ${answer}!`) until the user enters an answer. Because `reader.question` is asynchronous, JS doesn't wait around for that answer before continuing to execute the rest of the code. Therefore, `"Last program line"` will be printed before the answer the user types in will be logged. +
    +
    + + + + + +

    Which of the following is NOT executed asynchronously?

    + `reader.question` + `Array.prototype.forEach` + `window.setInterval` + `window.setTimeout` + `forEach` will go ahead and start iterating and JS will not move on to other code until the `forEach` is complete. +
    +
    + + + +```javascript +// ./dog.js +function Dog () { + // ... +}; + +// ./animals.js +const Dog = require('./dog.js'); + +const dog = new Dog(); +``` + + + +

    Why will the above code throw an error?

    + `dog.js` fails to export the `Dog` constructor function. + `animals.js` should import an instance of `Dog` rather than the `Dog` constructor function. + `animals.js` should save `Dog` to a variable. + The above code will work as expected. + If we don't export the `Dog` function, JS will not know what to assign to `Dog` inside of our `animals.js` file. +
    +
    + + + +```javascript +// ./dog.js +function Dog () { + // ... +}; + +module.exports = Dog; + +// ./animals.js +require("./dog"); + +const dog = new Dog(); +``` + + + +

    Why will the above code throw an error?

    + `dog.js` should export the object `{ Dog: Dog }`. + `dog.js` should export an instance of Dog rather than the Dog constructor function. + `animals.js` should save `require("./dog")` as the constant `Dog`. + The above code will work as expected. + Simply requiring the `dog.js` file will not make the `Dog` constructor function available to us. We need to assign the code that we are importing to a constant `Dog` to be able to invoke the constructor function. +
    +
    + + + +```javascript +const RyanHall = { + name: "Ryan Hall", + + greet () { + console.log(`Hi, I'm ${this.name}, how can I help you?`) + } +}; + +const Dumbo = { + name: "Dumbo", + + greet () { + console.log(`phHRRRRRRR my name is ${this.name}.`); + } +}; + +Dumbo.greet.call(RyanHall); +``` + + + +

    Consider the above code. What is logged to the console?

    + "phHRRRRRRR my name is Ryan Hall" + "phHRRRRRRR my name is Dumbo" + "Hi, I'm Dumbo, how can I help you?" + "Hi, I'm Ryan Hall, how can I help you?" + `call` is being invoked on the `Dumbo` `greet` method. `greet` gets invoked, but with the new context of `RyanHall`. Therefore `"phHRRRRRRR my name is Ryan Hall"` will get logged to the console because we are invoking `Dumbo`'s `greet` method but `RyanHall` is the new context of `this`. +
    +
    \ No newline at end of file diff --git a/javascript/quizzes_originals/jquery.md b/javascript/quizzes_originals/jquery.md new file mode 100644 index 0000000..fc6b4c5 --- /dev/null +++ b/javascript/quizzes_originals/jquery.md @@ -0,0 +1,79 @@ +# jQuery Quiz + + + + +

    What is the difference between `document.getElementById("cat")` and `$('#cat')`?

    + `document.getElementById("cat")` returns an HTML element and `$('#cat')` returns a jQuery object + `$('#cat')` executes more quickly than `document.getElementById("cat")` + No difference + You need to have JQuery loaded in order to run `$('#cat')`, and you don't for `document.getElementById("cat")` + `document.getElementById` is Vanilla Javascript and will return an HTML Element. `$()` is jquery and will return a jquery object. To use `$()` you have to load jQuery. +
    +
    + + + +```javascript +$('ul.test').on('click', 'li', () => { + alert('!!!'); +}) +``` + + + +

    The above code is part of a script loaded by an html page. Assume that the html page and the rest of the script are syntactically correct and bug-free. What do these lines of code do?

    + they alert "!!!" when an `li` inside of a `ul` with class `test` is clicked + they fail silently + they alert "!!!" when an `li` is clicked + they alert "!!!" when an `li` inside of a `ul` is clicked + they alert "!!!" when a `ul` is clicked + We are setting up and event listener on a `ul` with a class `test`. It is listening for the "click" event on a child `li` element. When the click happens, the callback will be invoked which will alert "!!!" +
    +
    + + + +```javascript +$( () => { + alert('!!!') +}); +``` + + + +

    The above code is in a .js file that is loaded by a website. When will the alert happen?

    + When the file is fully loaded + When the document has loaded, including its dependencies + As soon as it is interpreted or compiled + When a user clicks anywhere on the page + We do not specify an element on the page, therefore the callback will be invoked as soon as the document and its dependencies have loaded. This is shorthand for the `$(document).ready(cb)` which will only execute `cb` once the page DOM is "ready" to receive JS code to execute. +
    +
    + + + + + +

    If you wanted to select all of the `ul`s of class `abc`, how would you do so using jQuery?

    + `$('ul').class('abc')` + `document.getElementById(abc)` + `$('ul.abc')` + `$('ul>abc')` + The `.` inside of a string given to the `$()` as an argument signifies that we are looking for an element based on the class name given. So `$('.hello')` would mean we are looking for elements with a class name of `hello`. `$('li.hello')` would mean we are looking for `li` elements that has a class name of `hello`. +
    +
    + + + + + +

    Fill in the blanks: ______ is the way to access a data attribute that has been set with ______.

    + `$li.data("number");`, `$li.data("number", number);` + `$li.data("number", idx);`, `$li.data("number");` + `$li.data("test");`, `$li.data("testing", idx);` + `$li.attr("number", idx);`, `$li.data("number", idx);` + `$li.data("number", idx);`, `$li.data("number", idx);` + `$li.data("number");` will allow us to see what the `"number"` attribute is set to and `$li.data("number", number);` will set the `"number"` attribute to some `number`. +
    +
    \ No newline at end of file diff --git a/javascript/quizzes_originals/js_dom_api.md b/javascript/quizzes_originals/js_dom_api.md new file mode 100644 index 0000000..406abcf --- /dev/null +++ b/javascript/quizzes_originals/js_dom_api.md @@ -0,0 +1,164 @@ +# Javascript DOM API Quiz + + +```html + + +
      +
    • Leopold
    • +
    • Stephen
    • +
    • Molly
    • + + +
    + + +``` + + + +

    When mousing over the `Leopold` `li` element, what are the `currentTarget` and `target`, respectively?

    + `ul.joycean-corgis` and `
  • Leopold
  • `
    + `
  • Leopold
  • ` and `ul.joycean-corgis`
    + `ul.joycean-corgis` and `ul.joycean-corgis` + `
  • Leopold
  • ` and `
  • Leopold
  • `
    + There's only a `delegateTarget` and a `currentTarget` + `target` will be the element that triggered the event - in this case, the `
  • ` element that was moused over. `currentTarget` is the element that the event listener is assigned to, which is the `ul.joycean-corgis` + + + + + +```html + + +
      +
    • Leopold
    • +
    • Stephen
    • +
    • Molly
    • + + +
    + + +``` + + + +

    The code is the same as in question 1. When mousing over `Leopold` `li` element, what element(s) generate(s) the event?

    + `ul.joycean-corgis` and `
  • Leopold
  • ` + `
  • Leopold
  • `
    + `ul.joycean-corgis` + the `aside` + No element generates the event. + The `
  • ` is the element that was moused over and is therefore the element that generates the event. + + + + + +```html + + +
      +
    • Leopold
    • +
    • Stephen
    • +
    • Molly
    • + + +
    + + +``` + + + +

    This code has a different `script`. What would be the `currentTarget`, `target`, and `delegateTarget`, respectively, when mousing over `Leopold` `li` element?

    + `
  • Leopold
  • `, `
  • Leopold
  • `, `
  • Leopold
  • ` + `ul.joycean-corgis`, `
  • Leopold
  • `, `ul.joycean-corgis`
    + `
  • Leopold
  • `, `
  • Leopold
  • `, `ul.joycean-corgis`
    + `ul.joycean-corgis`, NONE, `ul.joycean-corgis` + `ul.joycean-corgis`, `ul.joycean-corgis`, `ul.joycean-corgis` + We are mousing over `
  • Leopold
  • ` therefore that is the `target`. The event listener is assigned to the `'li'` elements that are children to `ul.joycean-corgis`, therefor the `currentTarget` is the `'li'` that was moused over (`
  • Leopold
  • `). The `delegateTarget` will be the element that the event listener was originally attached, `'ul.joycean-corgis'`.
    +
    +
    + + + +```html +
    + Knossos +
    + Labyrinth +
    + Minotaur +
    + Labyrinth +
    + Knossos +
    + + +``` + + + +

    In what order would the alerts appear if you were to click on the text "Labyrinth"?

    + 'Nom Nom', 'Uh Oh', 'Escape!' + 'Escape!', 'Uh Oh', 'Nom Nom' + 'Escape!', 'Uh Oh' + 'Uh Oh', 'Escape!' + No events are triggered + The event will start at the element that we clicked on and then bubble up. +
    +
    + + + + + +

    What's the data type of the return value of `window.history`?

    + String + Array + Hash + NaN + Object + Everything in JS is an object! `window.history` is an object with different properties like `length`. +
    +
    \ No newline at end of file diff --git a/javascript/quizzes_originals/js_fundamentals.md b/javascript/quizzes_originals/js_fundamentals.md new file mode 100644 index 0000000..1a5aa71 --- /dev/null +++ b/javascript/quizzes_originals/js_fundamentals.md @@ -0,0 +1,156 @@ +## Javascript Fundamentals Quiz + +`1 * 34 + '0' - 100` + + +

    What does the above code evaluate to in Node?

    + `"240"` + `-66` + `240` + `NaN` + The code will throw an error; you cannot add or subtract a string with an integer. + `1 * 34` evaluates to 34. `34 + '0'` coerces the number `34` into the string `'34'` and then adds the two strings together giving you `'340'`. Subtracting `100` off of the string `'340'` coerces the string `'340'` into a number and then subtracts 100 giving us `240`. +
    +
    + + + +```javascript +function isStringZero (item) { + return item == "0"; +} +``` + + + +

    We want the above function to return true only if the item is equal to the string `"0"`. + Why will the code not work?

    + The code will throw an error because `item` is not declared as a `var` + Because the `==` operation is used instead of `===`, `isStringZero` will return true for the integer 0. + The code will throw an error because javascript does not have a `==` operator. + The function will work as expected. + Double equals (`==`) does not check for type matching. JS will attempt to coerce the two things into a common type before comparing them. Tripe equals (`===`) will verify that the two things being compared have the same type without doing any coercing. +
    +
    + + + +```javascript +function printNSkip3(n) { + let i = 0; + + while(i < n) { + if(i % 3 === 0) { + i += 1; + break; + } + + console.log(i); + i += 1; + } +} +``` + + + +

    We want a function that prints each number from 0 to `n`, except those which are divisible by 3. Why will the above function not work as planned?

    + The function will not actually skip numbers divisible by 3 since the `break` will only break out of the `if` statement. + The `break` statement will break out of the entire while loop and should be replaced with `continue`, so that it instead carries on to the next iteration. + There is a syntax error in the `if` statement - javascript `if` statements must include an `else` clause. + The function will work as expected. + `break` kicks us out of the loop completely instead of simply skipping an iteration! +
    +
    + + + +```javascript + +function testFn () { + const favoriteFood = "pizza"; + + if (true) { + let favoriteFood = "ramen"; + console.log(favoriteFood); + } + + console.log(favoriteFood); +} +``` + + + +

    What is logged when we run `testFn`?

    + "ramen", "ramen" + "ramen", "pizza" + "pizza", "pizza" + The code will throw an error because `favoriteFood` was defined using `const` and cannot be overwritten in the scope of the function. + When the first `console.log` runs, JS will look inside of the current scope for a variable called `favoriteFood`. One exists in that scope itself so the `"ramen"` gets printed out. When the second `console.log` runs, JS does the same thing and finds a `favoriteFood` variable that is set to `"pizza"`. +
    +
    + + +```js + // A. With an anonymous callback that takes no arguments + [1,2,3,4,5].forEach(function() { + console.log(el); + }); + + // B. With an anonymous callback that takes an element as an argument + [1,2,3,4,5].forEach(function(el) { + console.log(el); + }); + + // C. Using a block + [1,2,3,4,5].forEach( |el| { console.log(el); } ); + + // D. Passing in a pre-defined function as a callback + function printEl (el) { + console.log(el); + }; + [1,2,3,4,5].forEach(printEl); + + // E. Passing in an arrow function that takes an argument + [1,2,3,4,5].forEach((el) => console.log(el)); +``` + + + +

    Which of the following are valid ways to iterate over and print out each element in an array?

    + A + B + C + D + E + `forEach` takes a callback as an argument. The callback needs to take an argument for the element in the array well be looking at. There are no blocks in JS! +
    +
    + + + +```js +function times(n, callback) { + let i = 0; + + while (i < n) { + callback(); + i++; + } +}; + +function dogTrick(dogName, trickVerb) { + times(3, function () { + console.log(`${dogName} is ${trickVerb}!`); + }); +}; +``` + + + +

    Consider the above code. The anonymous function that prints out the dog trick is a:

    + closure + function that captures `dogName` and `trickVerb` + callback + The anonymous function passed into the invokation of `times` closes over and captures the `dogName` and `trickVerb` arguments so that JS knows what they are inside of a new context. The function is also a callback because it is being passed in as an argument. The `times` function will handle invoking the function that we are passing in. +
    +
    diff --git a/javascript/quizzes_originals/object_oriented_js.md b/javascript/quizzes_originals/object_oriented_js.md new file mode 100644 index 0000000..2b1daaa --- /dev/null +++ b/javascript/quizzes_originals/object_oriented_js.md @@ -0,0 +1,166 @@ +# Object Oriented Javascript Quiz + + +```js + function colors(color1, color2, ...moreColors) { + moreColors.forEach(color => { + console.log(color); + }); + } + + colors("red", "orange", "yellow", "green", "blue", "purple"); +``` + + + +

    What will the above code output?

    + "red", "orange", "yellow", "green", "blue", "purple" + "yellow", "green", "blue", "purple" + "red", "orange" + `...moreColors` will grab the "rest" of the arguments given to the function invokation. In this case, `color1` will be "red", `color2` will be "orange", and `moreColors` will be an array of `["yellow", "green", "blue", "purple"]` +
    +
    + + + +```js + function bunnies(bunny1, bunny2, bunny3) { + console.log(`${bunny1} likes carrots`); + console.log(`${bunny2} likes hopping`); + console.log(`${bunny3} likes burrowing`); + } + + const bunnyNames = ["Peter", "Bancroft", "Hopper"]; +``` + + + +

    Consider the above code. What is a correct way to pass `bunnyNames` to the `bunnies` function?

    + `bunnies(...bunnyNames);` + `bunnyNames.bunnies();` + `bunnies().bind(bunnyNames);` + `bunnies(*bunnyNames);` + `bunnies(bunnyNames.join(", "));` + Since `bunnies` takes three separate arguments and `bunnyNames` is an array, we need to get all of the items in the array to be passed indivually into `bunnies`. For this, we can use the Spread Operator to "spread" out the array. +
    +
    + + + +```js + Function.prototype.inherits = function(Parent) { + function Surrogate() {} + Surrogate.prototype = Parent.prototype; + // what goes here??? + this.prototype.constructor = this; + }; +``` + + + +

    Which of the above lines of code will complete the `inherits` function?

    + `this.__proto__ = Surrogate.prototype;` + `Parent.prototype = new Surrogate();` + `this.prototype = new Surrogate();` + `parent.__proto__ = this.prototype;` + Nothing, the function works as-is + We need to set the prototype of `this` based on the inheritance we have created with Surrogate. We assign `this.prototype` to a an instance of Surrogate so that *A)* we don't have create an instance of the Parent in case that constructor is an expensive one or there are specific arguments required that we would have to worry about and *B)* so that we are able to write fuctions on our own class and not have them also added to the Parent class (which would happen if we were to just set `self.prototype = Parent.prototype`). +
    +
    + + + +```html + +``` + +```js + const canvas = document.getElementById("canvas"); + const ctx = canvas.getContext("2d"); + + // your code here + ctx.fillRect(10, 10, 100, 100); +``` + + + +

    What is the correct way set the rectangle's fill color to yellow?

    + `ctx.color = "yellow";` + `ctx.color = yellow;` + `ctx.fillStyle = "yellow";` + `ctx.fillStyle = yellow;` + `ctx.fillColor = "yellow";` + `ctx.fillColor = yellow;` + `fillStyle` is the attribute we need to set and it accepts strings for the colors. +
    +
    + + + + + + +

    What is webpack?

    + a module bundler + a transpiler + Chrome devtools extension + a lightweight JavaScript server + an asynchronous function + Yep! It's a bundler to allow us to use different files for our code but get it all bundled up into one file that the browser is able to handle. +
    +
    + + + +```js +// I. + +function Dog (name, breed) { + this.name = name; + this.breed = breed; + + this.bark = function() { + console.log(`${this.name} says woof!`); + }; +}; + + +// II. + +function Dog (name, breed) { + this.name = name; + this.breed = breed; +}; + +Dog.prototype.bark = function() { + console.log(`${this.name} says woof!`); +}; +``` + + + +

    When defining a method that can be called on any instance of the `Dog` class, which of these two options is preferable and why?

    + `I` is preferable because it encapsulates all Dog methods within the Dog object. + `II` is preferable because it does not create a new version of the `bark` function for each dog instance that is created. + `I` is preferable because it can be called directly on a dog (e.g. `fido.bark()`), whereas `II` must be called on the dog's prototype (e.g. `dog.prototype.bark()`). + They are both equally good. + `I` would create a whole new version of the `bark` method every time we create a new instance of a Dog. +
    +
    + + + +```js +let ernest = new Dog("ernest", "corgi mix"); +``` + + + +

    Consider the above. What does `ernest.__proto__` point to?

    + `dog.proto` + `Dog.proto` + `Dog.__proto__` + `Dog.prototype` + `__proto__` is a property that points to the object used in the lookup chain. In this case, it will be the `Dog.prototype` object. +
    +
    \ No newline at end of file