Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is there no comparison statement in this javascript 'If... Else...' statement

In the following code

var $next =  $active.next().length ? $active.next()
        : $('#slideshow IMG:first');

the part '$active.next().length' doesn't seem to compare anything and I don't understand how the condition is determined to be True or False.

Or is it saying that: if the various $next is equal to $active.next().length then the condition is true?

like image 663
Simon Suh Avatar asked May 01 '12 17:05

Simon Suh


People also ask

How do you make a comparison in JavaScript?

Example 1: Equal to Operator== evaluates to true if the operands are equal. Note: In JavaScript, == is a comparison operator, whereas = is an assignment operator. If you mistakenly use = instead of == , you might get unwanted result.

Why if statement is not working in JS?

It also appears not to be working based on: The context of usage. For example, you placed the condition statement under an event block. Though the syntax of the event block and the conditional statement might be right but if the event is not triggered, nothing will happen.

What can I use instead of if else in JavaScript?

Javascript offers a ternary operator which acts like a one-line if / else statement with a single condition. It works really well for conditionally assigning a value to a variable.


2 Answers

In javascript any expression can be converted to a truthy or falsy value and hence is valid in a comparison place. The values which are false in javascript are

  • false
  • 0
  • "" (empty string)
  • null
  • undefined
  • NaN

In this case length refers to a numeric value and if it evaluates to 0 then it will be considered falsy. Otherwise it will be truthy

like image 60
JaredPar Avatar answered Oct 23 '22 04:10

JaredPar


If the length property is equal to 0 or undefined (i.e. $active is not an array), the condition will be false.

like image 5
bfontaine Avatar answered Oct 23 '22 04:10

bfontaine