diff --git a/curriculum/challenges/english/25-front-end-development/lecture-debugging-techniques/6733aa9b006d29f4d11307a5.md b/curriculum/challenges/english/25-front-end-development/lecture-debugging-techniques/6733aa9b006d29f4d11307a5.md index b17cee5c3f2..414e8470d66 100644 --- a/curriculum/challenges/english/25-front-end-development/lecture-debugging-techniques/6733aa9b006d29f4d11307a5.md +++ b/curriculum/challenges/english/25-front-end-development/lecture-debugging-techniques/6733aa9b006d29f4d11307a5.md @@ -10,6 +10,64 @@ dashedName: what-are-some-examples-of-common-javascript-errors Watch the video lecture and answer the questions below. +# --transcript-- + +What are some examples of common JavaScript errors? + +As you've been programming in JavaScript, you've inevitably run into error messages. Understanding common error messages will help you debug more effectively and develop into a stronger programmer. The four common types of error messages are `SyntaxError`, `ReferenceError`, `TypeError`, and `RangeError`. + +A `SyntaxError` happens when you write something incorrectly in your code, like missing a parenthesis, or a bracket. Think of it like a grammar mistake in a sentence. Here is a common mistake developers make when creating arrays: + +```js +const arr = ["Beau", "Quincy" "Tom"] +``` + +Each array element needs to be separated by a comma otherwise it will result in an error message. + +The second common JavaScript error is a `ReferenceError`. There are several types of `ReferenceError`s, triggered in different ways. The first type of `ReferenceError` would be not defined variables. + +```js +console.log(price); +``` + +In this example, we are trying to log the `price` variable to the console but it hasn’t been defined. This is will result in a `ReferenceError`. + +Another example of a `ReferenceError` is trying to access a variable, declared with `let` or `const`, before it has been defined: + +```js +console.log(b); +const b = 50; +``` + +The example above will result in a `Cannot access 'b' before initialization` error. + +The third common error would be a `TypeError`. These errors occur when you try to perform an operation on the wrong type. Here is an example of trying to use the `map` method on an object: + +```js +const developerObj = { + name: "Jessica", + country: "USA", + isEmployed: true +}; + +developerObj.map() +``` + +This example will result in a `developerObj.map is not a function` error because the `map` method is used for arrays and not objects. + +The last common error we will look at is the `RangeError`. + +A `RangeError` happens when your code tries to use a value that’s outside the range of what JavaScript can handle. Here is an example of trying to assign an invalid index to the length of the array: + +```js +const arr = []; +arr.length = -1; +``` + +Since `-1` is not a valid index used for arrays, this will result in a `RangeError`. + +As you continue to program in JavaScript, just be aware of these different types of errors you will probably encounter and why they are happening. + # --questions-- ## --text-- diff --git a/curriculum/challenges/english/25-front-end-development/lecture-debugging-techniques/6733bec70d86e13522e98a4f.md b/curriculum/challenges/english/25-front-end-development/lecture-debugging-techniques/6733bec70d86e13522e98a4f.md index 2118071aa6d..ecb35826fe9 100644 --- a/curriculum/challenges/english/25-front-end-development/lecture-debugging-techniques/6733bec70d86e13522e98a4f.md +++ b/curriculum/challenges/english/25-front-end-development/lecture-debugging-techniques/6733bec70d86e13522e98a4f.md @@ -10,6 +10,46 @@ dashedName: how-does-the-throw-statement-work Watch the lecture video and answer the questions below. +# --transcript-- + +How does the `throw` statement work? + +The `throw` statement in JavaScript is used to throw a user defined exception. An exception in programming, is when an unexpected event happens and disrupts the normal flow of the program. + +As programmers it is important to handle these exceptions, so your programs don’t crash unexpectedly when errors occur. Here is the basic syntax for the `throw` statement: + +```js +throw expression; +``` + +The `expression` in this case would be the object or value that represents the exception you want to throw. Examples of this would be the built in exception classes like the `Error`, `TypeError`, or `RangeError` class. Here is an example of using the `throw` statement to throw a `TypeError`: + +```js +function validateNumber(input) { + if (typeof input !== "number") { + throw new TypeError("Expected a number, but received " + typeof input); + } + return input * 2; +} +``` + +In this example, we are checking if the type of `input` is not of type `number`. If not, then we are throwing a `TypeError` with a custom message. Otherwise, the function will return the result of multiplying the `input` by `2`. + +If you wanted to throw a more generic error message, then you can reference the `Error` constructor like this: + +```js +function divide(numerator, denominator) { + if (denominator === 0) { + throw new Error("Cannot divide by zero"); + } + return numerator / denominator; +} +``` + +Here is an example of a function that will check if the denominator is `0`. If that is the case, then it will throw a custom error message saying `Cannot divide by zero`. + +In the next lecture video, we will look at how to throw errors messages within the context of the `try`/`catch` block which is used to gracefully handle exceptions in JavaScript. + # --questions-- ## --text-- diff --git a/curriculum/challenges/english/25-front-end-development/lecture-debugging-techniques/6733becf4b0c353553b9bfa4.md b/curriculum/challenges/english/25-front-end-development/lecture-debugging-techniques/6733becf4b0c353553b9bfa4.md index 191090dd59f..9453aa41350 100644 --- a/curriculum/challenges/english/25-front-end-development/lecture-debugging-techniques/6733becf4b0c353553b9bfa4.md +++ b/curriculum/challenges/english/25-front-end-development/lecture-debugging-techniques/6733becf4b0c353553b9bfa4.md @@ -10,6 +10,58 @@ dashedName: how-does-the-debugger-statement-work Watch the lecture video and answer the questions below. +# --transcript-- + +How does the `debugger` statement work? + +The `debugger` statement is a powerful JavaScript tool that lets you pause your code at a specific line to investigate what's going on in the program. When used correctly, the `debugger` statement can save you a lot of time trying to figure out why something is not working as it should. + +JavaScript executes your code from top to bottom. While JavaScript executes your code and hits a `debugger` statement, it immediately pauses execution at that line. This gives you the chance to inspect variables, check functions, and the flow of of the code in general. + +With that, you can see exactly what is going right or wrong. However, this only happens if your browser's developer tools are open. Otherwise, the `debugger` statement is ignored, and the code continues to run as usual. + +In addition, when you use the `debugger` statement, modern browsers will pause code execution at the specified line. They also allow you to resume execution by clicking the play button, but the page itself does not automatically reload unless manually triggered. + +To use the `debugger` statement, place it at the line in which you want the code execution to pause. Here's an example: + +```js +let firstNumber = 5; +let secondNumber = 10; +debugger; // Code execution pauses here +let sum = firstNumber + secondNumber; +console.log(sum); +``` + +With this example, if you don't have the console open before the code runs and you eventually open it, you'll see `15` in there. While the console is open and you reload the page, the execution is paused for you so you can inspect the code.  + +Here's a more complex example: + +```js +function calculateTotalPrice(price, discountPercentage) { + debugger + let discountAmount = (price * discountPercentage) / 100 + let totalPrice = price - discountAmount + + console.log(`Original Price: ${price}`) + console.log(`Discount Amount: ${discountAmount}`) + console.log(`Total Price after Discount: ${totalPrice}`) + + return totalPrice +} + +let price = 100 +let discount = 15 + +let finalPrice = calculateTotalPrice(price, discount) +console.log(`Final Price: ${finalPrice}`); +``` + +In this example the `debugger` statement is placed at the top of the `calculateTotalPrice`. When the function is called, the function execution will be paused. + +If you reload the page with the console opened, you'll see that the page keeps reloading, confirming that the execution of the code is only paused, not stopped. If you want the execution to continue, you can click the play button. + +As you continue to build out your JavaScript programs, test out the `debugger` statement in your code to see how it can help you better understand the flow of execution, inspect variables in real-time, and quickly identify where things might be going wrong. + # --questions-- ## --text-- diff --git a/curriculum/challenges/english/25-front-end-development/lecture-debugging-techniques/6733bee844600f35c05b8264.md b/curriculum/challenges/english/25-front-end-development/lecture-debugging-techniques/6733bee844600f35c05b8264.md index cc678b11647..66e1929d289 100644 --- a/curriculum/challenges/english/25-front-end-development/lecture-debugging-techniques/6733bee844600f35c05b8264.md +++ b/curriculum/challenges/english/25-front-end-development/lecture-debugging-techniques/6733bee844600f35c05b8264.md @@ -10,6 +10,60 @@ dashedName: how-does-try-catch-finally-work Watch the lecture video and answer the questions below. +# --transcript-- + +How does `try…catch…finally` work? + +In the previous lecture video, you learned how to throw exceptions in your programs. In this lecture video, we will take a look at how to gracefully handle these errors in a `try…catch…finally` block. + +The `try` block is used to wrap code that might throw an error. It acts as a safe space to try something that could fail. + +The `catch` block captures and handles errors that occur in the `try` block. You can use the `Error` object inside `catch` to inspect what went wrong. + +The `finally` block runs after the `try` and `catch` blocks, regardless of whether an error occurred. It’s commonly used for cleanup tasks, such as closing files or releasing resources. + +Here is an example of using a `try…catch` block: + +```js +function processInput(input) { + if (typeof input !== "string") { + throw new TypeError("Input must be a string."); + } + + return input.toUpperCase(); +} + +try { + console.log("Starting to process input..."); + const result = processInput(9); + console.log("Processed result:", result); +} catch (error) { + console.error("Error occurred:", error.message); +} +``` + +In this example, we have a function called `processInput` that first checks if the `input` is not of type `string`. If that is the case, then we throw an error. Otherwise, we return the result of using the `toUpperCase` method on the `input`. + +We call the function inside of a `try` block. Since the function call throws an error, then it will be caught inside the `catch` block and the error message will be displayed in the console. + +The error passed into the `catch` block is an `Error` object which contains information about that error. In this case, we are using the `message` property which displays human readable information to the user. + +We are using the `console.error` because it is designed specifically to log errors. In many modern browsers, the output of `console.error()` appears in red in the console. + +The `finally` statement is executed regardless of if an exception was thrown or not. + +```js +try { + // Code that might throw an error +} catch (error) { + // Code to handle the error +} finally { + // Code that runs regardless of whether an error occurred or not +} +``` + +A good use case for the `finally` statement is if you were working with files. In JavaScript, you can open a file, use a `try` block to write data to the file. If there are any errors, you can use the `catch` to catch those errors. Then use the `finally` statement to close the file. + # --questions-- ## --text-- diff --git a/curriculum/challenges/english/25-front-end-development/lecture-debugging-techniques/6733befb703ca6361da3755b.md b/curriculum/challenges/english/25-front-end-development/lecture-debugging-techniques/6733befb703ca6361da3755b.md index a6d2d7a98da..9010ed62b57 100644 --- a/curriculum/challenges/english/25-front-end-development/lecture-debugging-techniques/6733befb703ca6361da3755b.md +++ b/curriculum/challenges/english/25-front-end-development/lecture-debugging-techniques/6733befb703ca6361da3755b.md @@ -10,6 +10,40 @@ dashedName: what-are-some-examples-of-using-advanced-javascript-debugging-techni Watch the lecture video and answer the questions below. +# --transcript-- + +What are some examples of using advanced JavaScript debugging techniques? + +Debugging your JavaScript programs goes beyond using `console.log()` statements in your code. There are more advanced techniques that make debugging a breeze once you get used to them. Let's go through those more advanced techniques so you'll be happy to debug your JavaScript program once you run into errors. + +The first concept we will take a look at is working with breakpoints. Breakpoints let you pause the execution of your code at a specific line of your choice. After the pause, you can inspect variables, evaluate expressions, and examine the call stack. + +To add a breakpoint to any line in your code in the Chrome browser, open the developer tools and navigate to the Sources tab, open the JavaScript file you want to debug, and click on a line number to set a breakpoint. + +After the execution reaches the breakpoint and stops, you can step through the code by using the icons on the top right corner. You can also add a conditional breakpoint by right-clicking on a line and selecting "Add conditional breakpoint…" + +Now, let’s move on to watching expressions. Watch expressions lets you monitor the values of variables or expressions as the code runs even if they are out of the current scope. + +To add a watch expression, navigate to the Sources tab of the developer tools, look for the watch panel on the right and click the plus (`+`) icon to add it. + +The next concept we will look at is profiling. Profiling helps you identify performance bottlenecks by letting you capture screenshots and record CPU usage, function calls, and execution time. + +To do that for your code, open the Performance tab, click record, and perform the action you want to profile. After you're done executing that action, stop the recording to analyze the results. + +This could be useful if your application is lagging during certain operations. With the profiler, you can see which function or other data in the code consumes the most resources. + +Now, let’s move onto inspecting network requests. Inspecting network requests can help you debug issues related to API requests such as parameter errors, address errors, or server errors. + +To use the Network tab for debugging, open the developer tools and head over to the Network tab, then click on individual requests to see details like headers, responses, and payloads. + +For the last portion of the video, we will focus on `console.table` and `console.dir`. + +`console.table()` displays tabular data as a table in the console. It takes one mandatory argument, which must be an array or an object, and one optional argument to specify which properties or columns to display. + +`console.dir()` on the other hand lets you display an interactive list of the properties of a specified JavaScript object. It outputs a hierarchical listing that can be expanded to see all nested properties. + +Now that you have an expanded toolkit of debugging techniques, put these new skills to the test in your upcoming JavaScript projects. By applying these strategies, you'll be able to identify and resolve issues more efficiently, leading to cleaner, more reliable code. + # --questions-- ## --text--