1

I have a hamlc (known as Haml + Inline CoffeeScript) which has a line like

- @variable1 ?= @object1.element[0]

I wonder if this means: if @object1.element[0] has a value then store it inside @variable1.

I cannot find any info about hamlc. Also, if what I understand is right, what if I want to add an else condition?

Patrik Affentranger
  • 13,245
  • 2
  • 22
  • 25
Takumi
  • 355
  • 1
  • 7
  • 19

1 Answers1

2

The ?= operator is known as the existential operator in CoffeeScript.

From the docs:

It's a little difficult to check for the existence of a variable in JavaScript. if (variable) ... comes close, but fails for zero, the empty string, and false. CoffeeScript's existential operator ? returns true unless a variable is null or undefined, which makes it analogous to Ruby's nil?

That means that the way it works is, using your example:

 @variable1 ?= @object1.element[0]

If @variable1 is null or undefined, assign @object1.element[0] to it.

what if I want to add the condition for "else" ?

@variable1 = 
  if @variable1?
    @object1.element[0]
  else
    # your else clause here
magni-
  • 1,934
  • 17
  • 20