H
H
HoHsi2015-11-27 12:58:31
CoffeeScript
HoHsi, 2015-11-27 12:58:31

How to check for the existence of a variable in CoffeeScript?

Good morning!
I recently discovered the ||=and operators ?=.
Questions immediately arose:
1) What are their differences, besides the fact that ||= is a string operation, and ?= is executed through if
2) Can the entry be replaced
value = value ? {id: 1}
with
value ||= {id: 1}
or better
value ?= {id: 1}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey Ukolov, 2015-11-27
@HoHsi

In fact, they are very different checks.
will turn into

value || (value = {
  id: 1
});

but
will turn into
if (value == null) {
  value = {
    id: 1
  };
}

As you can see, the second check is stricter - the default value will only be used if value is undefined or null . In the first case, any falsy value ( false, 0, null, undefined ) will be replaced.
Which of these options to use depends on your application. If 0 or false, for example, are valid values ​​for the variable, take the second option, then the value will not be overwritten.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question