0

I know that shift and unshift is used to remove or add elements at the beginning of an array.Below is the simple Javascript Code.

var arx = ["Plumber",12,14,15,[18,"Try"]];
console.log("The array is :- ",arx);
arx.shift();    // SHIFT removes element from beginning
console.log("The array after shift operation is :- "+arx);
arx.unshift(11,"Try",["ABC",34,"GTH"],999);  ////////////   LINE 1
console.log("The array array unshift operation is :- "+arx);

Below is the output

enter image description here

I am not able to understand why after shift opeartion , my entire array is being displayed in series like that without any square bracket and all. Even the last element which is itself an array [18,'Try'] has been broken into two different elements. Even the unshift opeartion is adding every element one by one and is not adding array ["ABC",34,"GTH"] from line 1 in the form of array.Can anyone tell me what am I doing wrong ?

Brijesh
  • 35
  • 6
  • 3
    It's due to how `.toString` works. You're using `+` to concatenate the array to a string. Instead try listing the array as a separate argument in console.log? `console.log("The array array unshift operation is :- ", arx)` – evolutionxbox Sep 12 '22 at 08:30
  • It worked thanks a lot. Btw, can you tell me some good sources to learn javascript.I am newbiee in it. – Brijesh Sep 12 '22 at 08:37
  • https://justjavascript.com/ – evolutionxbox Sep 12 '22 at 08:39

1 Answers1

1

If you notice, in your console.logs you are adding "+" sign before arx. Try replacing it with a comma

var arx = ["Plumber",12,14,15,[18,"Try"]];
console.log("The array is :- ",arx);
arx.shift();    // SHIFT removes element from beginning
console.log("The array after shift operation is :- ",arx);
arx.unshift(11,"Try",["ABC",34,"GTH"],999);  ////////////   LINE 1
console.log("The array array unshift operation is :- ",arx);
  • Why does + sign makes it like that ?? – Brijesh Sep 12 '22 at 09:11
  • With the `+` operator where you were using it, you simply were concatenating an array with a string, that's why javascript transformed your array into a string. Try `console.log(+arx)`, the result will be NaN. Another syntax for the console.logs which resulted in the way you didn't want would be : ``console.log(`The array after shift operation is :- ${arx}`)`` For concatenation, check out **string interpolation** (in javascript) – Foucauld Gaudin Sep 12 '22 at 12:31
  • for a better understanding of the `+` operator, check out the most upvoted comment there [https://stackoverflow.com/questions/7124884/why-is-1-2-3-4-1-23-4-in-javascript] – Foucauld Gaudin Sep 12 '22 at 12:35