Strategies
High-Level
- Unless you have an async/await statement, Javascript is really just running code line by line
- Remember that Javascript will not wait for a line's output before moving on
- Think of the order in which things load. Are you referencing an item before it is loaded, or before it is changed?
Tools
- Have DevTools open when developing
- Write
console.log() statements before the line of the error.
- Log relevant information - whether it's a variable, or function output
- A single line of code may reference multiple variables or functions. Separately log both the variable, and function
- Use labels to distinguish what you are logging - i.e.
console.log('value of x', x)
- Use
console.table() to log objects or tabular data
Techniques
- Be mindful of brackets!
{ and [
- When the page isn't behaving as expected, look at the line of the error by DevTools
- This doesn't necessarily get to the the root of the problem. The line shown is the most recent place where the error happened.
- However, this is a good starting point and can help you trace the error
- Hunt & trace the issue to its root
- When debugging a loops through an array of many objects (say, more than 10), always slice your array so that reading your log statements is manageable
- Instead of
array.forEach(), or array.map, try array.slice(0,5).forEach or array.slice(0,5).map to just debug the first few elements
- If all else fails, just comment out chunks of code to help isolate the issue
- For example, you may want to comment out an entire function and see if that resolves the error that is appearing. If it does, uncomment it, and start to comment out smaller pieces to isolate the error
- And lastly, you can always copy paste your error message into Google and see what sort of responses are available
- Debugging CSS is a little bit trickier than JS because errors are typically not displayed in the console
- However, CSS is more limited in its syntax. Issues with CSS either stem from (1) your selector or (2) the style property and value you've applied
- However, DevTools Elements lets you clearly see if CSS has been applied to an element. If you don't see your styles applied to an element, you have an issue
- To debug your selector, add a style that is very obvious - like
background: blue - and see if it appears. If it does not, your selector was not chosen properly. Otherwise, it's likely an issue with your style property.
- Use Prettier extension to help with code formatting (so you avoid syntax issues)
Common Issues
- Brackets
{} or parentheses, () causing an unexpected token issue
- Every opening bracket, and parentheses needs a closing bracket or parentheses
- On VS code, if you click on a bracket or parentheses, it will show you the corresponding opening or closing one
- General syntax issue
- If you see a red squiggly line in your VS code editor you have a syntax issue. Look up an example of what you are trying to do and fix up the syntax!