Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use || in variable function declaration?

Tags:

javascript

I'm learning js and I've come across an example in which || is used when declaring a var as a function:

var Triangulation = Triangulation || (function() {   
...   

It seems to me that this is checking to see if the var has already been declared before assigning it. Looking around the web, I don't see any other examples where this approach is used. What would be a reason to take this approach vs:

var Triangulation = function() {   
...  

Thanks

like image 979
Mitch Avatar asked Nov 23 '13 06:11

Mitch


2 Answers

It means there is a chance the triangulation variable already defined, if it is, the triangulation variable returns itself, if not defined yet -- the anonymous function will return the value for the new variable triangulation.

And important/sensitive thing there is the var. It is a tricky business. For example:

<script>
var triangulation = function (){return(1);};
</script>

Actually means:

<script>
window.triangulation = function (){return(1);};// because "triangulation" is in global                       
                                               // namespace and "var" in this case 
                                               // means nothing "local", as you may expect
</script>

Next time, initialization var triangulation = ... will overwrite the global variable. If you want to preserve it, you have to write:

var triangulation = triangulation || function (){...}; 
like image 90
Ruben Kazumov Avatar answered Oct 16 '22 18:10

Ruben Kazumov


It checks if Triangulation exists before assigning it a new value using Short-circuiting. This is a common practice when you want to support a feature that differs from browsers to browsers.

One example is requestAnimationFrame. Since every browser require different vendor prefix, we use || to assign the correct method to the variable so that it supports all browsers.

window.requestAnimFrame = (function(){
  return  window.requestAnimationFrame       ||
          window.webkitRequestAnimationFrame ||
          window.mozRequestAnimationFrame    ||
          function( callback ){
            window.setTimeout(callback, 1000 / 60);
          };
})();

//whatever exists will be assigned to window.requestAnimFrame .
like image 42
Derek 朕會功夫 Avatar answered Oct 16 '22 19:10

Derek 朕會功夫