{"id":2900,"date":"2022-07-10T10:22:47","date_gmt":"2022-07-10T15:22:47","guid":{"rendered":"https:\/\/www.becomebetterprogrammer.com\/?p=2900"},"modified":"2022-07-11T08:41:48","modified_gmt":"2022-07-11T13:41:48","slug":"javascript-tuples","status":"publish","type":"post","link":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/javascript-tuples\/","title":{"rendered":"JavaScript | What are Tuples and How to Use Them (examples)"},"content":{"rendered":"\n<p>If you have a Python background, you must have come across one of the four main built-in data types called Tuples used to store multiple items in a single variable. Previously, we didn\u2019t have tuples in JavaScript, and programmers had to use various methods like array destructuring to play the role of tuples. But that was before the <a href=\"https:\/\/github.com\/tc39\/proposal-record-tuple\" target=\"_blank\" rel=\"noopener\">ECMAScript proposal (by Robin Ricard and Rick Button)<\/a> that introduced two new compound primitive values in JavaScript:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li>Records<\/li><li>Tuples<\/li><\/ul>\n\n\n\n<p>This post will primarily focus on the latter &#8211; JavaScript tuples.<\/p>\n\n\n\n<p><strong>In JavaScript, tuples are a bit like arrays since we use square brackets to define them and can also use various array methods. However, unlike arrays, they have a pre-defined length, and the types of data in a tuple are fixed once we have initialized it. In other words, a tuple in JavaScript is a typed array.<\/strong><\/p>\n\n\n\n<p>In this post, we will have an in-depth look at JavaScript Tuples and how to use them in our applications. Let\u2019s dive in.<\/p>\n\n\n\n<div id=\"ez-toc-container\" class=\"ez-toc-v2_0_82_2 counter-hierarchy ez-toc-counter ez-toc-custom ez-toc-container-direction\">\n<div class=\"ez-toc-title-container\"><p class=\"ez-toc-title\" style=\"cursor:inherit\">Table of Contents<\/p>\n<\/div><nav><ul class='ez-toc-list ez-toc-list-level-1 ' ><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-1\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/javascript-tuples\/#Support_for_Tuples\" >Support for Tuples<\/a><ul class='ez-toc-list-level-3' ><li class='ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-2\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/javascript-tuples\/#Using_Polyfill_and_Playground\" >Using Polyfill and Playground<\/a><\/li><\/ul><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-3\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/javascript-tuples\/#Creating_a_Tuple_in_JavaScript\" >Creating a Tuple in JavaScript<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-4\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/javascript-tuples\/#Tuples_are_Primitives\" >Tuples are Primitives<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-5\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/javascript-tuples\/#Tuples_are_Deeply_Immutable\" >Tuples are Deeply Immutable<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-6\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/javascript-tuples\/#Comparing_by_Value\" >Comparing by Value<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-7\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/javascript-tuples\/#Convert_Arrays_to_Tuples\" >Convert Arrays to Tuples<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-8\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/javascript-tuples\/#Convert_Tuples_to_Arrays\" >Convert Tuples to Arrays<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-9\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/javascript-tuples\/#JSON_and_Tuples\" >JSON and Tuples<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-10\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/javascript-tuples\/#Conclusion\" >Conclusion<\/a><\/li><\/ul><\/nav><\/div>\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Support_for_Tuples\"><\/span>Support for Tuples<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>As stated above, Tuples are still a new primitive type in JavaScript introduced by the ECMAScript proposal. This proposal is currently in <strong>Stage 2 <\/strong>at the moment of this writing<strong>,<\/strong> which means people have looked at it and seen it\u2019s a topic worth debating. At this point, developers also try to figure out the syntax and how the tuples would work. Unfortunately, Tuples won&#8217;t be introduced into browsers and Javascript frameworks like NodeJS until they reach Stage 3 (Candidate) or Stage 4.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Using_Polyfill_and_Playground\"><\/span>Using Polyfill and Playground<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p>Since we are still in Stage 2, we can use tuples in our applications only with Babel by using <a href=\"https:\/\/babeljs.io\/docs\/en\/babel-plugin-proposal-record-and-tuple#docsNav\" target=\"_blank\" rel=\"noopener\">this polyfill<\/a>. However, if you simply want to practice using Records and tuples without the hassle of setting up the environment, feel free to use the easy-to-use REPL &#8211; <a href=\"https:\/\/rickbutton.github.io\/record-tuple-playground\" target=\"_blank\" rel=\"noopener\">Rick Button &#8211; Tuple and Record playground<\/a>. We will use this playground for this particular post.<\/p>\n\n\n\n<figure class=\"wp-block-image\"><img loading=\"lazy\" decoding=\"async\" width=\"1794\" height=\"584\" src=\"http:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-content\/uploads\/2022\/07\/word-image-2900-1.png\" alt=\"\" class=\"wp-image-2901\" srcset=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-content\/uploads\/2022\/07\/word-image-2900-1.png 1794w, https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-content\/uploads\/2022\/07\/word-image-2900-1-300x98.png 300w, https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-content\/uploads\/2022\/07\/word-image-2900-1-1024x333.png 1024w, https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-content\/uploads\/2022\/07\/word-image-2900-1-1536x500.png 1536w\" sizes=\"auto, (max-width: 1794px) 100vw, 1794px\" \/><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Creating_a_Tuple_in_JavaScript\"><\/span>Creating a Tuple in JavaScript<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>Tuples introduced a new primitive type in JavaScript, which essentially follows the array syntax. There is only one difference. When declaring a tuple, you must prefix the square brackets with a \u2018#\u2019 (hash) symbol. Look at the code below, which shows the difference between an array and a tuple.<\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>let myArray = &#91;12, 23, \"yellow\"] \/\/this is an Array \n\nlet myTuple = #&#91;4, 5, \"black\"] \/\/ this is a Tuple. You can see the '#' in front of the square brackets. \n\nlog(\"isArray\", Array.isArray(myArray)) \n\/\/Returns &#91;\u201cisArray\u201d, true] \n\nlog(\"isTuple\", Tuple.isTuple(myTuple)) \n\/\/Returns &#91;\u201cisTuple\u201d, true]<\/code><\/pre>\n\n\n\n<p>As you can see in the code snippet above, the syntax of tuples is quite similar to that of arrays, with the only difference being the \u2018#\u2019 sign.<\/p>\n\n\n\n<p>You will also notice that although we said tuples are primitive data types, we are using the Tuple.isTuple to check the type of our tuple variable instead of the typeof() keyword. That\u2019s because typeof() is still an unsupported feature in the Babel polyfill we are using and will return an incorrect value.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Tuples_are_Primitives\"><\/span>Tuples are Primitives<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>JavaScript stores data either as \u2018primitive types\u2019 or \u2018reference types.\u2019 Primitive types are simple atomic pieces that are always saved and accessed by the variable\u2019s value and not as a reference to an object. There are six main primitive types in JavaScript: undefined, null, boolean, symbol, string, and number. With the ECMAScript proposal, we will now have more primitives, including records and tuples.<\/p>\n\n\n\n<p>Therefore, when we use the typeof keyword to check the type of our tuple variable, it should return a tuple as shown in the code snippet below.<\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>typeof #&#91;'a', 'b'] \n\/\/returns 'tuple' \n\nlet myTuple = #&#91;\"Bob\",\"Jane\"] \ntypeof(myTuple) \n\/\/returns 'tuple'<\/code><\/pre>\n\n\n\n<p>Reference types are not simple atomic values, but objects made up of multiple properties assigned to them. They are stored as a reference in memory and not as independent values assigned to variables. The three main reference types in JavaScript are arrays, objects, and functions.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Tuples_are_Deeply_Immutable\"><\/span>Tuples are Deeply Immutable<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>In many programming languages, we have both mutable and immutable values. Mutable values are those that can be changed or a new property can be added to them. On the other hand, immutable values in JavaScript cannot be changed or have anything added to them. They can only be reassigned. All primitive types in JavaScript are immutable. Let\u2019s understand this by looking at strings and arrays.<\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>\n\/\/We will create two String variables (nameOne and nameTwo)\n\n\n\nlet nameOne = \"John\"; \nlet nameTwo = nameOne; \n\nconsole.log(nameOne) \n\/\/returns 'John' \nconsole.log(nameTwo) \n\/\/returns 'John' \n\n \n\/\/Here we are re-assigning the nameTwo variable to \u2018Janedoe\u2019\nnameTwo = \"Janedoe\"\n\n \n\/\/When we log the output of the two variables, only nameTwo changed.\n\nconsole.log(nameOne) \n\/\/returns 'John' \nconsole.log(nameTwo) \n\/\/returns 'Janedoe'<\/code><\/pre>\n\n\n\n<p>From the code snippet above, you notice that after we re-assigned the variable \u201c<em>nameTwo<\/em>,\u201d the value of variable \u201c<em>nameOne<\/em>\u201d did not change and instead a new string was created. Now let\u2019s look at arrays that are reference types and are mutable.<\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>\nlet arrayOne = &#91;12, 13, 14] \nLet arrayTwo = arrayOne \n\nconsole.log(arrayOne); \n\/\/returns &#91;12,13,14] \nconsole.log(arrayTwo) \n\/\/returns &#91;12,13,14] \n\n\/\/Let's re-assign an index in arrayTwo\n\n\narrayTwo&#91;0] = \"yellow\" \nconsole.log(arrayOne); \n\/\/returns &#91;\"Yellow\",13,14] \nconsole.log(arrayTwo) \n\/\/returns &#91;\"Yellow\",13,14]<\/code><\/pre>\n\n\n\n<p>From the code snippet, you notice that when we re-assigned the <em>index[0]<\/em> in <em>arrayTwo<\/em>, the values in <em>arrayOne<\/em> also changed since the two variables were referencing one object.<\/p>\n\n\n\n<p>So, why are tuples deeply immutable? That\u2019s mainly because tuples by themselves are immutable and they can only hold primitive types, other tuples or records (which are also immutable). A tuple cannot hold any reference types, such as arrays or objects. However, the opposite is true. You can use an array or object to hold a tuple.<\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>\/\/ This is Okay \nconst tupleOne = #&#91;10, 20, \"Johndoe\",] \n\n\/\/ERROR: Sets an Array  \nconst tupleTwo = #&#91;10,22,\"Janedoe\",&#91;12,4,5]]\n\n \n\/\/ERROR: Sets an Object\n\n \nconst tupleThree = &#91;new Date()]\n\n \n\/\/This is Okay. \n\n \nconst arrayOne = &#91;12, 13, 14, #&#91;12, 13, \u201cYellow\u201d]]\n\n \nconsole.log(arrayOne&#91;3])\n\n \n\/\/returns tuple {12,13,\u201dYellow\u201d}\n\n \n\/\/Error: Tuples can\u2019t be changed at any level\n\n \nconst tupleOne&#91;0] = 23<\/code><\/pre>\n\n\n\n<p>Lastly, tuples cannot have holes of unset values.<\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>\/\/This will raise an Error: Unexpected token ','  \nLet tupOne = #&#91;2,,,\"Green\",5]<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Comparing_by_Value\"><\/span><a id=\"post-2900-_5tk8azmxgtrh\"><\/a>Comparing by Value<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>If there is one hurdle that most newbie JavaScript developers face is comparing reference types. Let\u2019s look at the code below which tries to compare arrays and objects.<\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>\/\/Compare Objects \nconsole.log({a:12, b:24} === {a:12,b:24}) \n\/\/returns false \n\n\/\/Compare Arrays \nconsole.log(&#91;12,13,14]===&#91;12,13,14]) \n\/\/returns false<\/code><\/pre>\n\n\n\n<p>Why are we getting a \u2018 False \u2019 yet the array and the object have the same values? Reference types like Arrays and Objects in JavaScript are compared by the reference or address in memory where the value is stored. And of course, we cannot store two different variables in the same memory address.<\/p>\n\n\n\n<p>Unlike arrays, tuples are compared by their values.<\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>console.log(#&#91;12,13,14] === #&#91;12,13,14]) \n\/\/returns true \nconsole.log(#&#91;12,13,15] === #&#91;20,30,40]) \n\/\/returns false<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Convert_Arrays_to_Tuples\"><\/span><a id=\"post-2900-_ez53ttrmu9h\"><\/a>Convert Arrays to Tuples<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>You can use the Tuple.from() method to create a tuple from an existing array.<\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>const arrayOne = &#91;12,13,14] \nconst tupleOne = Tuple.from(arrayOne) \n\nconst tupleTwo = Tuple.from(&#91;12,24,35])<\/code><\/pre>\n\n\n\n<p><strong>Caveat<\/strong>: However, there is a catch! If any value in the array is of non-primitive type, you will get an error. That\u2019s because tuples in JavaScript can only hold primitive types. See the code snippet below.<\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>\nconst arrayOne = &#91;12,13,&#91;25,34]] \n\n\/\/This will raise an Error \nconst tupOne = Tuple.from(arrayOne)\n\n \n\/\/This will raise Error\nconst tupTwo = Tuple.from(&#91;1,2,&#91;\u201ca\u201d,\u201db\u201d]])<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Convert_Tuples_to_Arrays\"><\/span><a id=\"post-2900-_n7tffhqi0g5z\"><\/a>Convert Tuples to Arrays<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>Likewise, you can use the Array.from() method to convert tuples to arrays.<\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>let tupOne = #&#91;12,13] \n\nlog(Array.from(tupOne)) \n\/\/returns &#91;12,13]<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"JSON_and_Tuples\"><\/span><a id=\"post-2900-_3txbwyo4lw0c\"><\/a>JSON and Tuples<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>The JSON.stringify() method is used to convert arrays and objects to JSON strings and treats tuples like arrays. See the code snippet below.<\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>const tupOne = #&#91;12,13,#&#91;12,13]] \nconst a = JSON.stringify(tupOne) \nconsole.log(a) \n\/\/returns \"&#91;12,13,&#91;12,13]]\" \n\nconst tupTwo = #&#91;12,13] \nconsole.log(tupTwo) \n\/\/returns # \"&#91;12,13]\"<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Conclusion\"><\/span><a id=\"post-2900-_ppbwhegnjq9g\"><\/a>Conclusion<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>That\u2019s it! Up to this point, I believe you now have a good understanding of what tuples are in JavaScript and how you can use them in your program. Other than the few examples we have looked at above, you can use tuples in loops and functions as you would with arrays. As of writing this post, tuples are still a new feature and not widely supported. You will need the Babel polyfill to use them.<\/p>\n\n\n\n<p><strong>Have you already worked with tuples? <\/strong><\/p>\n\n\n\n<p>Please, let us know your thoughts by replying on <a href=\"https:\/\/twitter.com\/bbprogrammer\" target=\"_blank\" rel=\"noopener\">Twitter of Become A Better Programmer<\/a>.<\/p>\n\n\n\n<figure class=\"wp-block-embed aligncenter is-type-rich is-provider-twitter wp-block-embed-twitter\"><div class=\"wp-block-embed__wrapper\">\n<blockquote class=\"twitter-tweet\" data-width=\"550\" data-dnt=\"true\"><p lang=\"en\" dir=\"ltr\">We have a gift for you today!<br><br>Here is a \ud83c\udf3c<br><br>It&#39;s a flower! It&#39;s a Tuple&#8230;<br><br>A programmatic tuple. <br><br>Even better, in <a href=\"https:\/\/twitter.com\/hashtag\/javascript?src=hash&amp;ref_src=twsrc%5Etfw\" target=\"_blank\" rel=\"noopener\">#javascript<\/a>! <br><br>In short: A Tuple in JavaScript is a typed array. <br><br>#[1, 2, 3]<br><br>&quot;But that looks like an array!&quot; <br><br>Learn more!<a href=\"https:\/\/t.co\/v1d7fSq53e\">https:\/\/t.co\/v1d7fSq53e<\/a><\/p>&mdash; Become A Better Programmer (@bbprogrammer) <a href=\"https:\/\/twitter.com\/bbprogrammer\/status\/1546487818230308864?ref_src=twsrc%5Etfw\" target=\"_blank\" rel=\"noopener\">July 11, 2022<\/a><\/blockquote><script async src=\"https:\/\/platform.twitter.com\/widgets.js\" charset=\"utf-8\"><\/script>\n<\/div><\/figure>\n","protected":false},"excerpt":{"rendered":"<p>If you have a Python background, you must have come across one of the four main built-in data types called Tuples used to store multiple items in a single variable. Previously, we didn\u2019t have tuples in JavaScript, and programmers had to use various methods like array destructuring to play the role of tuples. But that &#8230; <a title=\"JavaScript | What are Tuples and How to Use Them (examples)\" class=\"read-more\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/javascript-tuples\/\" aria-label=\"More on JavaScript | What are Tuples and How to Use Them (examples)\">Read more<\/a><\/p>\n","protected":false},"author":1,"featured_media":2903,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"nf_dc_page":"","_monsterinsights_skip_tracking":false,"_monsterinsights_sitenote_active":false,"_monsterinsights_sitenote_note":"","_monsterinsights_sitenote_category":0,"footnotes":""},"categories":[16],"tags":[],"class_list":["post-2900","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-javascript","generate-columns","tablet-grid-50","mobile-grid-100","grid-parent","grid-50"],"_links":{"self":[{"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/posts\/2900","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/comments?post=2900"}],"version-history":[{"count":2,"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/posts\/2900\/revisions"}],"predecessor-version":[{"id":2916,"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/posts\/2900\/revisions\/2916"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/media\/2903"}],"wp:attachment":[{"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/media?parent=2900"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/categories?post=2900"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/tags?post=2900"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}