0

I've been tasked with working on some code that I didn't write, but there is a line in this code that I just don't understand.

var headerHeight = window.innerWidth > 1920 ? $('.bottom-header').outerHeight() + $('.bottom-fixed-selector').outerHeight() : 0;

what I do understand is that the question mark is a conditional operator. I had no idea a conditional operator could be used within a variable declaration, however. Is there an alternative way to write this that is easier for me to understand?

dftg
  • 45
  • 8
  • 3
    It's actually called a [ternary operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator). Pretty much similar to an `if` statement. – j08691 Jul 05 '17 at 15:38
  • 2
    This belongs to the [MDN: Conditional (ternary) Operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator) – t.niese Jul 05 '17 at 15:38
  • 2
    `let headerHeight = 0; if (window.innerWidth > 1920) { headerHeight = $('.bottom-header').outerHeight() + $('.bottom-fixed-selector').outerHeight() }` – Icepickle Jul 05 '17 at 15:38
  • I don't agree this is a duplicate (at least with the one linked to), OP is asking for an equivalent to the code he posted. In any case, if OP is reading. This is the equivalent: https://pastebin.com/r7BXh0p5 – shotor Jul 05 '17 at 15:40
  • You can replace it with **If..Else** condition like below var headerHeight = 0; if(window.innerWidth > 1920){ headerHeight = $('.bottom-header').outerHeight() + $('.bottom-fixed-selector').outerHeight(); } BTW that one is ternary operator not conditional operator. – Arun Jul 05 '17 at 15:42

0 Answers0