Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP

firstOrDefault(defValue) , firstOrDefault(predicate, defValue[, arg])

suckgamoni edited this page · 1 revision

Returns the first element of the sequence that satisfies a condition or a default value if no such element is found.

Syntax

Parameters

predicate

Type: function(value, key, arg): boolean
A function to test each element for a condition.

defValue

Default value to return.

arg

An external argument.

Return Value

defValue if source is empty or if no element passes the test specified by predicate; otherwise, the first element in source that passes the test specified by predicate.


Example

var numbers = [ ];
var first = from(numbers).firstOrDefault(0);
console.log(first);

/*
 This code produces the following output:

 0
*/
var names = [ "Hartono, Tommy", "Adams, Terry", "Andersen, Henriette Thaulow", "Hedlund, Magnus", "Ito, Shu" ];

var firstLongName = from(names).firstOrDefault("$length > 20", "");

console.log("The first long name is '" + firstLongName + "'.");

var firstVeryLongName = from(names).firstOrDefault("$length > 30", null);

console.log(
    "There is " + (firstVeryLongName == null ? "not a" : "a") + " name longer than 30 characters.");

/*
 This code produces the following output:

 The first long name is 'Andersen, Henriette Thaulow'.
 There is not a name longer than 30 characters.
*/
Something went wrong with that request. Please try again.