1

I just ran across this javascript snippet:

myArray.length--;

What does it do exactly?

Sam Washburn
  • 1,817
  • 3
  • 25
  • 43

2 Answers2

4

This removes the last items in the array.

var myArray = [1, 2, 3];
myArray.length--;
alert(myArray);

The output is:

[1, 2]
Luis Perez
  • 27,650
  • 10
  • 79
  • 80
3

Simple experimentation shows that it chops off last element of the array.

> var a = [1, 2, 3];
=> undefined
> a
=> [1, 2, 3]
> a.length--
=> 3
> a
=> [1, 2]
Sergio Tulentsev
  • 226,338
  • 43
  • 373
  • 367
  • What do you use for an interpreter? I've never seen an interactive javascript console like that. – Sam Washburn Jan 09 '12 at 07:15
  • 1
    Chrome's javascript console :-) – Sergio Tulentsev Jan 09 '12 at 07:18
  • 2
    Which by the way you get to by pressing F12, then clicking the >= toolbar icon on the very bottom. That and other features in chrome even allow you to experiment and alter the current page. (The other browsers offer some versions of this feature - also try the jsFiddle website) – Luis Perez Jan 09 '12 at 21:36