Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can anyone explain what is happening in this bit of Javascript?

I was looking through a jQuery smooth-scrolling tutorial, and trying to figure out how it worked, when I hit this line of code:

 $target = $target.length && $target || $('[name=' + this.hash.slice(1) +']');

I can't figure out what it does. It looks like the guy is assigning a string to a variable, but it also kinda looks like he's testing that variable. And I don't understand the use of && and || here. Can anybody explain this?

Thanks!

EDIT: Wow! What a response! This is taking a bit for me to understand, though - I will have to print this out or something and work on it. Once I understand what's going on, I'll be able to pick the answer that helped me the most. In particular, this bit:

if ($target.length && $target) {
$target = $target;

is stymying me. How does the program know to assign $target to $target? Does the operation assign $target to the first reference to itself (the left side of the equals sign), or to the second reference to itself (the right side, after the &&)?

like image 834
StormShadow Avatar asked Sep 26 '11 05:09

StormShadow


1 Answers

It is a cryptic(or elegant?) version of the equivalent ternary operator

$target = ($target.length && $target) ? $target : $('[name=' + this.hash.slice(1) +']');

This ternary and the original short circuit expression will return exactly same values if the evaluation of $target does not change the value of $target. But if the evaluation of $target changes the value of $target then SCE and ternary returns different values e.g.

var a = 1; b = 2; c = 3;
a && ++b || c
returns 3;
//resetting b
b = 2
a && ++b ? ++b : c 
returns 4;

If the evaluation of $target changes the value of $target then the equivalent ternary operator for the SCE $target = $target.length && $target || $('[name=' + this.hash.slice(1) +']'); would be the following

$target = ($result= ($target.length && $target)) ? $result : $('[name=' + this.hash.slice(1) +']');
like image 135
Narendra Yadala Avatar answered Oct 20 '22 20:10

Narendra Yadala