The Array method unshift() in Apps Script

The Array method unshift() adds one or more elements to the beginning of an array and returns its new size.

Syntax

array.unshift(val, val2, …, val3)

Parameters

One or more values to be added to the beginning of the array.

Return value

The length of the array after adding elements to it.

Examples

The code below uses the unshift() array method to add elements to the beginning of the array colors.

var colors = ["red", "blue"];
Logger.log(colors);
Logger.log(colors.length);

// Adding just one element
var length = colors.unshift('purple');
Logger.log(colors);
Logger.log(length);

// Adding two elements
length = colors.unshift('green', 'yellow');
Logger.log(colors);
Logger.log(length);

Output

[red, blue]

2.0

[purple, red, blue]

3.0

[green, yellow, purple, red, blue]

5.0

Conclusion

In this tutorial, you learned how to use the unshift() array method to add elements to the beginning of an array.

Master Google Sheets Automation

Sign up to receive exclusive Automation tips and tutorials!
I'll send you actionable tips on automating tasks with Google Sheets and coding with Apps Script. You'll also be notified whenever new content is published.
PLUS: Get instant access to my Birthday Reminder Template! 🎂
By signing up you agree to the Privacy Policy & Terms.

Have feedback for me?

I'd appreciate any feedback you can give me regarding this post.

Was it useful? Are there any errors or was something confusing? Would you like me to write a post about a related topic? Any other feedback is also welcome. Thank you so much!