{"id":751,"date":"2023-12-06T12:00:00","date_gmt":"2023-12-06T12:00:00","guid":{"rendered":"https:\/\/favtutor.com\/articles\/?p=751"},"modified":"2023-12-07T05:35:14","modified_gmt":"2023-12-07T05:35:14","slug":"unshift-javascript","status":"publish","type":"post","link":"https:\/\/favtutor.com\/articles\/unshift-javascript\/","title":{"rendered":"JavaScript Array unshift() Method Explained (with code)"},"content":{"rendered":"\n<p>In this article, we will look into JavaScript&#8217;s arrays and the use of the unshift() function to manipulate the arrays. It is mostly used with arrays. It\u2019s important to look into various functionalities of the function.\u00a0Let us get started.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong><strong>What is unshift() Method in JavaScript?<\/strong><\/strong><\/h2>\n\n\n\n<p>Let&#8217;s first revise what are Arrays! Arrays are linear data structures that store homogenous data, i.e. same type of data. An array can contain all integers, all characters, or all strings as the elements. An array can not be a combination of integers and characters, or integers or strings. <\/p>\n\n\n\n<p>Let us look at how to declare and use arrays in Javascript:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>\/\/declaring an integers array\r\nlet marks = &#91;98, 75, 62, 82, 97, 53];\r\n\r\n\/\/declaring a characters array\r\nlet grades=&#91;'A', 'B', 'A', '0'];\r\n\r\n\/\/declaring a strings array\r\nlet favtutors=&#91;\"John\", \"Joshua\", \"Alex\", \"Kate\"];\r\n\r\n\/\/declaring a boolean array\r\nlet present=&#91;true, false, false, true];\r<\/code><\/pre>\n\n\n\n<p>In JavaScript, we do not need to specify the type of the array at the compile time as it is a dynamically typed language. Hence, We are not required to specify the data type explicitly while declaring an array.<\/p>\n\n\n\n<p><strong>The unshift() function is primarily used for adding elements to the beginning of an array. <\/strong>When new elements are added, the elements present at higher indices shift towards the right vacating indices for the newly added elements.\u00a0<\/p>\n\n\n\n<p>You just have to remember, that whenever we want to add single or multiple elements at the beginning of an array, we use this method.<\/p>\n\n\n\n<p>This operation is an in-place operation, i.e. the changes are reflected in the same array. A new copy of the array is not created.<\/p>\n\n\n\n<p>The syntax is as follows:<\/p>\n\n\n\n<pre class=\"wp-block-code has-black-color has-text-color has-background\" style=\"background-color:#fedcba\"><code>array_name.unshift(element1, element2, element3,\u2026.)<\/code><\/pre>\n\n\n\n<p>where,&nbsp;<\/p>\n\n\n\n<p><strong>array_name:<\/strong> the name of the array variable to which the elements are to be added<\/p>\n\n\n\n<p><strong>element\/element2,element3..<\/strong>: single or multiple elements that are to be added to the beginning of the array<\/p>\n\n\n\n<p>It returns the modified length of the array after adding the elements. Let us take an example to understand it better:<\/p>\n\n\n\n<div class=\"wp-block-codemirror-blocks-code-block code-block\"><pre class=\"CodeMirror\" data-setting=\"{&quot;mode&quot;:&quot;javascript&quot;,&quot;mime&quot;:&quot;text\/javascript&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;language&quot;:&quot;JavaScript&quot;,&quot;modeName&quot;:&quot;js&quot;}\">\/\/declaring an array\nlet arr=[1,2,3,4];\n\n\/\/checking return value\nlet unshiftReturn=arr.unshift(5,6);\n\n\/\/printing the variable unshiftReturn\nconsole.log(unshiftReturn);<\/pre><\/div>\n\n\n\n<p><strong>Output:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code has-black-color has-text-color has-background\" style=\"background-color:#fedcba\"><code>6<\/code><\/pre>\n\n\n\n<p>As we are using the function to add the sequence 5,6 at the beginning of the array, the new array becomes [5,6,1,2,3,4]. The new array has a length of 6 which the function returns.<\/p>\n\n\n\n<p>The time complexity to add elements using it is O(n + m), where n is the number of existing elements in the array, and m is the number of elements being added to the beginning.<\/p>\n\n\n\n<p>It can be used in multiple ways which we will explore in further sections. Also, check <a href=\"https:\/\/favtutor.com\/articles\/array-splice-javascript\/\">JavaScript Array splice() method<\/a>.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Case 1) Adding Multiple Elements at Once<\/strong><\/h3>\n\n\n\n<p>We can provide multiple parameters (a list of elements) in the unshift() function. Let us observe through an example:<\/p>\n\n\n\n<div class=\"wp-block-codemirror-blocks-code-block code-block\"><pre class=\"CodeMirror\" data-setting=\"{&quot;mode&quot;:&quot;javascript&quot;,&quot;mime&quot;:&quot;text\/javascript&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;language&quot;:&quot;JavaScript&quot;,&quot;modeName&quot;:&quot;js&quot;}\">\/\/declaring an array\nlet arr=[1,2,3,4];\n\n\/\/printing array before adding new elements\nconsole.log(arr);\n\n\/\/using unshift() function\narr.unshift(5,6,7);\n\n\/\/printing the array\nconsole.log(arr);<\/pre><\/div>\n\n\n\n<p><strong>Output:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code has-black-color has-text-color has-background\" style=\"background-color:#fedcba\"><code>&#91;1,2,3,4]\n&#91;5,6,7,1,2,3,4]\n<\/code><\/pre>\n\n\n\n<p>The elements provided as parameters are as it is added to the beginning of the array in the same sequence. As we can see, the order of elements remains the same (5,6,7) at the beginning of the array.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Case 2) Adding Elements One by One<\/strong><\/h3>\n\n\n\n<p>Let us understand through an example, what happens when we add the elements one by one.<\/p>\n\n\n\n<div class=\"wp-block-codemirror-blocks-code-block code-block\"><pre class=\"CodeMirror\" data-setting=\"{&quot;mode&quot;:&quot;javascript&quot;,&quot;mime&quot;:&quot;text\/javascript&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;language&quot;:&quot;JavaScript&quot;,&quot;modeName&quot;:&quot;js&quot;}\">\/\/declaring an array\nlet arr=[1,2,3,4];\n\n\/\/printing array before adding new elements\nconsole.log(arr);\n\n\/\/using unshift() function\narr.unshift(5);\narr.unshift(6);\narr.unshift(7);\n\n\/\/printing the array\nconsole.log(arr);<\/pre><\/div>\n\n\n\n<p><strong>Output:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code has-black-color has-text-color has-background\" style=\"background-color:#fedcba\"><code>&#91; 1, 2, 3, 4 ]\n&#91; 7, 6, 5, 1, 2, 3, 4]\n<\/code><\/pre>\n\n\n\n<p>Let us understand with the help of a dry run of the same.<\/p>\n\n\n\n<p>Initial array:<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter\"><img decoding=\"async\" src=\"https:\/\/lh7-us.googleusercontent.com\/WwdbELbD8CGBtX2f_TpGvZuyz3mRuPl4O0yq0xNjv4N2cCB18SNa5GcrMRxheoTY3P3Rc6G-xYLSCzm_uYmsT-99WTaW69QBiqLN1GWOlJm1TjQH_moVMbdltFXcZckvRZDTiyI04i3rOJfJk29NjWY\" alt=\"Initial array\"\/><\/figure>\n<\/div>\n\n\n<p>Array after first unshift(5) function:<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter\"><img decoding=\"async\" src=\"https:\/\/lh7-us.googleusercontent.com\/Pfhp0eX7c1KPzQziOG3aU-SYnyNTkBUoyhYke3YZdwRFHXcEOwr_0uFPN1UZJZpQA--Fh45pC_IJabIYMW8EHXzDgjDrblJmTjYmiRswRsZRxu39svb1rGYDO-V_YcYvKiOmGYxziKJ7f6ASnTsYKq0\" alt=\"Array after first unshift(5) function\"\/><\/figure>\n<\/div>\n\n\n<p>Array after second unshift(6) function:<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter\"><img decoding=\"async\" src=\"https:\/\/lh7-us.googleusercontent.com\/_meg4Zff7CVnY_jqbQ4edRU-6lunpJXYp1n_ceF6IL3Mv1XiMp1pBXN_sbvji7RN_YAC0dRQoJFhpI3az8wIgYo2Fd1wPOOhP2XSq8rJGTSjES9D4UfZO5twl36Z-3BBZ0ksUS5-bg1cd1Dq_Xx1pCM\" alt=\"Array after second unshift(6) function\"\/><\/figure>\n<\/div>\n\n\n<p>Array after third unshift(7) function:<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter\"><img decoding=\"async\" src=\"https:\/\/lh7-us.googleusercontent.com\/FxoU02HXNN44KYSYhkWyPz4Gr49oa62-K5iFvQMH4BOsaYbiEBE70gVR5uAEH7ivwKb_pjHGOu8-MOIb4wflHhzwsbU9buza7OAtcAZQvhT0jZOafwJ_OfgYwnP88rEcOrAE_twKO19oUMc_Bu-5Sa4\" alt=\"Array after third unshift(7) function\"\/><\/figure>\n<\/div>\n\n\n<p>We have obtained the desired result.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Reversing the Array using unshift() Function<\/strong><\/h3>\n\n\n\n<p>One of the most used functionalities of this method is to reverse an array. Let us see how we can reverse the array using it:<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li>We will iterate over every array element and use the unshift() function for every element from first to last.<br><\/li>\n\n\n\n<li>At every iteration, the current element of the original array will be pushed at the beginning of the reversed array.<br><\/li>\n\n\n\n<li>At the final iteration, we will observe that the last element of the original array will come at first of the reversed array.<\/li>\n<\/ol>\n\n\n\n<div class=\"wp-block-codemirror-blocks-code-block code-block\"><pre class=\"CodeMirror\" data-setting=\"{&quot;mode&quot;:&quot;javascript&quot;,&quot;mime&quot;:&quot;text\/javascript&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;language&quot;:&quot;JavaScript&quot;,&quot;modeName&quot;:&quot;js&quot;}\">\/\/declaring an array\nlet ogArray=[4,5,6,7];\n\n\/\/printing the array\nconsole.log(ogArray);\n\n\/\/creating a new array to store elements in reverse order\nlet reversedArray=[];\n\n\/\/using the unshift() loop\nfor(let i=0;i&lt;ogArray.length;i++){\n    \/\/adding elements in the reversedArray using\n    reversedArray.unshift(ogArray[i]);\n}\n\n\/\/printing the reversed ogArray\nconsole.log(reversedArray)<\/pre><\/div>\n\n\n\n<p><strong>Output:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code has-black-color has-text-color has-background\" style=\"background-color:#fedcba\"><code>&#91; 4, 5, 6, 7 ]\n&#91; 7, 6, 5, 4 ]\n<\/code><\/pre>\n\n\n\n<p>We have obtained the desired result.<\/p>\n\n\n\n<p>Remember that while unshift() is useful, it may not be the most performant choice for large arrays, as shifting elements requires reindexing the entire array. Careful consideration of your application&#8217;s requirements will help you determine when to leverage its benefits in your JavaScript projects.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>Conclusion<\/strong><\/h2>\n\n\n\n<p>In this article, we learned that unshift() allows us to add elements to the beginning of an array efficiently, without creating a new array. We discussed the syntax, the return value, and various ways the elements can be added to the beginning of an array. It becomes easier to manipulate the arrays with this method. If this is a question that you got in your school, you might want some <a href=\"https:\/\/favtutor.com\/javascript-assignment-help\" data-type=\"link\" data-id=\"https:\/\/favtutor.com\/javascript-assignment-help\">help with JavaScript homework<\/a>.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Learn how to use the unshift function in JavaScript Arrays to add a single or multiple elements at the beginning with examples.<\/p>\n","protected":false},"author":9,"featured_media":753,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"jnews-multi-image_gallery":[],"jnews_single_post":null,"jnews_primary_category":{"id":"","hide":""},"footnotes":""},"categories":[9],"tags":[11,13],"class_list":["post-751","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-web-development","tag-javascript","tag-javascript-array"],"_links":{"self":[{"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/posts\/751","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/users\/9"}],"replies":[{"embeddable":true,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/comments?post=751"}],"version-history":[{"count":3,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/posts\/751\/revisions"}],"predecessor-version":[{"id":837,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/posts\/751\/revisions\/837"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/media\/753"}],"wp:attachment":[{"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/media?parent=751"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/categories?post=751"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/tags?post=751"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}