Debugging is the process of removing bugs and errors from your code.
Syntax errors: Stops code from running.
Runtime errors: Where your code has unexpected behaviour.
Logical errors: Where your code doesn't do what you intended.
In the fight against bugs, the console is your best friend.
Following are some of the common bugs we encounter every day.
Missing Parenthesis, strings.
function sum() {
let p = 6;
let q = 3;
return p + q;
}
let ans = sum;
console.log(ans);
Answer
function sum() {
let p = 6;
let q = 3;
return p + q;
}
let ans = sum();
console.log(ans);
Arguments in the Wrong Order.
function raiseToPower(b, e) {
return Math.pow(b, e);
}
let base = 2;
let exp = 3;
let power = raiseToPower(exp, base);
console.log(power);//9
Answer
function raiseToPower(b, e) {
return Math.pow(b, e);
}
let base = 2;
let exp = 3;
let power = raiseToPower(base, exp);
console.log(power);//8
Off By One Error.
Indexing in JS starts at zero, not one, which means the last index is always one less than the length of the item.
let string = "Thisirhgebuggystrig";
let length = string.length;
for (let i = 0; i <= length; i++) {
// loops one too many times at the end
console.log(string[i]);
}
for (let j = 1; j < length; j++) {
// loops one too few times and misses the first character at index 0
console.log(string[j]);
}
for (let k = 0; k < length; k++) {
// This is just right
console.log(string[k]);
}
These are just a fraction of many bugs you will face while learning to code and building projects. However, do not let any bug stop you from coding. The knowledge you gain after finding the solution is worthwhile.
Check out this breathtaking bug story (SE DAILY podcast).
You can find me at Twitter.
This blog is inspired by FreeCodeCamp debugging section.
Top comments (0)