The task is to perform unshift operation without using the unshift() method with the help of jQuery. There are two approaches that are discussed below:
Approach 1: We can use the Array concat() method which is used to join two or more arrays. Just pass the newElement as the arrays of size 1 and the rest of the array.
- Example:
<!DOCTYPE HTML>
<
html
>
Â
Â<
head
>
   Â
<
title
>
       Â
How to perform the unshift() operationÂ
       Â
without using it in JavaScript
   Â
</
title
>
</
head
>
Â
Â<
body
style
=
"text-align:center;"
>
   Â
<
h1
style
=
"color:green;"
>Â
           Â
neveropenÂ
   Â
</
h1
>
   Â
<
p
id
=
"GFG_UP"
>
   Â
</
p
>
   Â
<
button
onclick
=
"myGFG()"
>
       Â
Click Here
   Â
</
button
>
   Â
<
p
id
=
"GFG_DOWN"
>
   Â
</
p
>
   Â
<
script
>
       Â
var array = ['Geeks', 'GFG', 'Geek', 'neveropen'];
       Â
var up = document.getElementById("GFG_UP");
       Â
up.innerHTML = "Array = [" + array + "]";
       Â
var down = document.getElementById("GFG_DOWN");
Â
ÂÂ Â Â Â Â Â Â Â
function myGFG() {
           Â
var newElement = 'gfg';
           Â
newArray = [newElement].concat(array);
           Â
down.innerHTML = "Elements of array = ["
                             Â
+ newArray + "]";
       Â
}
   Â
</
script
>
</
body
>
Â
Â</
html
>
-
Output:
Approach 2: We can use the ES6 spread operator to perform the operation.
- Example:
<!DOCTYPE HTML>
<
html
>
Â
Â<
head
>
   Â
<
title
>
       Â
How to perform the unshift() operation withoutÂ
       Â
using it in JavaScript
   Â
</
title
>
</
head
>
Â
Â<
body
style
=
"text-align:center;"
>
   Â
<
h1
style
=
"color:green;"
>Â
           Â
neveropenÂ
   Â
</
h1
>
   Â
<
p
id
=
"GFG_UP"
>
   Â
</
p
>
   Â
<
button
onclick
=
"myGFG()"
>
       Â
Click Here
   Â
</
button
>
   Â
<
p
id
=
"GFG_DOWN"
>
   Â
</
p
>
   Â
<
script
>
       Â
var array = ['Geeks', 'GFG', 'Geek', 'neveropen'];
       Â
var up = document.getElementById("GFG_UP");
       Â
up.innerHTML = "Array = [" + array + "]";
       Â
var down = document.getElementById("GFG_DOWN");
Â
ÂÂ Â Â Â Â Â Â Â
function myGFG() {
           Â
var newElement = 'gfg';
           Â
newArray = [newElement, ...array];
           Â
down.innerHTML = "elements of array = ["
                           Â
+ newArray + "]";
       Â
}
   Â
</
script
>
</
body
>
Â
Â</
html
>
-
Output: