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 ?

3
  • 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) Commented Sep 12, 2022 at 8:30
  • It worked thanks a lot. Btw, can you tell me some good sources to learn javascript.I am newbiee in it. Commented Sep 12, 2022 at 8:37
  • justjavascript.com Commented Sep 12, 2022 at 8:39

1 Answer 1

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);

Sign up to request clarification or add additional context in comments.

3 Comments

Why does + sign makes it like that ??
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)
for a better understanding of the + operator, check out the most upvoted comment there [stackoverflow.com/questions/7124884/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.