Frederik Witte
Frederik Witte

Reputation: 1345

How does this function work in particular?

Can someone explain me how this function works? I know the ternary operator, so I understand the part, that he checks if flag is true, and if not then use the 2. value. But I don't understand why flag is a Boolean in the first place and why it switches from true to false and vice versa when animate() is being called...

flag = $texte.data('animToggle');
$texte.data('animToggle', !flag);
$texte.animate({
    'left': flag ? '-51%' : '0'
})

Upvotes: 1

Views: 48

Answers (1)

James Donnelly
James Donnelly

Reputation: 128791

JavaScript has truthy and falsy values. These are values which equate to true and false when evaluated as Boolean. This means that true and false aren't the only values which can represent true or false data.

For example, if $texte.data('animToggle') is equal to 0 it will be falsy as 0 is a falsy value.

Example 1: 1000

1000 is a truthy value, so this will output "True":

var flag = 1000;
console.log(flag ? "True" : "False");

> "True"

Example 2: ""

"" (empty string) is a falsy value, so this will output "False":

var flag = "";
console.log(flag ? "True" : "False");

> "False"

The ! (Logical NOT) operator converts a value to Boolean and negates it. $texte.data('animToggle', !flag); sets the animToggle data property of $texte to the opposite of what it previously was.

!true   // False
!1000   // False

!false  // True
!""     // True

Upvotes: 3

Related Questions