- Debugging is the process of going through your code, finding any issues, and fixing them.
Issues in code generally come in three forms: syntax errors that prevent your program from running, runtime errors where your code has unexpected behavior, or logical errors where your code doesn't do what you intended.
In these upcoming posts, you'll learn how to use the JavaScript console to debug programs and prevent common issues before they happen.
Using the JavaScript Console to Check the Value of a Variable
- Both Chrome and Firefox have excellent JavaScript consoles, also known as DevTools, for debugging your JavaScript.
- The
console.log()
method, which "prints" the output of what's within its parentheses to the console, will likely be the most helpful debugging tool. Placing it at strategic points in your code can show you the intermediate values of variables. It's good practice to have an idea of what the output should be before looking at what it is. Having check points to see the status of your calculations throughout your code will help narrow down where the problem is. - Ex:
let a = 5;
let b = 1;
a++
let sumAB = a + b;
console.log(sumAB); the console will display 7
console.log(a); console will display 6
Use typeof to Check the Type of a Variable
You can use
typeof
to check the data structure, or type, of a variable. This is useful in debugging when working with multiple data types. If you think you're adding two numbers, but one is actually a string, the results can be unexpected. Type errors can lurk in calculations or function calls. Be careful especially when you're accessing and working with external data in the form of a JavaScript Object Notation (JSON) object.Ex:
console.log(typeof "");
console.log(typeof 0);
console.log(typeof []);
console.log(typeof {});
In order, the console will display the strings
string
,number
,object
, andobject
.JavaScript recognizes six primitive (immutable) data types:
Boolean
,Null
,Undefined
,Number
,String
, andSymbol
(new with ES6) and one type for mutable items:Object
. Note that in JavaScript, arrays are technically a type of object.Other Ex:
let seven = 7;
let three = "3";
console.log(typeof seven); will display number
console.log(typeof three); will display string
Catch Misspelled Variable and Function Names
The
console.log()
andtypeof
methods are the two primary ways to check intermediate values and types of program output. One syntax-level issue that fast typers can commiserate with is the humble spelling error.Transposed, missing, or mis-capitalized characters in a variable or function name will have the browser looking for an object that doesn't exist - and complain in the form of a reference error. Remember JavaScript variable and function names are case-sensitive.
Let's Fix the two spelling errors in the code so the netWorkingCapital calculation works.
let receivables = 10;
let payables = 8;
let netWorkingCapital = recievables - payable;
console.log(`Net working capital is: ${netWorkingCapital}`); will display ReferenceError: recievables is not defined
let receivables = 10;
let payables = 8;
let netWorkingCapital = receivables - payables;
console.log(`Net working capital is: ${netWorkingCapital}`); will display Net working capital is: 2
Catch Unclosed Parentheses, Brackets, Braces and Quotes
- Another syntax error to be aware of is that all opening parentheses, brackets, curly braces, and quotes have a closing pair. Forgetting a piece tends to happen when you're editing existing code and inserting items with one of the pair types. Also, take care when nesting code blocks into others, such as adding a callback function as an argument to a method.
One way to avoid this mistake is as soon as the opening character is typed, immediately include the closing match, then move the cursor back between them and continue coding. Fortunately, most modern code editors generate the second half of the pair automatically.
Let's Fix the two pair errors in the code.
let myArray = [1, 2, 3;
let arraySum = myArray.reduce((previous, current => previous + current);
console.log(`Sum of array values is: ${arraySum}`);
- Answer:
let myArray = [1, 2, 3];
let arraySum = myArray.reduce((previous, current) => previous + current);
console.log(`Sum of array values is: ${arraySum}`); // will display Sum of array values is: 6
The reduce() method reduces an array to a single value. If you’re not familiar with it, the following code shows an example of using the the method:
const array1 = [1, 2, 3, 4];
console.log(array1.reduce((accumulator, currentValue) => accumulator + currentValue)); // expected output: 10
- You can also define the argument to the reduce method as a variable or constant and hand that in to the function.
const array1 = [1, 2, 3, 4];
const reducer = (accumulator, currentValue) => accumulator + currentValue;
// 1 + 2 + 3 + 4
console.log(array1.reduce(reducer)); // expected output: 10
Catch Mixed Usage of Single and Double Quotes
- JavaScript allows the use of both single (
'
) and double ("
) quotes to declare a string. - Having two choices is great when a string has contractions or another piece of text that's in quotes. Just be careful that you don't close the string too early, which causes a syntax error.
- Ex:
const quoteInString = "Randy once said 'I wanna play Rocket League.'";
const incorrectString = 'I've had a perfectly wonderful evening, but this wasn't it.';
- The first one is correct, but the second is incorrect.
- Of course, it is okay to use only one style of quotes. You can escape the quotes inside the string by using the backslash (
\
) escape character:
const allSameQuotes = 'I\'ve had a perfectly wonderful evening, but this wasn\'t it.';
Top comments (0)