{
  "$type": "site.standard.document",
  "content": "Being a javascript programmer is great but we can never avoid the dreaded stack trace! 😡, most of these bugs are just one Google search away from being solved but sometimes Google can't help and you become stuck with this headache-inducing bug, but do not worry because I have some tips that will help you avoid most bugs.\r\n\r\n\r\n### 1. Know your *Sources* and *Sinks*\r\n\r\n![Sink](https://media.giphy.com/media/3o7TKOuX9nFjq3bR5u/giphy.gif)\r\nFirst of all, what are *Sources* and *Sinks*, a **Source** is a process that generates a piece of information and a **Sink** is the consumer of this information. \r\nExample:\r\n\r\n{% runkit %}\r\nfunction doSomething(randomPercentage){\r\n    const percentString = randomPercentage + \"%\";\r\n    console.log(percentString);\r\n}\r\n\r\nconst randomPercentage = Math.random()*100; // Math.random is the Source here.\r\n\r\ndoSomething(randomPercentage); // And the doSomething function is the sink.\r\n{% endrunkit %}\r\n\r\nThis looks very trivial and from the surface, everything looks fine but looks can be deceiving, the function appears to only add a \"%\" at the end of the number and displays the resulting string, But when the code is executed you will get something similar to this `17.64650669753125%`. That does not look good.\r\n\r\nThis is a classic example of what can go wrong if you don't carefully check your sources or sinks.\r\n\r\nThe reason why the percentage is not a whole number comes from the `Math.random` function because it only generates floating point numbers which we did not **Math.floor**. So let's fix that\r\n\r\n{% runkit \r\n\r\nfunction doSomething(randomPercentage){\r\n    const percentString = randomPercentage + \"%\";\r\n    console.log(percentString);\r\n}\r\n\r\n%}\r\nconst randomPercentage = Math.floor(Math.random()*100);\r\n\r\ndoSomething(randomPercentage); // And our sink now receivs correct data.\r\n{% endrunkit %}\r\n\r\nThe main point is to find data used before/by our function and work our way up the stream until we find the point where wrong/unexpected data is generated.\r\n\r\n### 2. Avoid `undefined`\r\n\r\n![Avoid](https://media.giphy.com/media/QA88yMhazfDI4/giphy.gif)\r\n\r\nSometimes we can be lazy and leave some variables undefined and expect that by the time we use them, they will be initialized. In some cases, such code is required but when the time comes to use them, it is best to have a default value.\r\n\r\nExamples\r\n\r\n**Wrong usage.**\r\n\r\n```js\r\n\r\nlet laterUsed;\r\n\r\ndoAsyncTask().then(()=>{\r\n    useVariable(laterUsed); // ❌ It could still be undefined\r\n})\r\n\r\n\r\n```\r\n**Correct usage.**\r\n\r\n```js\r\nlet laterUsed;\r\n\r\ndoAsyncTask().then(()=>{\r\n    useVariable(laterUsed || externalAlternativeValue); \r\n    // ✅ Another value is used when the original value is undefined\r\n})\r\n\r\n```\r\n**Even more correct usage**\r\n\r\n```js\r\ndoAsyncTask()\r\n  .then(result => {\r\n    useVariable(laterUsed)\r\n  })\r\n  .catch(e => {\r\n    // handle whatever happens when doAsyncTask() goes wrong\r\n  })\r\n```\r\n\r\nAnd also, avoid\r\n- communicating between asynchronous processes using global variables.\r\n- using `undefined` to indicate an error state. Or an absence of value.\r\n\r\n### 3. Know your **PASTA!**\r\n\r\n![Pasta](https://media.giphy.com/media/ToMjGpRhf96j23aTc5i/giphy.gif)\r\n\r\nThere are many different ways to write code and these styles have pasta based categorization that you need to understand in order to know which styles to use.\r\n\r\n#### Spaghetti code\r\n\r\nAvoid this, it does not matter that real spaghetti is delicious 😋, spaghetti code is characterized by tangled and messy code without any real structure/pattern *you know.... like spaghetti* and this code style is prone to a lot of bugs which are very hard to solve due to the aforementioned tangled messiness that is the code base.\r\n\r\n\r\n#### Ravioli code\r\n\r\nThis coding style is in a very nice middle ground where the program is broken down into components that work well together but can also function as good on their own. Whether or not you write Ravioli code is based on how your program is structured.\r\n\r\n#### Lasagna code\r\n\r\nThe holy grail of javascript development, well-structured components separated into layers to perform specific tasks through well-defined interfaces. Use this whenever you can because it reduces the risks of bugs and if they occur, they will be confined to a specific layer.\r\n\r\nAnother thing to note is **please use type-checking when necessary.**\r\n\r\n\r\n### 4. Don't do too much at once\r\n\r\n![too much](https://media.giphy.com/media/3ohjV6xeE0OrC6QXq8/giphy.gif)\r\n\r\nSometimes we tend to write a lot of code without testing it each step of the way, this is very dangerous because when an error occurs you can't tell which new code caused this issue and will make you debug parts of your code that you don't need to which wastes time and can be stressing.\r\n\r\nSo each time you add a new feature or decide to route your app data differently, always run the code to make sure that part is okay.\r\n\r\n### 4.5. Use linters\r\n\r\nPlease use linters! They really are good at helping enforce a good coding style and catch errors for you.\r\n\r\n\r\n## Conclusion\r\n\r\nThese are some tips I have for you so you can avoid as many bugs as possible and some of them apply to other languages apart from javascript.\r\n\r\n*Fun fact: I came up with number 4 because I wrote too much code without testing and spent 7 hours trying to debug it*\r\n\r\nThanks to these wonderful people for their great advice.\r\n\r\n{% user jesuszilla_tm %}\r\n\r\n{% user gypsydave5 %}\r\n\r\n## Thanks for reading!!\r\n\r\n*Consider giving me a follow on [Twitter](https://twitter.com/neutrino2211) and you can check out my previous post [here](https://dev.to/neutrino2211/avoiding-weird-javascript-behaviour-true--true--2-but-true--1-pn9)*",
  "description": "Essential tips on how to avoid most javascript bugs",
  "path": "/posts/how-to-avoid-javascript-bugs-31pm",
  "publishedAt": "2019-04-04T20:44:51.000Z",
  "site": "https://blog.mainasara.dev",
  "tags": [
    "beginner",
    "javascript",
    "webdev"
  ],
  "textContent": "Being a javascript programmer is great but we can never avoid the dreaded stack trace! 😡, most of these bugs are just one Google search away from being solved but sometimes Google can't help and you become stuck with this headache-inducing bug, but do not worry because I have some tips that will help you avoid most bugs.\r\n\r\n\r\n### 1. Know your *Sources* and *Sinks*\r\n\r\n![Sink](https://media.giphy.com/media/3o7TKOuX9nFjq3bR5u/giphy.gif)\r\nFirst of all, what are *Sources* and *Sinks*, a **Source** is a process that generates a piece of information and a **Sink** is the consumer of this information. \r\nExample:\r\n\r\n{% runkit %}\r\nfunction doSomething(randomPercentage){\r\n    const percentString = randomPercentage + \"%\";\r\n    console.log(percentString);\r\n}\r\n\r\nconst randomPercentage = Math.random()*100; // Math.random is the Source here.\r\n\r\ndoSomething(randomPercentage); // And the doSomething function is the sink.\r\n{% endrunkit %}\r\n\r\nThis looks very trivial and from the surface, everything looks fine but looks can be deceiving, the function appears to only add a \"%\" at the end of the number and displays the resulting string, But when the code is executed you will get something similar to this `17.64650669753125%`. That does not look good.\r\n\r\nThis is a classic example of what can go wrong if you don't carefully check your sources or sinks.\r\n\r\nThe reason why the percentage is not a whole number comes from the `Math.random` function because it only generates floating point numbers which we did not **Math.floor**. So let's fix that\r\n\r\n{% runkit \r\n\r\nfunction doSomething(randomPercentage){\r\n    const percentString = randomPercentage + \"%\";\r\n    console.log(percentString);\r\n}\r\n\r\n%}\r\nconst randomPercentage = Math.floor(Math.random()*100);\r\n\r\ndoSomething(randomPercentage); // And our sink now receivs correct data.\r\n{% endrunkit %}\r\n\r\nThe main point is to find data used before/by our function and work our way up the stream until we find the point where wrong/unexpected data is generated.\r\n\r\n### 2. Avoid `undefined`\r\n\r\n![Avoid](https://media.giphy.com/media/QA88yMhazfDI4/giphy.gif)\r\n\r\nSometimes we can be lazy and leave some variables undefined and expect that by the time we use them, they will be initialized. In some cases, such code is required but when the time comes to use them, it is best to have a default value.\r\n\r\nExamples\r\n\r\n**Wrong usage.**\r\n\r\n```js\r\n\r\nlet laterUsed;\r\n\r\ndoAsyncTask().then(()=>{\r\n    useVariable(laterUsed); // ❌ It could still be undefined\r\n})\r\n\r\n\r\n```\r\n**Correct usage.**\r\n\r\n```js\r\nlet laterUsed;\r\n\r\ndoAsyncTask().then(()=>{\r\n    useVariable(laterUsed || externalAlternativeValue); \r\n    // ✅ Another value is used when the original value is undefined\r\n})\r\n\r\n```\r\n**Even more correct usage**\r\n\r\n```js\r\ndoAsyncTask()\r\n  .then(result => {\r\n    useVariable(laterUsed)\r\n  })\r\n  .catch(e => {\r\n    // handle whatever happens when doAsyncTask() goes wrong\r\n  })\r\n```\r\n\r\nAnd also, avoid\r\n- communicating between asynchronous processes using global variables.\r\n- using `undefined` to indicate an error state. Or an absence of value.\r\n\r\n### 3. Know your **PASTA!**\r\n\r\n![Pasta](https://media.giphy.com/media/ToMjGpRhf96j23aTc5i/giphy.gif)\r\n\r\nThere are many different ways to write code and these styles have pasta based categorization that you need to understand in order to know which styles to use.\r\n\r\n#### Spaghetti code\r\n\r\nAvoid this, it does not matter that real spaghetti is delicious 😋, spaghetti code is characterized by tangled and messy code without any real structure/pattern *you know.... like spaghetti* and this code style is prone to a lot of bugs which are very hard to solve due to the aforementioned tangled messiness that is the code base.\r\n\r\n\r\n#### Ravioli code\r\n\r\nThis coding style is in a very nice middle ground where the program is broken down into components that work well together but can also function as good on their own. Whether or not you write Ravioli code is based on how your program is structured.\r\n\r\n#### Lasagna code\r\n\r\nThe holy grail of javascript development, well-structured components separated into layers to perform specific tasks through well-defined interfaces. Use this whenever you can because it reduces the risks of bugs and if they occur, they will be confined to a specific layer.\r\n\r\nAnother thing to note is **please use type-checking when necessary.**\r\n\r\n\r\n### 4. Don't do too much at once\r\n\r\n![too much](https://media.giphy.com/media/3ohjV6xeE0OrC6QXq8/giphy.gif)\r\n\r\nSometimes we tend to write a lot of code without testing it each step of the way, this is very dangerous because when an error occurs you can't tell which new code caused this issue and will make you debug parts of your code that you don't need to which wastes time and can be stressing.\r\n\r\nSo each time you add a new feature or decide to route your app data differently, always run the code to make sure that part is okay.\r\n\r\n### 4.5. Use linters\r\n\r\nPlease use linters! They really are good at helping enforce a good coding style and catch errors for you.\r\n\r\n\r\n## Conclusion\r\n\r\nThese are some tips I have for you so you can avoid as many bugs as possible and some of them apply to other languages apart from javascript.\r\n\r\n*Fun fact: I came up with number 4 because I wrote too much code without testing and spent 7 hours trying to debug it*\r\n\r\nThanks to these wonderful people for their great advice.\r\n\r\n{% user jesuszilla_tm %}\r\n\r\n{% user gypsydave5 %}\r\n\r\n## Thanks for reading!!\r\n\r\n*Consider giving me a follow on [Twitter](https://twitter.com/neutrino2211) and you can check out my previous post [here](https://dev.to/neutrino2211/avoiding-weird-javascript-behaviour-true--true--2-but-true--1-pn9)*",
  "title": "How To Avoid Javascript Bugs"
}