proposal-array-last icon indicating copy to clipboard operation
proposal-array-last copied to clipboard

Add .firstItem for symmetry

Open zocky opened this issue 5 years ago • 3 comments

I realize that this would be a trivial syntactic sugar for array[0], but

  • Symmetry is good. It makes the language easier to learn and the code easier to write and read.
  • Annoying the programmer is bad. If you often type .lastItem you will automatically start typing .firstItem even if it doesn't exist.
  • When using arrays with .shift() and .pop() (as opposed to iteration by index), using .firstItem and .lastItem makes the code more readable.

zocky avatar Aug 14 '19 08:08 zocky

Periodic reminder that .get(-1) (#23) solves this problem. ;)

Zarel avatar Aug 14 '19 09:08 Zarel

I like this idea. I think it makes code more readable since you don't need to figure out if the [0] might be the first item by accident. The main problem with [0] is that you don't know if the original programmer intended to type [1] or if she was expecting the index to change in the future. Where as firstItem communicates clearly that the index should never change.

I even think we should have firstIndex for similar reasons. Also, at one point in my life I was programming with both JavaScript and Lua and array indexing of arrays was different between the languages. While this is perhaps not common it would be nice to be able to state what you mean rather than having to remember technical details about how the indexing works. Usually you could just use map, forEach and similar constructs that do not depend on magic numbers.

cyberixae avatar Nov 22 '19 09:11 cyberixae

This also reads more fluently with the common pattern of chaining array prototype methods together,

compare

function shortestWord(words) {
	return words.filter(word => word.length > 0)
				.sort((a, b) => a.length - b.length)
				.firstItem()
}

with

function shortestWord(words) {
	return words.filter(word => word.length > 0)
				.sort((a, b) => a.length - b.length)
				[0]
}

the former is a lot more readable as the dangling [0] doesn't seem to fit with the flow.

zakhenry avatar May 22 '20 13:05 zakhenry