Samantha J Samantha J - 1 year ago 45
Javascript Question

How can I return a property value for the first element in an array or 0 if there are no elements?

In my HTML I have this code block:

<div ng-click="wos.wordWordFormRowClicked(wf)"
ng-repeat="wf in word.wordForms">

object can have 0 or many
and each
has a property

In javascript how can I get the
of the first
or return 0 if there are no wordForms. Hope this makes sense, if not please ask and I will try to explain more.

Here are the typescript interfaces:

interface IWord {
wordForms: IWordForm[];
wordId: string;

interface IWordForm {
definition: string;
wordFormId: string;
wordFormIdentity: number;
wordId: string;

Answer Source

Am I missing something or does this handle it? I responded in Typescript as well.

function getFirstId (word:IWord) :number {
    if(word && word.wordForms && word.wordForms.length > 0) {
        return word.wordForms[0].wordFormIdentity;
    return 0;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download