({{, (RefLink[OptionalElement, paclet:ref/OptionalElement])[patt] 
is a grammar rules pattern object that represents 0 or 1 instances of patt.}, {, (RefLink[OptionalElement, paclet:ref/OptionalElement])[patt,default]
uses default if the element is not present. }})

OpenersNotesSection(Spacer1)Details

(RefLink[OptionalElement, paclet:ref/OptionalElement]) appears inside (RefLink[GrammarRules, paclet:ref/GrammarRules]) objects.

OpenersPrimaryExamplesSection(Spacer1)Examples  (3)

OpenersExampleSection0(Spacer1)Basic Examples  (2)

Allow certain words to be optional:

grammar = CloudDeploy[
GrammarRules[{FixedOrder[OptionalElement["from"],from:GrammarToken["City"],"to",to:GrammarToken["Ocean"]]:>from->to}]
]

GrammarApply[grammar,"Boston to the Pacific"]

Supply a default value for a missing element:

grammar = CloudDeploy[
GrammarRules[{FixedOrder[OptionalElement["from"],from:OptionalElement[GrammarToken["City"],None],"to",to:GrammarToken["Ocean"]]:>Replace[from,None->$GeoLocationCity]->to}]
]

GrammarApply[grammar,"Boston to the Pacific"]

GrammarApply[grammar,"to the Pacific"]

OpenersExampleSection2(Spacer1)Possible Issues  (1)

The default value evaluates immediately:

CloudGet[CloudDeploy[
GrammarRules[{FixedOrder[OptionalElement["from"],from:OptionalElement[GrammarToken["City"],$GeoLocationCity],"to",to:GrammarToken["Ocean"]]:>from->to}]
]]

Use a sentinel for a dynamic default value:

grammar = CloudDeploy[
GrammarRules[{FixedOrder[OptionalElement["from"],from:OptionalElement[GrammarToken["City"],None],"to",to:GrammarToken["Ocean"]]:>Replace[from,None->$GeoLocationCity]->to}]
]

GrammarApply[grammar,"to the Pacific"]

({{DocumentationFooterIconsRelatedFunction.png, ({{See Also}, {(RefLink[GrammarRules, paclet:ref/GrammarRules])  ▪  (RefLink[GrammarApply, paclet:ref/GrammarApply])  ▪  (RefLink[Repeated, paclet:ref/Repeated])  ▪  (RefLink[Optional, paclet:ref/Optional])  ▪  (RefLink[FixedOrder, paclet:ref/FixedOrder])}})}})

({{DocumentationFooterIconsRelatedGuide.png, ({{Related Guides}, {▪(RefLinkPlain[Programmable Linguistic Interface, paclet:guide/ProgrammableLinguisticInterface])}})}})