Exceptions and Stack Traces
An exception gives a return value that can be used to deal with an error. If you were to call a function that didn't exsist: unicorn(); you might get an error like: ReferenceError: unicorn is not defined
A stack trace shows the methods or function calls that lead to the point where the error occured.
Testing and Debugging
Strict Mode
You can use strict mode to make sure you write good quality code. You can do this by adding the following line to the top of your js file: 'use strict'; You can also use it in just a function by putting it in the first line of the function. Modules use strict mode by default.
Debugging in the Browser
You can use the alert() method to help you debug by placing it in different parts of your code. Here's an example:
function amIOldEnough(age){
if (age < 12) {
alert(age);
return 'No, sorry.';
} else if (age < 18) {
return 'Only if you are accompanied by an adult.';
}
else {
return 'Yep, come on in!';
}
}
Another way to debug is the use the console.
function amIOldEnough(age){
console.log(age);
if (age < 12) {
console.log(`In the if with ${age}`);
return 'No, sorry.';
} else if (age < 18) {
console.log(`In the else-if with ${age}`);
return 'Only if you are accompanied by an adult.';
} else {
console.log(`In the else with ${age}`);
return 'Yep, come on in!';
}
}
If you add the debugger keyword to your code, you can create a breakpoint. This will also allow you to see the value of your variables.
Exceptions
If you use the throw statement, the program will stop. This is how you throw an error object: throw new Error('Something has gone badly wrong!');
You can also have try, catch, and finally which tell the program what to do if an error occurs. The finally block will always occur.
function imaginarySquareRoot(number) {
'use strict';
let answer;
try {
answer = String(squareRoot(number));
} catch(error) {
answer = squareRoot(-number)+"i";
} finally {
return `+ or - ${answer}`;
}
}
Test Driven Development
- Write tests (that initially fail)
- Write code to pass the tests
- Refactor the code
- Test refactored code
- Write more tests for new features