Search code examples
javascriptoperators

Question about javascript function declaration


What does it mean when a javascript function is declared in the following way:

JSON.stringify = JSON.stringify || function (obj)
{
  //stuff
};

How is the above different from just declaring it like below?

function stringify(obj)
{
  //stuff
}

Solution

    • function stringify will declare the function in the global scope (if you're not already inside another scope, such as another function or a hash) or the scope you're currently in.

      Example:

      function a() { ... } /* global scope */
      function a() { function b() { ... } /* scope of the a() function */ }
      
    • JSON.stringify = function will define the function on the JSON object.

      Example:

      JSON = {}
      JSON.stringify = function() { ... } /* you can now call stringify() on the JSON object */
      
    • JSON.stringify || function will only define it if it was not previously defined.

      Example:

      JSON = {}
      JSON.stringify = function() { ... }
      JSON.stringify = JSON.stringify || function() { ... } /* will not be replaced */