Week 4 Day 4
New Terms
- Return Statement
- Break Statement
- Continue Statement
- Try Statement
- Catch Statement
- Finally Statement
- Finally Block
- Throw Statement
Return Statement
The return statement is like the exit door of a functionâitâs how a function hands back its result to the calling code. When a function executes a return statement, it immediately ends the function and passes the specified value to wherever the function was called. This value can be anythingâlike numbers, strings, or even other functions!
Break Statement
The break statement is the âstop signâ for loops or switch cases. When the break is executed, it instantly terminates the current loop or switch block, even if there are still iterations or conditions left to evaluate. Itâs a powerful tool for controlling loop flow when a specific condition is met.
Continue Statement
In contrast to break, the continue statement doesnât terminate the loopâit just skips over the current iteration and moves to the next one. Itâs often used when you want to avoid certain conditions and keep iterating.
Try Statement
The try statement is the starting point of error handling in JavaScript. It lets you write code that might cause an error and âwrap it upâ in a try block. If something goes wrong, the catch statement will step in to handle the error, keeping your application from crashing unexpectedly.
Catch Statement
The catch statement works hand-in-hand with try. When an error occurs inside the try block, the code jumps into the catch block where you can handle the errorâwhether itâs logging it, displaying a message, or trying a different solution.
Finally Statement
No matter what happens, the finally block will always execute after a try-catch sequenceâwhether an error was thrown or not. Itâs perfect for cleanup tasks like closing files, releasing resources, or resetting states.
Finally Block
The finally block is a section of code that you can add after catch in a try-catch-finally structure. Itâs guaranteed to execute after the try block, no matter what happensâwhether an error is thrown or the code runs smoothly. You typically use it to clean up after your operations.
Throw Statement
The throw statement is your way of manually throwing an error when something goes wrong in your code. You can throw a variety of objects, but typically itâs used with an Error object to create a more controlled, predictable failure.