Into
In part 1 we went over some common syntax and reference errors that you may come across as a beginning programmer. In part 2 we will go over some more common errors along with some less common but equally important ones.
Forgetting to Close Parenthesis on a Function Call
When you create a function that does not take any arguments, a common error is to forget the parenthesis when you call that function:
function printNumberFive(){
let x = 2
let y = 3
return x + y;
}
let notFive = printNumberFive; // will set notFive equal to a function but not 5
let five = printNumberFive(); // will set five equal to return x + y of function
Passing Arguments in the Wrong Order
Another common error when dealing with functions is passing/calling the arguments in the incorrect order:
function groceryList (array,name){
return `Hi my name is ${name} and these are my groceries I need to buy ${array}`
}
groceryList("Dan",["Bacon","Eggs","Milk"])
//'Hi my name is Bacon,Eggs,Milk and these are my groceries I need to buy Dan'
Just remember the arguments must be called in the same order that they are passed in:
function groceryList (array,name){
return `Hi my name is ${name} and these are my groceries I need to buy ${array}`
}
groceryList(["Bacon","Eggs","Milk"],"Dan")
//'Hi my name is Dan and these are my groceries I need to buy Bacon,Eggs,Milk'
Off By One Error When Indexing
Off by one errors typically occur when looping over indices or targeting a specific index in a string or array. Javascript indices start at zero and a common mistake is to assume they start at 1, leading to the index you are targeting to be off by one:
let myArray = [1,2,5,10,20,40]
for(var i = 0; i <= myArray.length; i++){
console.log(myArray[i])
}
// Loops one to many times at the end because there are only 5 indices but i <= myArray.length will attempt to print out 6 indices.
for(var i = 1; i < myArray.length; i++){
console.log(myArray[i])
}
// Does not print the first number in the array
for(var i = 0; i < myArray.length; i++){
console.log(myArray[i])
}
// Correctly prints all the numbers in the array
Conclusion
Knowing these common errors can be a huge time saver. If there are other common errors I missed feel free to comment below, I would love to hear them.
Top comments (0)