Array length: Difference between revisions

(J: flesh out the description)
Line 288:
 
<lang javascript>console.log(['apple', 'orange'].length);</lang>
 
However, determining the length of a list, array, or collection may simply be the wrong thing to do.
 
If, for example, the actual task (undefined here, unfortunately) requires retrieving the final item, while it is perfectly possible to write '''last''' in terms of '''length'''
 
<lang JavaScript>function last(lst) {
return lst[lst.length - 1];
}</lang>
 
using length has the disadvantage that it leaves ''last'' simply undefined for an empty list.
 
We might do better to drop the narrow focus on length, and instead use a fold (''reduce'', in JS terms) which can return a default value of some kind.
 
<lang JavaScript>function last(lst) {
return lst.reduce(function (a, x) {
return x;
}, null);
}</lang>
 
=={{header|ooRexx}}==
9,659

edits