I want to assign an expression to a variable, and if it has no value, use some default.

On almost every programming language I can use something like:

let linked_hl_id = hlID(l:linked_group) || 114

But of course it does not work, and the option I found is this eyesore using ternary and 2 lines of assignment:

let linked_hl_id = hlID(l:linked_group)
let linked_hl_id = linked_hl_id ? linked_hl_id : 114

What is a better syntax for that? Using NVIM v0.4.4.


  • @BLayer I love ternary, but I wonder if those 2 lines can be compacted to 1.
    – Moshe
    Commented Jun 8, 2021 at 7:04
  • 1
    Ah, okay. :) I misinterpreted what you are conveying.
    – B Layer
    Commented Jun 8, 2021 at 7:04
  • Gotta admit I'm not a fan of that format. The elvis-operator is great (not in vimscript, unfortunately) but that "or" syntax is non-intuitive...kind of "gross" lol. What languages are you a regular user of? Javascript? Python? (Just curious...nothing to do with an answer. :)
    – B Layer
    Commented Jun 8, 2021 at 7:24
  • 1
    @BLayer yes exactly both, and bash.
    – Moshe
    Commented Jun 8, 2021 at 7:26

1 Answer 1


Starting from 8.2.1794 vim has null coalescing operator aka falsy operator

let value = somevar ?? othervar ?? 100

:h ??

The expression before the '??' is evaluated.  If it evaluates to
|truthy|, this is used as the result.  Otherwise the expression after the '??'
is evaluated and used as the result.  This is most useful to have a default
value for an expression that may result in zero or empty: >
    echo theList ?? 'list is empty'
    echo GetName() ?? 'unknown'

Neovim uses quite an old vimscript so there is a doubt it would ever have this provided it is focused on lua.

There is also get function that could be used for cases like:

" my_var = g:my_var if it is defined, 100 otherwise
let my_var = get(g:, "my_var", 100)

" my_var = s:my_var if it is defined, 100 otherwise
let my_var = get(s:, "my_var", 100)

  • not working on neovim (also vim from what I see).
    – Moshe
    Commented Jun 8, 2021 at 10:03
  • and get( doesn't help me because it only retrieves item from a list
    – Moshe
    Commented Jun 8, 2021 at 10:05
  • 1
    next time specify neovim in the question pls, @Moshe. This operator is in recent vim 8.2.1794
    – Maxim Kim
    Commented Jun 8, 2021 at 10:47
  • as for get( it works for g:, b:, s:, l: and t: variables
    – Maxim Kim
    Commented Jun 8, 2021 at 10:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.