{"id":8304,"date":"2020-07-27T08:56:57","date_gmt":"2020-07-27T04:56:57","guid":{"rendered":"https:\/\/techxmedia.com\/?p=8304"},"modified":"2020-07-27T11:31:11","modified_gmt":"2020-07-27T07:31:11","slug":"how-to-write-cleaner-code-with-javascript","status":"publish","type":"post","link":"https:\/\/techxmedia.com\/en\/how-to-write-cleaner-code-with-javascript\/","title":{"rendered":"How to write cleaner code with JavaScript"},"content":{"rendered":"\n<p>Destructuring is one of my favorite tools in JavaScript, in simple terms, destructuring allows you to break down a complex structure (like an array or an object) into simpler parts, though there\u2019s a bit more to it than that.<\/p>\n\n\n\n<p>Let\u2019s see it better in an example:<\/p>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/cdn0.tnwcdn.com\/wp-content\/blogs.dir\/1\/files\/2020\/07\/Screen-Shot-2020-07-21-at-12.29.28-PM.png\" alt=\"\" class=\"wp-image-1307048\"\/><\/figure>\n\n\n\n<p>Now, some people have been using this feature for some time, perhaps while building React apps, but they don\u2019t quite understand it, for others it may be the first time. So I\u2019ll guide you from the start so that by the end of the article we\u2019ll have the same level of understanding.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"destructuring-objects\">Destructuring objects<\/h2>\n\n\n\n<p>In the example above, all the magic happens at the following line:<\/p>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/cdn0.tnwcdn.com\/wp-content\/blogs.dir\/1\/files\/2020\/07\/Screen-Shot-2020-07-23-at-12.28.11-PM.png\" alt=\"\" class=\"wp-image-1307539\"\/><\/figure>\n\n\n\n<p>Now it may seem a bit weird to have those brackets like that on the left side of the assignment, but that\u2019s how we tell JavaScript that we\u2019re destructing an object.<\/p>\n\n\n\n<p>Destructuring on object lets you bind different properties of an object at any depth. Let\u2019s start with an even simpler example:<\/p>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/cdn0.tnwcdn.com\/wp-content\/blogs.dir\/1\/files\/2020\/07\/Screen-Shot-2020-07-23-at-12.28.54-PM.png\" alt=\"\" class=\"wp-image-1307540\"\/><\/figure>\n\n\n\n<p>In the case above, we\u2019re declaring a variable called&nbsp;<code>name<\/code>&nbsp;which will be initialized from the property with the same name in the object&nbsp;<code>me<\/code>, so that when we evaluate the value of&nbsp;<code>name<\/code>&nbsp;we get&nbsp;<code>Juan<\/code>. This same method can be applied to any depth, to which heading back to our example:<\/p>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/cdn0.tnwcdn.com\/wp-content\/blogs.dir\/1\/files\/2020\/07\/Screen-Shot-2020-07-23-at-12.29.07-PM.png\" alt=\"\" class=\"wp-image-1307541\"\/><\/figure>\n\n\n\n<p>For&nbsp;<code>title<\/code>&nbsp;and&nbsp;<code>rating<\/code>&nbsp;it\u2019s exactly the same as we already explained, but in&nbsp;<code>author<\/code>, things are a bit different. When we get to a property which is either an object or an array, we can choose whether to create a variable&nbsp;<code>author<\/code>&nbsp;with a reference to the&nbsp;<code>article.author<\/code>&nbsp;object, or we can do a deep destructuring and get immediate access to the properties of the inner object.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Accessing the object property<\/h2>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/cdn0.tnwcdn.com\/wp-content\/blogs.dir\/1\/files\/2020\/07\/Screen-Shot-2020-07-23-at-12.29.53-PM.png\" alt=\"\" class=\"wp-image-1307542\"\/><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\">Doing a deep or nested destructuring<\/h2>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/cdn0.tnwcdn.com\/wp-content\/blogs.dir\/1\/files\/2020\/07\/Screen-Shot-2020-07-23-at-12.30.07-PM.png\" alt=\"\" class=\"wp-image-1307543\"\/><\/figure>\n\n\n\n<p>Wait, what? If I destructed&nbsp;<code>author<\/code>, why is it not defined? What is going on is actually really simple. When we ask JavaScript to destruct the&nbsp;<code>author<\/code>&nbsp;object, that binding itself is not created and instead we get access to all the&nbsp;<code>author<\/code>&nbsp;properties we selected. So please always remember that.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Spread operator (\u2026)<\/h2>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/cdn0.tnwcdn.com\/wp-content\/blogs.dir\/1\/files\/2020\/07\/Screen-Shot-2020-07-23-at-12.31.33-PM.png\" alt=\"\" class=\"wp-image-1307544\"\/><\/figure>\n\n\n\n<p>Additionally, we can use the spread operator&nbsp;<code>...<\/code>&nbsp;to create an object with all the properties which didn\u2019t get destructed.<\/p>\n\n\n\n<p>If you\u2019re interested in knowing how to do this, check out my previous&nbsp;article on the&nbsp;<a href=\"https:\/\/livecodestream.dev\/post\/2020-05-23-how-to-use-the-spread-operator-in-javascript\/\" target=\"_blank\" rel=\"noreferrer noopener\">Spread Operator in JavaScript<\/a>.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"renaming-properties\">Renaming properties<\/h2>\n\n\n\n<p>One great property of destructing is the ability to choose a different name for the variable to the property we are extracting. Let\u2019s look at the following example:<\/p>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/cdn0.tnwcdn.com\/wp-content\/blogs.dir\/1\/files\/2020\/07\/Screen-Shot-2020-07-23-at-12.31.50-PM.png\" alt=\"\" class=\"wp-image-1307545\"\/><\/figure>\n\n\n\n<p>By using&nbsp;<code>:<\/code>&nbsp;on a property we can provide a new name for it, in our case&nbsp;<code>newName<\/code>. Then we can access that variable in our code. It\u2019s important to notice that a variable with the original property&nbsp;<code>name<\/code>&nbsp;in our case name won\u2019t be defined.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"missing-properties\">Missing properties<\/h2>\n\n\n\n<p>So what would happen if we try to destructure a property that is not defined in our object?<\/p>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/cdn0.tnwcdn.com\/wp-content\/blogs.dir\/1\/files\/2020\/07\/Screen-Shot-2020-07-23-at-12.32.28-PM.png\" alt=\"\" class=\"wp-image-1307546\"\/><\/figure>\n\n\n\n<p>In this case, the variable is created with value&nbsp;<code>undefined<\/code>.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"default-values\">Default values<\/h2>\n\n\n\n<p>Expanding on missing properties, it\u2019s possible to assign a default value for when the property does not exist, let\u2019s see some examples of this:<\/p>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/cdn0.tnwcdn.com\/wp-content\/blogs.dir\/1\/files\/2020\/07\/Screen-Shot-2020-07-23-at-12.33.01-PM.png\" alt=\"\" class=\"wp-image-1307547\"\/><\/figure>\n\n\n\n<p>In the example above we demonstrated some examples of assigning default values to our destructions. The default values are only assigned when the property is&nbsp;<code>undefined<\/code>. If the value of the property is for instance&nbsp;<code>null<\/code>&nbsp;or a&nbsp;<code>string<\/code>&nbsp;the default value won\u2019t be assigned, but the actual value of the property.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"destructuring-arrays-and-iterables\">Destructuring arrays and iterables<\/h2>\n\n\n\n<p>We already saw some examples of destructuring objects, but the same can apply to arrays or iterables in general. Let\u2019s start with an example:<\/p>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/cdn0.tnwcdn.com\/wp-content\/blogs.dir\/1\/files\/2020\/07\/Screen-Shot-2020-07-23-at-12.33.39-PM.png\" alt=\"\" class=\"wp-image-1307548\"\/><\/figure>\n\n\n\n<p>The example is self-explanatory when we need to destruct an array we need to use&nbsp;<code>[]<\/code>&nbsp;instead of&nbsp;<code>{}<\/code>, and we can map each position of the array with a different variable. But there are some nice tricks too.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"skipping-elements\">Skipping elements<\/h2>\n\n\n\n<p>By using the&nbsp;<code>,<\/code>&nbsp;operator, we can skip some elements from the iterable as follows:<\/p>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/cdn0.tnwcdn.com\/wp-content\/blogs.dir\/1\/files\/2020\/07\/Screen-Shot-2020-07-23-at-12.34.06-PM.png\" alt=\"\" class=\"wp-image-1307549\"\/><\/figure>\n\n\n\n<p>Notice how leaving it&nbsp;empty between&nbsp;<code>,<\/code>&nbsp;skips the elements. This may be subtle but it has big consequences in the end&nbsp;results.&nbsp;You can also use the spread operator&nbsp;<code>...<\/code>&nbsp;as follows:<\/p>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/cdn0.tnwcdn.com\/wp-content\/blogs.dir\/1\/files\/2020\/07\/Screen-Shot-2020-07-23-at-12.34.38-PM.png\" alt=\"\" class=\"wp-image-1307550\"\/><\/figure>\n\n\n\n<p>In this case,&nbsp;<code>z<\/code>&nbsp;will&nbsp;get all the values after&nbsp;<code>b<\/code>&nbsp;as an array. Or maybe you have a more specific need, and you want to destruct specific positions in the array, no problem, JavaScript got you covered:<\/p>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/cdn0.tnwcdn.com\/wp-content\/blogs.dir\/1\/files\/2020\/07\/Screen-Shot-2020-07-23-at-12.35.59-PM.png\" alt=\"\" class=\"wp-image-1307551\"\/><\/figure>\n\n\n\n<p>If we destruct an array as if it were an object, we can use the indexes as properties and thus access any position within the array.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"missing-properties-1\">Missing properties<\/h2>\n\n\n\n<p>As was the case of objects, it\u2019s also possible to set default values for undefined elements in the array. Let\u2019s take a look at some examples:<\/p>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/cdn0.tnwcdn.com\/wp-content\/blogs.dir\/1\/files\/2020\/07\/Screen-Shot-2020-07-23-at-12.36.12-PM.png\" alt=\"\" class=\"wp-image-1307552\"\/><\/figure>\n\n\n\n<p>For destructing arrays, it\u2019s also possible to set default values for&nbsp;<code>undefined<\/code>&nbsp; properties, however, it\u2019s not possible to set a default when we have the spread operator&nbsp;<code>...,<\/code>&nbsp;which in the case of&nbsp;<code>undefined<\/code>, will return an empty array.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"swapping-variables\">Swapping variables<\/h2>\n\n\n\n<p>This is a fun use case of destructuring, 2 variables can be swapped in one single expression:<\/p>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/cdn0.tnwcdn.com\/wp-content\/blogs.dir\/1\/files\/2020\/07\/Screen-Shot-2020-07-23-at-12.36.42-PM.png\" alt=\"\" class=\"wp-image-1307553\"\/><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"destructuring-with-computed-properties\">Destructuring with computed properties<\/h2>\n\n\n\n<p>Until now, any time we wanted to destruct the properties of an object, or the elements of an iterable, we used static keys. If we want dynamic keys (as those stored on a variable) we need to use computed properties.<\/p>\n\n\n\n<p>Here\u2019s an example:<\/p>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/cdn0.tnwcdn.com\/wp-content\/blogs.dir\/1\/files\/2020\/07\/Screen-Shot-2020-07-23-at-12.37.18-PM.png\" alt=\"\" class=\"wp-image-1307554\"\/><\/figure>\n\n\n\n<p>Pretty awesome right! By using a variable between&nbsp;<code>[]<\/code>, we can evaluate its value before doing the assignment, and thus it\u2019s possible to do dynamic destructuring.However, it\u2019s mandatory to provide a name for this new variable.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"destructuring-function-arguments\">Destructuring function arguments<\/h2>\n\n\n\n<p>Destructing variables can be placed anywhere where we can declare variables. For example by using&nbsp;<code>let<\/code>,&nbsp;<code>const<\/code>&nbsp;or&nbsp;<code>var<\/code>, but it\u2019s also possible to deconstruct in function arguments. Here\u2019s a simple example of the concept:<\/p>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/cdn0.tnwcdn.com\/wp-content\/blogs.dir\/1\/files\/2020\/07\/Screen-Shot-2020-07-23-at-12.37.39-PM.png\" alt=\"\" class=\"wp-image-1307555\"\/><\/figure>\n\n\n\n<p>As you can see, it\u2019s very simple and elegant and uses all the same rules we\u2019ve previously discussed.<\/p>\n\n\n\n<p>Destructuring may seem awkward at the beginning, but once you get used to it, there\u2019s no turning back. It can really help your code be more readable.<\/p>\n\n\n\n<p><em>This\u00a0<\/em><a href=\"https:\/\/livecodestream.dev\/post\/2020-07-15-write-cleaner-code-by-using-javascript-destructuring\/\" target=\"_blank\" rel=\"noreferrer noopener\"><em>article<\/em><\/a><em>\u00a0was originally published on\u00a0<\/em><a href=\"https:\/\/livecodestream.dev\/\" target=\"_blank\" rel=\"noreferrer noopener\"><em>Live Code Stream<\/em><\/a><em>\u00a0by\u00a0<\/em><a href=\"https:\/\/www.linkedin.com\/in\/bajcmartinez\/\" target=\"_blank\" rel=\"noreferrer noopener\"><em>Juan Cruz Martinez<\/em><\/a>,<em>\u00a0founder and publisher of Live Code Stream, entrepreneur, developer, author, speaker, and doer of things. You can follow Juan on <a href=\"https:\/\/techxmedia.com\/tag\/twitter\/\">Twitter<\/a>\u00a0<a href=\"https:\/\/twitter.com\/bajcmartinez\" target=\"_blank\" rel=\"noreferrer noopener\">here<\/a>.\u00a0<\/em><\/p>\n\n\n\n<p><a href=\"https:\/\/livecodestream.dev\/subscribe\" target=\"_blank\" rel=\"noreferrer noopener\"><em>Live Code Stream<\/em><\/a><em>&nbsp;is also available as a free weekly newsletter. Sign up for updates on everything related to programming, AI, and computer science in general.<\/em><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Destructuring is one of my favorite tools in JavaScript, in [&hellip;]<\/p>\n","protected":false},"author":40,"featured_media":8307,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"inline_featured_image":false,"_monsterinsights_skip_tracking":false,"_monsterinsights_sitenote_active":false,"_monsterinsights_sitenote_note":"","_monsterinsights_sitenote_category":0,"footnotes":""},"categories":[1],"tags":[640],"contributor":[],"class_list":["post-8304","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-other-tech-events","tag-twitter"],"featured_image_src":"https:\/\/techxmedia.com\/en\/wp-content\/uploads\/2020\/07\/Untitled-design-17-796x417-1.png","author_info":{"display_name":"Techx Admin","author_link":"https:\/\/techxmedia.com\/en\/author\/techxadmin\/"},"aioseo_notices":[],"_links":{"self":[{"href":"https:\/\/techxmedia.com\/en\/wp-json\/wp\/v2\/posts\/8304","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/techxmedia.com\/en\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/techxmedia.com\/en\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/techxmedia.com\/en\/wp-json\/wp\/v2\/users\/40"}],"replies":[{"embeddable":true,"href":"https:\/\/techxmedia.com\/en\/wp-json\/wp\/v2\/comments?post=8304"}],"version-history":[{"count":0,"href":"https:\/\/techxmedia.com\/en\/wp-json\/wp\/v2\/posts\/8304\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/techxmedia.com\/en\/wp-json\/wp\/v2\/media\/8307"}],"wp:attachment":[{"href":"https:\/\/techxmedia.com\/en\/wp-json\/wp\/v2\/media?parent=8304"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/techxmedia.com\/en\/wp-json\/wp\/v2\/categories?post=8304"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/techxmedia.com\/en\/wp-json\/wp\/v2\/tags?post=8304"},{"taxonomy":"contributor","embeddable":true,"href":"https:\/\/techxmedia.com\/en\/wp-json\/wp\/v2\/contributor?post=8304"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}