Advertisement
here2share

Common JavaScript Errors

Jan 9th, 2023
901
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. Common JavaScript Errors
  2.  
  3. Syntax errors: These are mistakes in the structure of the code that prevent it from being parsed correctly. Examples include forgetting to close a string or forgetting to add a semicolon at the end of a statement.
  4.  
  5. // Syntax error: Unterminated string literal
  6. console.log("Hello world);
  7.  
  8. // Syntax error: Missing semicolon
  9. const x = 1
  10. const y = 2
  11.  
  12.  
  13.  
  14. Reference errors: These occur when you try to use a variable that has not been defined.
  15.  
  16. // Reference error: foo is not defined
  17. console.log(foo);
  18. Type errors: These occur when you try to perform an operation on the wrong data type.
  19.  
  20. // Type error: Cannot read property 'length' of undefined
  21. const arr = undefined;
  22. console.log(arr.length);
  23.  
  24. // Type error: Cannot use '+' operator to concatenate a string and an object
  25. const obj = {};
  26. console.log("The object is " + obj);
  27. Logic errors: These are mistakes in the logic of the code that prevent it from producing the correct output.
  28.  
  29. // Logic error: The loop should terminate when i is greater than 5, not less than 5
  30. for (let i = 0; i < 5; i++) {
  31.  console.log(i);
  32. }
  33.  
  34. // Logic error: The function should return true if the input is even, not odd
  35. function isEven(num) {
  36.  return num % 2 === 1;
  37. }
  38.  
  39.  
  40.  
  41. Undeclared variables: These are variables that are used without being declared with let, const, or var. In strict mode, this will cause a reference error, but in non-strict mode, the variable will be automatically declared in the global scope.
  42.  
  43. // Reference error in strict mode, or automatic global declaration in non-strict mode
  44. x = 1;
  45. console.log(x);
  46. Forgotten operator precedence: Operators have different precedence levels, and this can affect the order in which they are evaluated. It is important to use parentheses to ensure that the operations are performed in the correct order.
  47.  
  48. // Incorrect result due to operator precedence
  49. const x = 2 + 3 * 4;  // x is 14, not 20
  50.  
  51. // Correct result due to explicit grouping
  52. const x = (2 + 3) * 4;  // x is 20
  53. Misuse of null and undefined: These are special values in JavaScript that represent the absence of a value. It is important to understand the difference between them and use them correctly.
  54.  
  55. // Incorrect comparison of null and undefined
  56. if (x == null) { ... }
  57.  
  58. // Correct comparison of null and undefined
  59. if (x === null || typeof x === 'undefined') { ... }
  60.  
  61.  
  62.  
  63. Misuse of == and ===: In JavaScript, == is the loose equality operator, which performs type coercion (i.e. it converts the operands to the same type before comparing them). === is the strict equality operator, which does not perform type coercion and compares the operands for both value and type. It is generally recommended to use === instead of == to avoid unexpected behavior.
  64.  
  65. // Incorrect result due to type coercion
  66. console.log(1 == '1');  // true
  67.  
  68. // Correct result with strict comparison
  69. console.log(1 === '1');  // false
  70. Off-by-one errors: These are mistakes that occur when you iterate over an array or other data structure and forget to account for the fact that the index starts at 0, rather than 1. This can lead to errors such as accessing an index that is out of bounds, or skipping over elements that should have been processed.
  71.  
  72. // Off-by-one error: The loop will not iterate over the last element of the array
  73. const arr = [1, 2, 3];
  74. for (let i = 0; i <= arr.length; i++) {
  75.  console.log(arr[i]);
  76. }
  77.  
  78. // Correct loop: The loop will iterate over all elements of the array
  79. const arr = [1, 2, 3];
  80. for (let i = 0; i < arr.length; i++) {
  81.  console.log(arr[i]);
  82. }
  83.  
  84.  
  85.  
  86. Misuse of asynchronous code: Asynchronous code is code that runs in the background and does not block the main execution thread. This is often used when working with network requests, file I/O, and other operations that can take a long time to complete. It is important to understand how asynchronous code works and to use it correctly, otherwise you may encounter errors such as callback hell, race conditions, and other issues.
  87.  
  88. // Incorrect handling of asynchronous code: The console.log statement will execute before the timeout is complete
  89. console.log('Starting timeout...');
  90. setTimeout(() => {
  91.  console.log('Timeout complete');
  92. }, 1000);
  93. console.log('Timeout started');
  94.  
  95. // Correct handling of asynchronous code: The console.log statements will execute in the correct order
  96. console.log('Starting timeout...');
  97. setTimeout(() => {
  98.  console.log('Timeout complete');
  99. }, 1000);
  100. console.log('Timeout started');
  101.  
  102.  
  103.  
  104. Misuse of scope: In JavaScript, variables have different levels of scope, which determines where they can be accessed in the code. It is important to understand how scope works and to use it correctly, otherwise you may encounter errors such as undefined variables or unexpected behavior.
  105.  
  106. // Incorrect use of scope: The inner function has access to the i variable from the outer function, which can lead to unexpected behavior
  107. function outer() {
  108.  for (let i = 0; i < 5; i++) {
  109.    setTimeout(() => {
  110.      console.log(i);
  111.    }, 1000);
  112.  }
  113. }
  114.  
  115. // Correct use of scope: The inner function has access to a copy of the i variable from the outer function, which avoids unexpected behavior
  116. function outer() {
  117.  for (let i = 0; i < 5; i++) {
  118.    (function(i) {
  119.      setTimeout(() => {
  120.        console.log(i);
  121.      }, 1000);
  122.    })(i);
  123.  }
  124. }
  125.  
  126.  
  127.  
  128. Misuse of this: In JavaScript, this is a special keyword that refers to the current object. Its value is determined by the context in which it is used, and it can be confusing to understand how it works. It is important to understand how this works and to use it correctly, otherwise you may encounter errors such as undefined values or unexpected behavior.
  129.  
  130. // Incorrect use of this: The inner function will not have access to the expected value of this
  131. const obj = {
  132.  prop: 'Hello',
  133.  method: function() {
  134.    setTimeout(function() {
  135.      console.log(this.prop);  // undefined
  136.    }, 1000);
  137.  }
  138. };
  139.  
  140. // Correct use of this: The inner function will have access to the expected value of this
  141. const obj = {
  142.  prop: 'Hello',
  143.  method: function() {
  144.    const self = this;
  145.    setTimeout(function() {
  146.      console.log(self.prop);  // 'Hello'
  147.    }, 1000);
  148.  }
  149. };
  150.  
  151.  
  152.  
  153. Misuse of functions: Functions are a fundamental concept in JavaScript, and it is important to understand how they work and how to use them correctly. Mistakes with functions can include forgetting to add a return statement, forgetting to pass the correct number or type of arguments, or misunderstanding how the arguments object works.
  154.  
  155. // Incorrect use of functions: The function will not return the expected result
  156. function add(x, y) {
  157.  console.log(x + y);
  158. }
  159. const result = add(1, 2);  // undefined
  160.  
  161. // Correct use of functions: The function will return the expected result
  162. function add(x, y) {
  163.  return x + y;
  164. }
  165. const result = add(1, 2);  // 3
  166.  
  167.  
  168.  
  169. Misuse of objects: Objects are a fundamental data type in JavaScript, and it is important to understand how they work and how to use them correctly. Mistakes with objects can include forgetting to use the new keyword when creating an object, misunderstanding how object properties work, or misusing the this keyword.
  170.  
  171. // Incorrect use of objects: The object will not be created correctly
  172. function MyObject(name) {
  173.  this.name = name;
  174. }
  175. const obj = MyObject('hello');  // obj is undefined
  176.  
  177. // Correct use of objects: The object will be created correctly
  178. function MyObject(name) {
  179.  this.name = name;
  180. }
  181. const obj = new MyObject
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement