<p><strong>What "Hidden Features" of JavaScript do you think every programmer should know?</strong></p>

<p>After having seen the excellent quality of the answers to the following questions I thought it was time to ask it for JavaScript.</p>

<ul>
<li><a href="https://stackoverflow.com/questions/954327/">Hidden Features of HTML</a></li>
<li><a href="https://stackoverflow.com/questions/628407">Hidden Features of CSS</a></li>
<li><a href="https://stackoverflow.com/questions/61401/">Hidden Features of PHP</a></li>
<li><a href="https://stackoverflow.com/questions/54929/">Hidden Features of ASP.NET</a></li>
<li><a href="https://stackoverflow.com/questions/9033/">Hidden Features of C#</a></li>
<li><a href="https://stackoverflow.com/questions/15496/">Hidden Features of Java</a></li>
<li><a href="https://stackoverflow.com/questions/101268/">Hidden Features of Python</a></li>
</ul>

<p>Even though JavaScript is arguably the most important Client Side language right now (just ask Google) it's surprising how little most web developers appreciate how powerful it really is.</p>

[{'answer_id': 61094, 'author': 'Gulzar Nazim', 'author_id': 4337, 'author_profile': 'https://Stackoverflow.com/users/4337', 'pm_score': 8, 'selected': False, 'text': '<p>Functions are first class citizens in JavaScript:</p>\n\n<pre><code>var passFunAndApply = function (fn,x,y,z) { return fn(x,y,z); };\n\nvar sum = function(x,y,z) {\n  return x+y+z;\n};\n\nalert( passFunAndApply(sum,3,4,5) ); // 12\n</code></pre>\n\n<p><a href="http://www.ibm.com/developerworks/library/wa-javascript.html" rel="nofollow noreferrer">Functional programming techniques can be used to write elegant javascript</a>.</p>\n\n<p>Particularly, functions can be passed as parameters, e.g. <a href="http://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/filter" rel="nofollow noreferrer">Array.filter()</a> accepts a callback:</p>\n\n<pre><code>[1, 2, -1].filter(function(element, index, array) { return element &gt; 0 });\n// -&gt; [1,2]\n</code></pre>\n\n<p>You can also declare a "private" function that only exists within the scope of a specific function:</p>\n\n<pre><code>function PrintName() {\n    var privateFunction = function() { return "Steve"; };\n    return privateFunction();\n}\n</code></pre>\n'}, {'answer_id': 61097, 'author': 'Allain Lalonde', 'author_id': 2443, 'author_profile': 'https://Stackoverflow.com/users/2443', 'pm_score': 7, 'selected': False, 'text': '<p><strong>Private Methods</strong></p>\n\n<p>An object can have private methods.</p>\n\n<pre><code>function Person(firstName, lastName) {\n    this.firstName = firstName;\n    this.lastName = lastName;\n\n    // A private method only visible from within this constructor\n    function calcFullName() {\n       return firstName + " " + lastName;    \n    }\n\n    // A public method available to everyone\n    this.sayHello = function () {\n        alert(calcFullName());\n    }\n}\n\n//Usage:\nvar person1 = new Person("Bob", "Loblaw");\nperson1.sayHello();\n\n// This fails since the method is not visible from this scope\nalert(person1.calcFullName());\n</code></pre>\n'}, {'answer_id': 61118, 'author': 'Shog9', 'author_id': 811, 'author_profile': 'https://Stackoverflow.com/users/811', 'pm_score': 6, 'selected': False, 'text': '<p><strong><code>with</code></strong>.</p>\n<p>It\'s rarely used, and frankly, rarely useful... But, in limited circumstances, it does have its uses.</p>\n<p>For instance: object literals are quite handy for quickly setting up properties on a <em>new</em> object. But what if you need to change <em>half</em> of the properties on an existing object?</p>\n<pre><code>var user = \n{\n   fname: \'Rocket\', \n   mname: \'Aloysus\',\n   lname: \'Squirrel\', \n   city: \'Fresno\', \n   state: \'California\'\n};\n\n// ...\n\nwith (user)\n{\n   mname = \'J\';\n   city = \'Frostbite Falls\';\n   state = \'Minnesota\';\n}\n</code></pre>\n<p>Alan Storm points out that this can be somewhat dangerous: if the object used as context doesn\'t <em>have</em> one of the properties being assigned to, it will be resolved in the outer scope, possibly creating or overwriting a global variable. This is especially dangerous if you\'re used to writing code to work with objects where properties with default or empty values are left undefined:</p>\n<pre><code>var user = \n{\n   fname: &quot;John&quot;,\n// mname definition skipped - no middle name\n   lname: &quot;Doe&quot;\n};\n\nwith (user)\n{\n   mname = &quot;Q&quot;; // creates / modifies global variable &quot;mname&quot;\n}\n</code></pre>\n<p>Therefore, it is probably a good idea to avoid the use of the <code>with</code> statement for such assignment.</p>\n<h3>See also: <a href="https://stackoverflow.com/questions/61552/are-there-legitimate-uses-for-javascripts-with-statement">Are there legitimate uses for JavaScript’s “with” statement?</a></h3>\n'}, {'answer_id': 61125, 'author': 'Patrick', 'author_id': 429, 'author_profile': 'https://Stackoverflow.com/users/429', 'pm_score': 7, 'selected': False, 'text': '<p><strong>You can access object properties with <code>[]</code> instead of <code>.</code></strong></p>\n\n<p>This allows you look up a property matching a variable.</p>\n\n<pre><code>obj = {a:"test"};\nvar propname = "a";\nvar b = obj[propname];  // "test"\n</code></pre>\n\n<p>You can also use this to get/set object properties whose name is not a legal identifier.</p>\n\n<pre><code>obj["class"] = "test";  // class is a reserved word; obj.class would be illegal.\nobj["two words"] = "test2"; // using dot operator not possible with the space.\n</code></pre>\n\n<p>Some people don\'t know this and end up using <strong>eval()</strong> like this, which is a <em>really bad idea</em>:</p>\n\n<pre><code>var propname = "a";\nvar a = eval("obj." + propname);\n</code></pre>\n\n<p>This is harder to read, harder to find errors in (can\'t use jslint), slower to execute, and can lead to XSS exploits.</p>\n'}, {'answer_id': 61129, 'author': 'Eric Schoonover', 'author_id': 3957, 'author_profile': 'https://Stackoverflow.com/users/3957', 'pm_score': 6, 'selected': False, 'text': '<p>"<a href="http://codebetter.com/blogs/jeremy.miller/archive/2008/09/08/quot-extension-method-quot-in-javascript.aspx" rel="nofollow noreferrer">Extension methods in JavaScript</a>" via the prototype property.</p>\n\n<pre><code>Array.prototype.contains = function(value) {  \n    for (var i = 0; i &lt; this.length; i++) {  \n        if (this[i] == value) return true;  \n    }  \n    return false;  \n}\n</code></pre>\n\n<p>This will add a <code>contains</code> method to all <code>Array</code> objects.  You can call this method using this syntax </p>\n\n<pre><code>var stringArray = ["foo", "bar", "foobar"];\nstringArray.contains("foobar");\n</code></pre>\n'}, {'answer_id': 61158, 'author': 'Christian C. Salvadó', 'author_id': 5445, 'author_profile': 'https://Stackoverflow.com/users/5445', 'pm_score': 7, 'selected': False, 'text': '<p><strong>Assigning default values to variables</strong></p>\n\n<p>You can use the logical or operator <a href="https://developer.mozilla.org/en/Core_JavaScript_1.5_Guide/Operators/Logical_Operators" rel="nofollow noreferrer"><code>||</code></a> in an assignment expression to provide a default value:</p>\n\n<pre><code>var a = b || c;\n</code></pre>\n\n<p>The <code>a</code> variable will get the value of <code>c</code> only if <code>b</code> is <em>falsy</em> (if is <code>null</code>, <code>false</code>, <code>undefined</code>, <code>0</code>, <code>empty string</code>, or <code>NaN</code>), otherwise <code>a</code> will get the value of <code>b</code>.</p>\n\n<p>This is often useful in functions, when you want to give a default value to an argument in case isn\'t supplied:</p>\n\n<pre><code>function example(arg1) {\n  arg1 || (arg1 = \'default value\');\n}\n</code></pre>\n\n<p>Example IE fallback in event handlers:</p>\n\n<pre><code>function onClick(e) {\n    e || (e = window.event);\n}\n</code></pre>\n\n<hr>\n\n<p>The following language features have been with us for a long time, all JavaScript implementations support them, but they weren\'t part of the specification until <a href="http://www.ecma-international.org/publications/standards/Ecma-262.htm" rel="nofollow noreferrer">ECMAScript 5th Edition</a>:</p>\n\n<p><strong>The <code>debugger</code> statement</strong></p>\n\n<p>Described in: <em>&sect; 12.15 The debugger statement</em></p>\n\n<p>This statement allows you to put <em>breakpoints programmatically</em> in your code just by:</p>\n\n<pre><code>// ...\ndebugger;\n// ...\n</code></pre>\n\n<p>If a debugger is present or active, it will cause it to break immediately, right on that line.</p>\n\n<p>Otherwise, if the debugger is not present or active this statement has no observable effect.</p>\n\n<p><strong>Multiline String literals</strong></p>\n\n<p>Described in: <em>&sect; 7.8.4 String Literals</em></p>\n\n<pre><code>var str = "This is a \\\nreally, really \\\nlong line!";\n</code></pre>\n\n<p>You have to be careful because the character next to the <code>\\</code> <em>must</em> be a line terminator, if you have a space after the <code>\\</code> for example, the code will <em>look</em> exactly the same, but it will raise a <code>SyntaxError</code>.</p>\n'}, {'answer_id': 61165, 'author': 'Vaibhav', 'author_id': 380, 'author_profile': 'https://Stackoverflow.com/users/380', 'pm_score': 2, 'selected': False, 'text': "<p>It's surprising how many people don't realize that it's object oriented as well.</p>\n"}, {'answer_id': 61173, 'author': 'Eugene Yokota', 'author_id': 3827, 'author_profile': 'https://Stackoverflow.com/users/3827', 'pm_score': 7, 'selected': False, 'text': '<p><a href="http://developer.mozilla.org/En/Core_JavaScript_1.5_Guide:Block_Statement" rel="nofollow noreferrer">JavaScript does not have block scope</a> (but it has <a href="http://developer.mozilla.org/en/Core_JavaScript_1.5_Guide/Functions#Function_expressions" rel="nofollow noreferrer">closure</a> so let\'s call it even?).</p>\n\n<pre><code>var x = 1;\n{\n   var x = 2;\n}\nalert(x); // outputs 2\n</code></pre>\n'}, {'answer_id': 61193, 'author': 'Tyler', 'author_id': 5642, 'author_profile': 'https://Stackoverflow.com/users/5642', 'pm_score': 5, 'selected': False, 'text': '<p>How about <strong>closures</strong> in JavaScript (similar to anonymous methods in C# v2.0+). You can create a function that creates a function or "expression".</p>\n\n<p>Example of <strong>closures</strong>:</p>\n\n<pre><code>//Takes a function that filters numbers and calls the function on \n//it to build up a list of numbers that satisfy the function.\nfunction filter(filterFunction, numbers)\n{\n  var filteredNumbers = [];\n\n  for (var index = 0; index &lt; numbers.length; index++)\n  {\n    if (filterFunction(numbers[index]) == true)\n    {\n      filteredNumbers.push(numbers[index]);\n    }\n  }\n  return filteredNumbers;\n}\n\n//Creates a function (closure) that will remember the value "lowerBound" \n//that gets passed in and keep a copy of it.\nfunction buildGreaterThanFunction(lowerBound)\n{\n  return function (numberToCheck) {\n    return (numberToCheck &gt; lowerBound) ? true : false;\n  };\n}\n\nvar numbers = [1, 15, 20, 4, 11, 9, 77, 102, 6];\n\nvar greaterThan7 = buildGreaterThanFunction(7);\nvar greaterThan15 = buildGreaterThanFunction(15);\n\nnumbers = filter(greaterThan7, numbers);\nalert(\'Greater Than 7: \' + numbers);\n\nnumbers = filter(greaterThan15, numbers);\nalert(\'Greater Than 15: \' + numbers);\n</code></pre>\n'}, {'answer_id': 61196, 'author': 'Tyler', 'author_id': 5642, 'author_profile': 'https://Stackoverflow.com/users/5642', 'pm_score': 5, 'selected': False, 'text': '<p>You can also <strong>extend (inherit) classes and override properties/methods</strong> using the prototype chain <strong>spoon16</strong> alluded to.</p>\n\n<p>In the following example we create a class Pet and define some properties. We also override the .toString() method inherited from Object.</p>\n\n<p>After this we create a Dog class which <strong>extends Pet and overrides the .toString()</strong> method again changing it\'s behavior (polymorphism). In addition we add some other properties to the child class.</p>\n\n<p>After this we check the inheritance chain to show off that Dog is still of type Dog, of type Pet, and of type Object.</p>\n\n<pre><code>// Defines a Pet class constructor \nfunction Pet(name) \n{\n    this.getName = function() { return name; };\n    this.setName = function(newName) { name = newName; };\n}\n\n// Adds the Pet.toString() function for all Pet objects\nPet.prototype.toString = function() \n{\n    return \'This pets name is: \' + this.getName();\n};\n// end of class Pet\n\n// Define Dog class constructor (Dog : Pet) \nfunction Dog(name, breed) \n{\n    // think Dog : base(name) \n    Pet.call(this, name);\n    this.getBreed = function() { return breed; };\n}\n\n// this makes Dog.prototype inherit from Pet.prototype\nDog.prototype = new Pet();\n\n// Currently Pet.prototype.constructor\n// points to Pet. We want our Dog instances\'\n// constructor to point to Dog.\nDog.prototype.constructor = Dog;\n\n// Now we override Pet.prototype.toString\nDog.prototype.toString = function() \n{\n    return \'This dogs name is: \' + this.getName() + \n        \', and its breed is: \' + this.getBreed();\n};\n// end of class Dog\n\nvar parrotty = new Pet(\'Parrotty the Parrot\');\nvar dog = new Dog(\'Buddy\', \'Great Dane\');\n// test the new toString()\nalert(parrotty);\nalert(dog);\n\n// Testing instanceof (similar to the `is` operator)\nalert(\'Is dog instance of Dog? \' + (dog instanceof Dog)); //true\nalert(\'Is dog instance of Pet? \' + (dog instanceof Pet)); //true\nalert(\'Is dog instance of Object? \' + (dog instanceof Object)); //true\n</code></pre>\n\n<p>Both answers to this question were codes modified from a <a href="http://msdn.microsoft.com/en-us/magazine/cc163419.aspx" rel="nofollow noreferrer">great MSDN article by Ray Djajadinata.</a></p>\n'}, {'answer_id': 61260, 'author': 'VolkerK', 'author_id': 4833, 'author_profile': 'https://Stackoverflow.com/users/4833', 'pm_score': 7, 'selected': False, 'text': '<p>Functions are objects and therefore can have properties.</p>\n\n<pre>\nfn = function(x) {\n   // ...\n}\n\nfn.foo = 1;\n\nfn.next = function(y) {\n  //\n}\n</pre>\n'}, {'answer_id': 61545, 'author': 'Martin Clarke', 'author_id': 2422, 'author_profile': 'https://Stackoverflow.com/users/2422', 'pm_score': 8, 'selected': False, 'text': '<p>I could quote most of Douglas Crockford\'s excellent book\n<a href="https://rads.stackoverflow.com/amzn/click/com/0596517742" rel="nofollow noreferrer" rel="nofollow noreferrer">JavaScript: The Good Parts</a>.</p>\n\n<p>But I\'ll take just one for you, always use <code>===</code> and <code>!==</code> instead of <code>==</code> and <code>!=</code></p>\n\n<pre><code>alert(\'\' == \'0\'); //false\nalert(0 == \'\'); // true\nalert(0 ==\'0\'); // true\n</code></pre>\n\n<p><code>==</code> is not transitive. If you use <code>===</code> it would give false for \nall of these statements as expected.</p>\n'}, {'answer_id': 61584, 'author': 'Marius', 'author_id': 1585, 'author_profile': 'https://Stackoverflow.com/users/1585', 'pm_score': 3, 'selected': False, 'text': '<p>Javascript has static variables inside functions:</p>\n\n<pre><code>function someFunction(){\n  var Static = arguments.callee;\n  Static.someStaticVariable = (Static.someStaticVariable || 0) + 1;\n  alert(Static.someStaticVariable);\n}\nsomeFunction() //Alerts 1\nsomeFunction() //Alerts 2\nsomeFunction() //Alerts 3\n</code></pre>\n\n<p>It also has static variables inside Objects:</p>\n\n<pre><code>function Obj(){\n  this.Static = arguments.callee;\n}\na = new Obj();\na.Static.name = "a";\nb = new Obj();\nalert(b.Static.name); //Alerts b\n</code></pre>\n'}, {'answer_id': 64404, 'author': 'JW.', 'author_id': 4321, 'author_profile': 'https://Stackoverflow.com/users/4321', 'pm_score': 3, 'selected': False, 'text': '<p><code>undefined</code> is undefined. So you can do this:</p>\n\n<pre><code>if (obj.field === undefined) /* ... */\n</code></pre>\n'}, {'answer_id': 64912, 'author': 'Vitaly Sharovatov', 'author_id': 6647, 'author_profile': 'https://Stackoverflow.com/users/6647', 'pm_score': 2, 'selected': False, 'text': '<p>As Marius already pointed, you can have public static variables in functions. </p>\n\n<p>I usually use them to create functions that are executed only once, or to cache some complex calculation results.</p>\n\n<p>Here\'s the example of my old "singleton" approach:</p>\n\n<pre><code>var singleton = function(){ \n\n  if (typeof arguments.callee.__instance__ == \'undefined\') { \n\n    arguments.callee.__instance__ = new function(){\n\n      //this creates a random private variable.\n      //this could be a complicated calculation or DOM traversing that takes long\n      //or anything that needs to be "cached"\n      var rnd = Math.random();\n\n      //just a "public" function showing the private variable value\n      this.smth = function(){ alert(\'it is an object with a rand num=\' + rnd); };\n\n   };\n\n  }\n\n  return arguments.callee.__instance__;\n\n};\n\n\nvar a = new singleton;\nvar b = new singleton;\n\na.smth(); \nb.smth();\n</code></pre>\n\n<p>As you may see, in both cases the constructor is run only once.</p>\n\n<p>For example, I used this approach back in 2004 when I had to\ncreate a modal dialog box with a gray background that\ncovered the whole page (something like <a href="http://en.wikipedia.org/wiki/Lightbox_(JavaScript)" rel="nofollow noreferrer">Lightbox</a>). Internet\nExplorer 5.5 and 6 have the highest stacking context for\n&lt;select&gt; or &lt;iframe&gt; elements due to their\n"windowed" nature; so if the page contained select elements,\nthe only way to cover them was to create an iframe and\nposition it "on top" of the page. So the whole script was\nquite complex and a little bit slow (it used filter:\nexpressions to set opacity for the covering iframe). The\n"shim" script had only one ".show()" method, which created\nthe shim only once and cached it in the static variable :)</p>\n'}, {'answer_id': 64950, 'author': 'Thevs', 'author_id': 8559, 'author_profile': 'https://Stackoverflow.com/users/8559', 'pm_score': 4, 'selected': False, 'text': '<p>The way JavaScript works with Date() just excites me!</p>\n\n<pre><code>function isLeapYear(year) {\n    return (new Date(year, 1, 29, 0, 0).getMonth() != 2);\n}\n</code></pre>\n\n<p>This is really "hidden feature".</p>\n\n<p>Edit: Removed "?" condition as suggested in comments for politcorrecteness. \nWas: ... new Date(year, 1, 29, 0, 0).getMonth() != 2 ? true : false ...\nPlease look at comments for details.</p>\n'}, {'answer_id': 65002, 'author': 'Mark Cidade', 'author_id': 1659, 'author_profile': 'https://Stackoverflow.com/users/1659', 'pm_score': 3, 'selected': False, 'text': '<p>All functions are actually instances of the built-in <strong>Function</strong> type, which has a constructor that takes a string containing the function definition, so you can actually define functions at run-time by e.g., concatenating strings:</p>\n\n<pre><code>//e.g., createAddFunction("a","b") returns function(a,b) { return a+b; }\nfunction createAddFunction(paramName1, paramName2)\n { return new Function( paramName1, paramName2\n                       ,"return "+ paramName1 +" + "+ paramName2 +";");\n }\n</code></pre>\n\n<p>Also, for user-defined functions, <strong>Function.toString()</strong> returns the function definition as a literal string.</p>\n'}, {'answer_id': 65028, 'author': 'Mark Cidade', 'author_id': 1659, 'author_profile': 'https://Stackoverflow.com/users/1659', 'pm_score': 9, 'selected': False, 'text': "<p>You don't need to define any parameters for a function. You can just use the function's <code>arguments</code> array-like object.</p>\n\n<pre><code>function sum() {\n    var retval = 0;\n    for (var i = 0, len = arguments.length; i &lt; len; ++i) {\n        retval += arguments[i];\n    }\n    return retval;\n}\n\nsum(1, 2, 3) // returns 6\n</code></pre>\n"}, {'answer_id': 65064, 'author': 'Mark Cidade', 'author_id': 1659, 'author_profile': 'https://Stackoverflow.com/users/1659', 'pm_score': 4, 'selected': False, 'text': '<p>All objects in Javascript are implemented as hashtables, so their properties can be accessed through the indexer and vice-versa. Also, you can enumerate all the properties using the <strong>for/in</strong> operator:</p>\n\n<pre><code>var x = {a: 0};\nx["a"]; //returns 0\n\nx["b"] = 1;\nx.b; //returns 1\n\nfor (p in x) document.write(p+";"); //writes "a;b;"\n</code></pre>\n'}, {'answer_id': 65124, 'author': 'Mark Cidade', 'author_id': 1659, 'author_profile': 'https://Stackoverflow.com/users/1659', 'pm_score': 7, 'selected': False, 'text': '<p>You can use the <strong>in</strong> operator to check if a key exists in an object:</p>\n\n<pre><code>var x = 1;\nvar y = 3;\nvar list = {0:0, 1:0, 2:0};\nx in list; //true\ny in list; //false\n1 in list; //true\ny in {3:0, 4:0, 5:0}; //true\n</code></pre>\n\n<p>If you find the object literals too ugly you can combine it with the parameterless function tip:</p>\n\n<pre><code>function list()\n { var x = {};\n   for(var i=0; i &lt; arguments.length; ++i) x[arguments[i]] = 0;\n   return x\n }\n\n 5 in list(1,2,3,4,5) //true\n</code></pre>\n'}, {'answer_id': 65415, 'author': 'Sebastian Rittau', 'author_id': 7779, 'author_profile': 'https://Stackoverflow.com/users/7779', 'pm_score': 4, 'selected': False, 'text': '<p>JavaScript uses a simple object literal:</p>\n\n<pre><code>var x = { intValue: 5, strValue: "foo" };\n</code></pre>\n\n<p>This constructs a full-fledged object.</p>\n\n<p>JavaScript uses prototype-based object orientation and provides the ability to extend types at runtime:</p>\n\n<pre><code>String.prototype.doubleLength = function() {\n    return this.length * 2;\n}\n\nalert("foo".doubleLength());\n</code></pre>\n\n<p>An object delegates all access to attributes that it doesn\'t contain itself to its "prototype", another object. This can be used to implement inheritance, but is actually more powerful (even if more cumbersome):</p>\n\n<pre><code>/* "Constructor" */\nfunction foo() {\n    this.intValue = 5;\n}\n\n/* Create the prototype that includes everything\n * common to all objects created be the foo function.\n */\nfoo.prototype = {\n    method: function() {\n        alert(this.intValue);\n    }\n}\n\nvar f = new foo();\nf.method();\n</code></pre>\n'}, {'answer_id': 67614, 'author': 'Chris James', 'author_id': 3193, 'author_profile': 'https://Stackoverflow.com/users/3193', 'pm_score': 7, 'selected': False, 'text': '<p>Maybe a little obvious to some...</p>\n\n<p>Install <a href="http://en.wikipedia.org/wiki/Firebug_(Firefox_extension)" rel="nofollow noreferrer">Firebug</a> and use console.log("hello"). So much better than using random alert();\'s which I remember doing a lot a few years ago.</p>\n'}, {'answer_id': 68961, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 3, 'selected': False, 'text': '<p>One of my favorites is constructor type checking:</p>\n\n<pre><code>function getObjectType( obj ) {  \n    return obj.constructor.name;  \n}  \n\nwindow.onload = function() {  \n    alert( getObjectType( "Hello World!" ) );  \n    function Cat() {  \n        // some code here...  \n    }  \n    alert( getObjectType( new Cat() ) );  \n}\n</code></pre>\n\n<p>So instead of the tired old [Object object] you often get with the typeof keyword, you can actually get real object types based upon the constructor.</p>\n\n<p>Another one is using variable arguments as a way to "overload" functions. All you are doing is using an expression to detect the number of arguments and returning overloaded output:</p>\n\n<pre><code>function myFunction( message, iteration ) {  \n    if ( arguments.length == 2 ) {  \n        for ( i = 0; i &lt; iteration; i++ ) {  \n            alert( message );  \n        }  \n    } else {  \n        alert( message );  \n    }  \n}  \n\nwindow.onload = function() {  \n    myFunction( "Hello World!", 3 );  \n}\n</code></pre>\n\n<p>Finally, I would say assignment operator shorthand. I learned this from the source of the jQuery framework... the old way:</p>\n\n<pre><code>var a, b, c, d;\nb = a;\nc = b;\nd = c;\n</code></pre>\n\n<p>The new (shorthand) way:</p>\n\n<pre><code>var a, b, c, d;\nd = c = b = a;\n</code></pre>\n\n<p>Good fun :)</p>\n'}, {'answer_id': 75844, 'author': 'noah', 'author_id': 12034, 'author_profile': 'https://Stackoverflow.com/users/12034', 'pm_score': 3, 'selected': False, 'text': "<p>This one is super hidden, and only occasionally useful ;-)</p>\n\n<p>You can use the prototype chain to create an object that delegates to another object without changing the original object.</p>\n\n<pre><code>var o1 = { foo: 1, bar: 'abc' };\nfunction f() {}\nf.prototype = o1;\no2 = new f();\nassert( o2.foo === 1 );\nassert( o2.bar === 'abc' );\no2.foo = 2;\no2.baz = true;\nassert( o2.foo === 2 );\n// o1 is unchanged by assignment to o2\nassert( o1.foo === 1 );\nassert( o2.baz );\n</code></pre>\n\n<p>This only covers 'simple' values on o1. If you modify an array or another object, then the prototype no longer 'protects' the original object. Beware anytime you have an {} or [] in a Class definition/prototype.</p>\n"}, {'answer_id': 78155, 'author': 'user14079', 'author_id': 14079, 'author_profile': 'https://Stackoverflow.com/users/14079', 'pm_score': 4, 'selected': False, 'text': '<p>Timestamps in JavaScript:</p>\n\n<pre><code>// Usual Way\nvar d = new Date();\ntimestamp = d.getTime();\n\n// Shorter Way\ntimestamp = (new Date()).getTime();\n\n// Shortest Way\ntimestamp = +new Date();\n</code></pre>\n'}, {'answer_id': 78290, 'author': 'Jimmy', 'author_id': 4435, 'author_profile': 'https://Stackoverflow.com/users/4435', 'pm_score': 3, 'selected': False, 'text': '<p>Function.toString() (implicit):</p>\n\n<pre><code>function x() {\n    alert("Hello World");\n}\neval ("x = " + (x + "").replace(\n    \'Hello World\',\n    \'STACK OVERFLOW BWAHAHA"); x("\'));\nx();\n</code></pre>\n'}, {'answer_id': 104424, 'author': 'Chris MacDonald', 'author_id': 18146, 'author_profile': 'https://Stackoverflow.com/users/18146', 'pm_score': 5, 'selected': False, 'text': '<p>Private variables with a Public Interface</p>\n\n<p>It uses a neat little trick with a self-calling function definition.\nEverything inside the object which is returned is available in the public interface, while everything else is private.</p>\n\n<pre><code>var test = function () {\n    //private members\n    var x = 1;\n    var y = function () {\n        return x * 2;\n    };\n    //public interface\n    return {\n        setx : function (newx) {\n            x = newx;\n        },\n        gety : function () {\n            return y();\n        }\n    }\n}();\n\nassert(undefined == test.x);\nassert(undefined == test.y);\nassert(2 == test.gety());\ntest.setx(5);\nassert(10 == test.gety());\n</code></pre>\n'}, {'answer_id': 105603, 'author': 'Vincent Robert', 'author_id': 268, 'author_profile': 'https://Stackoverflow.com/users/268', 'pm_score': 6, 'selected': False, 'text': "<p>Methods (or functions) can be called on object that are not of the type they were designed to work with. This is great to call native (fast) methods on custom objects.</p>\n\n<pre><code>var listNodes = document.getElementsByTagName('a');\nlistNodes.sort(function(a, b){ ... });\n</code></pre>\n\n<p>This code crashes because <code>listNodes</code> is not an <code>Array</code></p>\n\n<pre><code>Array.prototype.sort.apply(listNodes, [function(a, b){ ... }]);\n</code></pre>\n\n<p>This code works because <code>listNodes</code> defines enough array-like properties (length, [] operator) to be used by <code>sort()</code>.</p>\n"}, {'answer_id': 109360, 'author': 'Zach', 'author_id': 9128, 'author_profile': 'https://Stackoverflow.com/users/9128', 'pm_score': 5, 'selected': False, 'text': '<p>Numbers are also objects. So you can do cool stuff like:</p>\n\n<pre><code>// convert to base 2\n(5).toString(2) // returns "101"\n\n// provide built in iteration\nNumber.prototype.times = function(funct){\n  if(typeof funct === \'function\') {\n    for(var i = 0;i &lt; Math.floor(this);i++) {\n      funct(i);\n    }\n  }\n  return this;\n}\n\n\n(5).times(function(i){\n  string += i+" ";\n});\n// string now equals "0 1 2 3 4 "\n\nvar x = 1000;\n\nx.times(function(i){\n  document.body.innerHTML += \'&lt;p&gt;paragraph #\'+i+\'&lt;/p&gt;\';\n});\n// adds 1000 parapraphs to the document\n</code></pre>\n'}, {'answer_id': 110337, 'author': 'user19745', 'author_id': 19745, 'author_profile': 'https://Stackoverflow.com/users/19745', 'pm_score': 3, 'selected': False, 'text': '<p>You can do almost anything between parentheses if you separate statements with commas:</p>\n\n<pre><code>var z = ( x = "can you do crazy things with parenthesis", ( y = x.split(" "), [ y[1], y[0] ].concat( y.slice(2) ) ).join(" ") )\n\nalert(x + "\\n" + y + "\\n" + z)\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>can you do crazy things with parenthesis\ncan,you,do,crazy,things,with,parenthesis\nyou can do crazy things with parenthesis\n</code></pre>\n'}, {'answer_id': 112295, 'author': 'Rakesh Pai', 'author_id': 20089, 'author_profile': 'https://Stackoverflow.com/users/20089', 'pm_score': 3, 'selected': False, 'text': "<p>The concept of truthy and falsy values. You don't need to do something like</p>\n\n<p>if(someVar === undefined || someVar === null) ...</p>\n\n<p>Simply do:</p>\n\n<p>if(!someVar).</p>\n\n<p>Every value has a corresponding boolean representation.</p>\n"}, {'answer_id': 114695, 'author': 'Dan', 'author_id': 17121, 'author_profile': 'https://Stackoverflow.com/users/17121', 'pm_score': 3, 'selected': False, 'text': "<p>You can execute an object's method on any object, regardless of whether it has that method or not. Of course it might not always work (if the method assumes the object has something it doesn't), but it can be extremely useful. For example:</p>\n\n<pre><code>function(){\n    arguments.push('foo') // This errors, arguments is not a proper array and has no push method\n    Array.prototype.push.apply(arguments, ['foo']) // Works!\n}\n</code></pre>\n"}, {'answer_id': 115587, 'author': 'jrockway', 'author_id': 8457, 'author_profile': 'https://Stackoverflow.com/users/8457', 'pm_score': 2, 'selected': False, 'text': '<p><a href="http://code.google.com/p/joose-js/" rel="nofollow noreferrer">Joose</a> is a nice object system if you would like Class-based OO that feels somewhat like CLOS.</p>\n\n<pre><code>// Create a class called Point\nClass("Point", {\n    has: {\n        x: {\n            is:   "rw",\n            init: 0\n        },\n        y: {\n            is:   "rw",\n            init: 0\n        }\n    },\n    methods: {\n        clear: function () {\n            this.setX(0);\n            this.setY(0);\n        }\n    }\n})\n\n// Use the class\nvar point = new Point();\npoint.setX(10)\npoint.setY(20);\npoint.clear();\n</code></pre>\n'}, {'answer_id': 115622, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 3, 'selected': False, 'text': '<p>All your "hidden" features are right here on the Mozilla wiki: <a href="http://developer.mozilla.org/en/JavaScript" rel="nofollow noreferrer">http://developer.mozilla.org/en/JavaScript</a>.</p>\n\n<p>There\'s <a href="http://developer.mozilla.org/en/Core_JavaScript_1.5_Reference" rel="nofollow noreferrer">the core JavaScript 1.5 reference</a>, <a href="http://developer.mozilla.org/en/New_in_JavaScript_1.6" rel="nofollow noreferrer">what\'s new in JavaScript 1.6</a>, what\'s <a href="http://developer.mozilla.org/en/New_in_JavaScript_1.7" rel="nofollow noreferrer">new in JavaScript 1.7</a>, and also what\'s <a href="http://developer.mozilla.org/en/New_in_JavaScript_1.8" rel="nofollow noreferrer">new in JavaScript 1.8</a>. Look through all of those for examples that actually work and are <em>not</em> wrong.</p>\n'}, {'answer_id': 115798, 'author': 'amix', 'author_id': 20081, 'author_profile': 'https://Stackoverflow.com/users/20081', 'pm_score': 3, 'selected': False, 'text': '<p>Visit:</p>\n\n<ul>\n<li><a href="http://images.google.com/images?q=disco" rel="nofollow noreferrer">http://images.google.com/images?q=disco</a> </li>\n</ul>\n\n<p>Paste this JavaScript code into your web browser\'s address bar:</p>\n\n<ul>\n<li><a href="http://amix.dk/upload/awt/spin.txt" rel="nofollow noreferrer">http://amix.dk/upload/awt/spin.txt</a></li>\n<li><a href="http://amix.dk/upload/awt/disco.txt" rel="nofollow noreferrer">http://amix.dk/upload/awt/disco.txt</a></li>\n</ul>\n\n<p>Enjoy the JavaScript disco show :-p</p>\n'}, {'answer_id': 116790, 'author': 'Andrey Fedorov', 'author_id': 10728, 'author_profile': 'https://Stackoverflow.com/users/10728', 'pm_score': 5, 'selected': False, 'text': '<p>Some would call this a matter of taste, but:</p>\n\n<pre><code>aWizz = wizz || "default";\n// same as: if (wizz) { aWizz = wizz; } else { aWizz = "default"; }\n</code></pre>\n\n<p>The trinary operator can be chained to act like Scheme\'s (cond ...):</p>\n\n<pre><code>(cond (predicate  (action  ...))\n      (predicate2 (action2 ...))\n      (#t         default ))\n</code></pre>\n\n<p>can be written as...</p>\n\n<pre><code>predicate  ? action( ... ) :\npredicate2 ? action2( ... ) :\n             default;\n</code></pre>\n\n<p>This is very "functional", as it branches your code without side effects. So instead of:</p>\n\n<pre><code>if (predicate) {\n  foo = "one";\n} else if (predicate2) {\n  foo = "two";\n} else {\n  foo = "default";\n}\n</code></pre>\n\n<p>You can write:</p>\n\n<pre><code>foo = predicate  ? "one" :\n      predicate2 ? "two" :\n                   "default";\n</code></pre>\n\n<p>Works nice with recursion, too :)</p>\n'}, {'answer_id': 117022, 'author': 'Leo', 'author_id': 20689, 'author_profile': 'https://Stackoverflow.com/users/20689', 'pm_score': 5, 'selected': False, 'text': '<p>Off the top of my head...</p>\n\n<p><strong>Functions</strong></p>\n\n<p>arguments.callee refers to the function that hosts the "arguments" variable, so it can be used to recurse anonymous functions:</p>\n\n<pre><code>var recurse = function() {\n  if (condition) arguments.callee(); //calls recurse() again\n}\n</code></pre>\n\n<p>That\'s useful if you want to do something like this:</p>\n\n<pre><code>//do something to all array items within an array recursively\nmyArray.forEach(function(item) {\n  if (item instanceof Array) item.forEach(arguments.callee)\n  else {/*...*/}\n})\n</code></pre>\n\n<p><strong>Objects</strong></p>\n\n<p>An interesting thing about object members: they can have any string as their names:</p>\n\n<pre><code>//these are normal object members\nvar obj = {\n  a : function() {},\n  b : function() {}\n}\n//but we can do this too\nvar rules = {\n  ".layout .widget" : function(element) {},\n  "a[href]" : function(element) {}\n}\n/* \nthis snippet searches the page for elements that\nmatch the CSS selectors and applies the respective function to them:\n*/\nfor (var item in rules) {\n  var elements = document.querySelectorAll(rules[item]);\n  for (var e, i = 0; e = elements[i++];) rules[item](e);\n}\n</code></pre>\n\n<p><strong>Strings</strong></p>\n\n<p><em>String.split</em> can take regular expressions as parameters:</p>\n\n<pre><code>"hello world   with  spaces".split(/\\s+/g);\n//returns an array: ["hello", "world", "with", "spaces"]\n</code></pre>\n\n<p><em>String.replace</em> can take a regular expression as a search parameter and a function as a replacement parameter:</p>\n\n<pre><code>var i = 1;\n"foo bar baz ".replace(/\\s+/g, function() {return i++});\n//returns "foo1bar2baz3"\n</code></pre>\n'}, {'answer_id': 117922, 'author': 'treat your mods well', 'author_id': 20772, 'author_profile': 'https://Stackoverflow.com/users/20772', 'pm_score': 1, 'selected': False, 'text': '<p>You can redefine large parts of the runtime environment on the fly, such as <a href="http://directwebremoting.org/blog/joe/2007/03/05/json_is_not_as_safe_as_people_think_it_is.html" rel="nofollow noreferrer">modifying the <code>Array</code> constructor</a> or defining <code>undefined</code>. Not that you should, but it <em>can</em> be a powerful feature.</p>\n\n<p>A somewhat less dangerous form of this is the addition of helper methods to existing objects. You can <a href="http://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Array/indexOf#Compatibility" rel="nofollow noreferrer">make IE6 "natively" support indexOf on arrays</a>, for example.</p>\n'}, {'answer_id': 117951, 'author': 'David Leonard', 'author_id': 19502, 'author_profile': 'https://Stackoverflow.com/users/19502', 'pm_score': 6, 'selected': False, 'text': '<p>Here are some interesting things:</p>\n\n<ul>\n<li>Comparing <code>NaN</code> with anything (even <code>NaN</code>) is always false, that includes <code>==</code>, <code>&lt;</code> and <code>&gt;</code>.</li>\n<li><code>NaN</code> Stands for Not a Number but if you ask for the type it actually returns a number.</li>\n<li><code>Array.sort</code> can take a comparator function and is called by a quicksort-like driver (depends on implementation).</li>\n<li>Regular expression "constants" can maintain state, like the last thing they matched.</li>\n<li>Some versions of JavaScript allow you to access <code>$0</code>, <code>$1</code>, <code>$2</code> members on a regex.</li>\n<li><code>null</code> is unlike anything else. It is neither an object, a boolean, a number, a string, nor <code>undefined</code>. It\'s a bit like an "alternate" <code>undefined</code>. (Note: <code>typeof null == "object"</code>)</li>\n<li>In the outermost context, <code>this</code> yields the otherwise unnameable [Global] object.</li>\n<li>Declaring a variable with <code>var</code>, instead of just relying on automatic declaration of the variable gives the runtime a real chance of optimizing access to that variable</li>\n<li>The <code>with</code> construct will destroy such optimzations</li>\n<li>Variable names can contain Unicode characters.</li>\n<li>JavaScript regular expressions are not actually regular. They are based on Perl\'s regexs, and it is possible to construct expressions with lookaheads that take a very, very long time to evaluate.</li>\n<li>Blocks can be labeled and used as the targets of <code>break</code>. Loops can be labeled and used as the target of <code>continue</code>.</li>\n<li>Arrays are not sparse. Setting the 1000th element of an otherwise empty array should fill it with <code>undefined</code>. (depends on implementation)</li>\n<li><code>if (new Boolean(false)) {...}</code>  will execute the <code>{...}</code> block</li>\n<li>Javascript\'s regular expression engine\'s are implementation specific: e.g. it is possible to write "non-portable" regular expressions. </li>\n</ul>\n\n<p><em>[updated a little in response to good comments; please see comments]</em></p>\n'}, {'answer_id': 118150, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 7, 'selected': False, 'text': '<p>Also mentioned in Crockford\'s "Javascript: The Good Parts":</p>\n\n<p><code>parseInt()</code> is dangerous.  If you pass it a string without informing it of the proper base it may return unexpected numbers.  For example <code>parseInt(\'010\')</code> returns 8, not 10.  Passing a base to parseInt makes it work correctly:</p>\n\n<pre><code>parseInt(\'010\') // returns 8! (in FF3)\nparseInt(\'010\', 10); // returns 10 because we\'ve informed it which base to work with.\n</code></pre>\n'}, {'answer_id': 118556, 'author': 'Chris Noe', 'author_id': 14749, 'author_profile': 'https://Stackoverflow.com/users/14749', 'pm_score': 4, 'selected': False, 'text': '<p>There are several answers in this thread showing how to \nextend the Array object via its prototype. This is a BAD \nIDEA, because it breaks the <code>for (i in a)</code> statement.</p>\n\n<p>So is it okay if you don\'t happen to use <code>for (i in a)</code> \nanywhere in your code? Well, only if your own code is the \nonly code that you are running, which is not too likely \ninside a browser. I\'m afraid that if folks start extending \ntheir Array objects like this, Stack Overflow will start \noverflowing with a bunch of mysterious JavaScript bugs.</p>\n\n<p>See helpful details <a href="http://web-graphics.com/2006/05/23/on-modifying-prototypes-of-javascript-built-ins/" rel="nofollow noreferrer">here</a>.</p>\n'}, {'answer_id': 123136, 'author': 'travis', 'author_id': 1414, 'author_profile': 'https://Stackoverflow.com/users/1414', 'pm_score': 4, 'selected': False, 'text': "<p>Here's a couple of shortcuts:</p>\n\n<pre><code>var a = []; // equivalent to new Array()\nvar o = {}; // equivalent to new Object()\n</code></pre>\n"}, {'answer_id': 128867, 'author': 'ScottKoon', 'author_id': 1538, 'author_profile': 'https://Stackoverflow.com/users/1538', 'pm_score': 7, 'selected': False, 'text': '<p>I\'d have to say self-executing functions.</p>\n\n<pre><code>(function() { alert("hi there");})();\n</code></pre>\n\n<p>Because Javascript <a href="https://stackoverflow.com/questions/61088/hidden-features-of-javascript/61173#61173">doesn\'t have block scope</a>, you can use a self-executing function if you want to define local variables:</p>\n\n<pre><code>(function() {\n  var myvar = 2;\n  alert(myvar);\n})();\n</code></pre>\n\n<p>Here, <code>myvar</code> is does not interfere with or pollute the global scope, and disappears when the function terminates.</p>\n'}, {'answer_id': 143666, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 3, 'selected': False, 'text': '<p>The == operator has a very special property, that creates this disturbing equality (Yes, I know in other dynamic languages like Perl this behavior would be expected but JavaScript ususally does not try to be smart in comparisons):</p>\n\n<pre><code>&gt;&gt;&gt; 1 == true\ntrue\n&gt;&gt;&gt; 0 == false\ntrue\n&gt;&gt;&gt; 2 == true\nfalse\n</code></pre>\n'}, {'answer_id': 152545, 'author': 'Rob', 'author_id': 11715, 'author_profile': 'https://Stackoverflow.com/users/11715', 'pm_score': 4, 'selected': False, 'text': '<p>Prevent annoying errors while testing in Internet Explorer when using console.log() for Firebug:</p>\n\n<pre><code>function log(message) {\n    (console || { log: function(s) { alert(s); }).log(message);\n}\n</code></pre>\n'}, {'answer_id': 155730, 'author': 'Eugene Yokota', 'author_id': 3827, 'author_profile': 'https://Stackoverflow.com/users/3827', 'pm_score': 3, 'selected': False, 'text': '<p><code>let</code>.</p>\n\n<p>Counterpart to <a href="https://stackoverflow.com/questions/61088/hidden-features-of-javascript#61173">var\'s lack of block-scoping</a> is <code>let</code>, <a href="http://developer.mozilla.org/en/New_in_JavaScript_1.7#Block_scope_with_let" rel="nofollow noreferrer">introduced in JavaScript 1.7</a>.</p>\n\n<blockquote>\n  <ul>\n  <li>The let statement provides a way to associate values with variables\n  within the scope of a block, without\n  affecting the values of like-named\n  variables outside the block.</li>\n  <li>The let expression lets you establish variables scoped only to a\n  single expression.</li>\n  <li>The let definition defines variables whose scope is constrained\n  to the block in which they\'re defined.\n  This syntax is very much like the\n  syntax used for var.</li>\n  <li>You can also use let to establish variables that exist only within the\n  context of a for loop.</li>\n  </ul>\n</blockquote>\n\n<pre><code>  function varTest() {\n        var x = 31;\n    if (true) {\n      var x = 71;  // same variable!\n      alert(x);  // 71\n    }\n    alert(x);  // 71\n  }\n\n  function letTest() {\n    let x = 31;\n    if (true) {\n      let x = 71;  // different variable\n      alert(x);  // 71\n    }\n    alert(x);  // 31\n  }\n</code></pre>\n\n<p>As of 2008, JavaScript 1.7 is supported in FireFox 2.0+ and Safari 3.x.</p>\n'}, {'answer_id': 155761, 'author': 'Eugene Yokota', 'author_id': 3827, 'author_profile': 'https://Stackoverflow.com/users/3827', 'pm_score': 3, 'selected': False, 'text': '<p><a href="http://developer.mozilla.org/en/New_in_JavaScript_1.7#Generators_and_iterators" rel="nofollow noreferrer">Generators and Iterators</a> (works only in Firefox 2+ and Safari).</p>\n\n<pre><code>function fib() {\n  var i = 0, j = 1;\n  while (true) {\n    yield i;\n    var t = i;\n    i = j;\n    j += t;\n  }\n}\n\nvar g = fib();\nfor (var i = 0; i &lt; 10; i++) {\n  document.write(g.next() + "&lt;br&gt;\\n");\n}\n</code></pre>\n\n<blockquote>\n  <p>The function containing the <code>yield</code>\n  keyword is a generator. When you call\n  it, its formal parameters are bound to\n  actual arguments, but its body isn\'t\n  actually evaluated. Instead, a\n  generator-iterator is returned. Each\n  call to the generator-iterator\'s\n  <code>next()</code> method performs another pass\n  through the iterative algorithm. Each\n  step\'s value is the value specified by\n  the <code>yield</code> keyword. Think of <code>yield</code> as\n  the generator-iterator version of\n  return, indicating the boundary\n  between each iteration of the\n  algorithm. Each time you call <code>next()</code>,\n  the generator code resumes from the\n  statement following the <code>yield</code>.</p>\n  \n  <p>In normal usage, iterator objects are\n  "invisible"; you won\'t need to operate\n  on them explicitly, but will instead\n  use JavaScript\'s <code>for...in</code> and <code>for each...in</code> statements to loop naturally\n  over the keys and/or values of\n  objects.</p>\n</blockquote>\n\n<pre><code>var objectWithIterator = getObjectSomehow();\n\nfor (var i in objectWithIterator)\n{\n  document.write(objectWithIterator[i] + "&lt;br&gt;\\n");\n}\n</code></pre>\n'}, {'answer_id': 155805, 'author': 'Ates Goral', 'author_id': 23501, 'author_profile': 'https://Stackoverflow.com/users/23501', 'pm_score': 6, 'selected': False, 'text': "<p>To properly remove a property from an object, you should delete the property instead of just setting it to <em>undefined</em>:</p>\n\n<pre><code>var obj = { prop1: 42, prop2: 43 };\n\nobj.prop2 = undefined;\n\nfor (var key in obj) {\n    ...\n</code></pre>\n\n<p>The property <em>prop2</em> will still be part of the iteration. If you want to completely get rid of <em>prop2</em>, you should instead do:</p>\n\n<pre><code>delete obj.prop2;\n</code></pre>\n\n<p>The property <em>prop2</em> will no longer will make an appearance when you're iterating through the properties.</p>\n"}, {'answer_id': 156290, 'author': 'Ates Goral', 'author_id': 23501, 'author_profile': 'https://Stackoverflow.com/users/23501', 'pm_score': 7, 'selected': False, 'text': '<p>If you\'re Googling for a decent JavaScript reference on a given topic, include the "mdc" keyword in your query and your first results will be from the Mozilla Developer Center. I don\'t carry any offline references or books with me. I always use the "mdc" keyword trick to directly get to what I\'m looking for. For example:</p>\n\n<p>Google: <a href="http://www.google.com/search?q=javascript+array+sort+mdc" rel="nofollow noreferrer">javascript array sort mdc</a><br>\n(in most cases you may omit "javascript")</p>\n\n<p><strong>Update:</strong> Mozilla Developer <strong>Center</strong> has been renamed to Mozilla Developer <strong>Network</strong>. The "mdc" keyword trick still works, but soon enough we may have to <strong>start using "mdn" instead</strong>.</p>\n'}, {'answer_id': 158462, 'author': 'Ates Goral', 'author_id': 23501, 'author_profile': 'https://Stackoverflow.com/users/23501', 'pm_score': 3, 'selected': False, 'text': '<p>If you blindly <code>eval()</code> a JSON string to deserialize it, you may run into problems:</p>\n\n<ol>\n<li>It\'s not secure. The string may contain malicious function calls!</li>\n<li><p>If you don\'t enclose the JSON string in parentheses, property names can be mistaken as labels, resulting in unexpected behaviour or a syntax error:</p>\n\n<pre><code>eval("{ \\"foo\\": 42 }"); // syntax error: invalid label\neval("({ \\"foo\\": 42 })"); // OK\n</code></pre></li>\n</ol>\n'}, {'answer_id': 170904, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 0, 'selected': False, 'text': '<blockquote>\n  <p>function l(f,n){n&amp;&amp;l(f,n-1,f(n));}</p>\n  \n  <p>l( function( loop ){ alert( loop ); },\n  5 );</p>\n</blockquote>\n\n<p>alerts 5, 4, 3, 2, 1</p>\n'}, {'answer_id': 179154, 'author': 'Ates Goral', 'author_id': 23501, 'author_profile': 'https://Stackoverflow.com/users/23501', 'pm_score': 2, 'selected': False, 'text': '<p>To convert a floating point number to an integer, you can use one of the following cryptic hacks (please don\'t):</p>\n\n<ol>\n<li><code>3.14 &gt;&gt; 0</code> (via <a href="https://stackoverflow.com/questions/173070/29999999999999999-5">2.9999999999999999 &gt;&gt; .5?</a>)</li>\n<li><code>3.14 | 0</code> (via <a href="https://stackoverflow.com/questions/131406/what-is-the-best-method-to-convert-to-an-integer-in-javascript">What is the best method to convert floating point to an integer in JavaScript?</a>)</li>\n<li><code>3.14 &amp; -1</code></li>\n<li><code>3.14 ^ 0</code></li>\n<li><code>~~3.14</code></li>\n</ol>\n\n<p>Basically, applying any binary operation on the float that won\'t change the final value (i.e. identity function) ends up converting the float to an integer.</p>\n'}, {'answer_id': 182493, 'author': 'cllpse', 'author_id': 20946, 'author_profile': 'https://Stackoverflow.com/users/20946', 'pm_score': 2, 'selected': False, 'text': '<p><strong>jQuery and JavaScript:</strong></p>\n\n<p>Variable-names can contain a number of odd characters. I use the $ character to identify variables containing jQuery objects:</p>\n\n<pre><code>var $links = $("a");\n\n$links.hide();\n</code></pre>\n\n<p>jQuery\'s pattern of chaining objects is quite nice, but applying this pattern can get a bit confusing. Fortunately JavaScript allows you to break lines, like so:</p>\n\n<pre><code>$("a")\n.hide()\n.fadeIn()\n.fadeOut()\n.hide();\n</code></pre>\n\n<p><strong>General JavaScript:</strong></p>\n\n<p>I find it useful to emulate scope by using self-executing functions:</p>\n\n<pre><code>function test()\n{\n    // scope of test()\n\n    (function()\n    {\n        // scope inside the scope of test()\n    }());\n\n    // scope of test()\n}\n</code></pre>\n'}, {'answer_id': 224227, 'author': 'Justin Love', 'author_id': 30203, 'author_profile': 'https://Stackoverflow.com/users/30203', 'pm_score': 3, 'selected': False, 'text': "<p>Function statements and function expressions are handled differently.</p>\n\n<pre><code>function blarg(a) {return a;} // statement\nbleep = function(b) {return b;} //expression\n</code></pre>\n\n<p>All function statements are parsed before code is run - a function at the bottom of a JavaScript file will be available in the first statement.  On the other hand, it won't be able to take advantage of certain dynamic context, such as surrounding <code>with</code> statements - the <code>with</code> hasn't been executed when the function is parsed.</p>\n\n<p>Function expressions execute inline, right where they are encountered.  They aren't available before that time, but they can take advantage of dynamic context.</p>\n"}, {'answer_id': 238770, 'author': 'Már Örlygsson', 'author_id': 16271, 'author_profile': 'https://Stackoverflow.com/users/16271', 'pm_score': 5, 'selected': False, 'text': '<p><strong>Prototypal inheritance</strong> (popularized by Douglas Crockford) completely revolutionizes the way you think about loads of things in Javascript.</p>\n\n<pre><code>Object.beget = (function(Function){\n    return function(Object){\n        Function.prototype = Object;\n        return new Function;\n    }\n})(function(){});\n</code></pre>\n\n<p>It\'s a killer! Pity how almost no one uses it.</p>\n\n<p>It allows you to "beget" new instances of any object, extend them, while maintaining a (live) prototypical inheritance link to their other properties.  Example:</p>\n\n<pre><code>var A = {\n  foo : \'greetings\'\n};  \nvar B = Object.beget(A);\n\nalert(B.foo);     // \'greetings\'\n\n// changes and additionns to A are reflected in B\nA.foo = \'hello\';\nalert(B.foo);     // \'hello\'\n\nA.bar = \'world\';\nalert(B.bar);     // \'world\'\n\n\n// ...but not the other way around\nB.foo = \'wazzap\';\nalert(A.foo);     // \'hello\'\n\nB.bar = \'universe\';\nalert(A.bar);     // \'world\'\n</code></pre>\n'}, {'answer_id': 302545, 'author': 'bbrown', 'author_id': 20595, 'author_profile': 'https://Stackoverflow.com/users/20595', 'pm_score': 3, 'selected': False, 'text': '<p><code>window.name</code>\'s value persists across page changes, can be read by the parent window if in same domain (if in an iframe, use <code>document.getElementById("your frame\'s ID").contentWindow.name</code> to access it), and is limited only by available memory.</p>\n'}, {'answer_id': 347540, 'author': 'Andreas Grech', 'author_id': 44084, 'author_profile': 'https://Stackoverflow.com/users/44084', 'pm_score': 5, 'selected': False, 'text': "<p>Be sure to use the <strong>hasOwnProperty</strong> method when iterating through an object's properties:</p>\n\n<pre><code>for (p in anObject) {\n    if (anObject.hasOwnProperty(p)) {\n        //Do stuff with p here\n    }\n}\n</code></pre>\n\n<p>This is done so that you will only access the <strong>direct properties of <em>anObject</em></strong>, and not use the properties that are down the prototype chain.</p>\n"}, {'answer_id': 347552, 'author': 'Andreas Grech', 'author_id': 44084, 'author_profile': 'https://Stackoverflow.com/users/44084', 'pm_score': 4, 'selected': False, 'text': '<p>When you want to remove an element from an array, one can use the <strong><em>delete</em></strong> operator, as such:</p>\n\n<pre><code>var numbers = [1,2,3,4,5];\ndelete numbers[3];\n//numbers is now [1,2,3,undefined,5]\n</code></pre>\n\n<p>As you can see, the element was removed, but a hole was left in the array since the element was replaced with an <em>undefined</em> value.</p>\n\n<p>Thus, to work around this problem, instead of using <em>delete</em>, use the <strong><em>splice</em></strong> array method...as such:</p>\n\n<pre><code>var numbers = [1,2,3,4,5];\nnumbers.splice(3,1);\n//numbers is now [1,2,3,5]\n</code></pre>\n\n<p>The first argument of <strong><em>splice</em></strong> is an ordinal in the array [index], and the second is the number of elements to delete.</p>\n'}, {'answer_id': 414508, 'author': 'Binoj Antony', 'author_id': 33015, 'author_profile': 'https://Stackoverflow.com/users/33015', 'pm_score': 3, 'selected': False, 'text': '<p>Microsofts <a href="http://en.wikipedia.org/wiki/XMLHttpRequest" rel="nofollow noreferrer">gift to JavaScript</a>: AJAX</p>\n\n<pre><code>AJAXCall(\'http://www.abcd.com/\')\n\nfunction AJAXCall(url) {\n var client = new XMLHttpRequest();\n client.onreadystatechange = handlerFunc;\n client.open("GET", url);\n client.send();\n}\n\nfunction handlerFunc() {\n if(this.readyState == 4 &amp;&amp; this.status == 200) {\n if(this.responseXML != null)\n   document.write(this.responseXML)\n }\n}\n</code></pre>\n'}, {'answer_id': 460884, 'author': 'Remy Sharp', 'author_id': 22617, 'author_profile': 'https://Stackoverflow.com/users/22617', 'pm_score': 2, 'selected': False, 'text': "<p>Large loops are faster in <code>while</code>-condition and backwards - that is, if the order of the loop doesn't matter to you. In about 50% of my code, it usually doesn't.</p>\n\n<p>i.e. </p>\n\n<pre><code>var i, len = 100000;\n\nfor (var i = 0; i &lt; len; i++) {\n  // do stuff\n}\n</code></pre>\n\n<p>Is slower than:</p>\n\n<pre><code>i = len;\nwhile (i--) {\n  // do stuff\n}\n</code></pre>\n"}, {'answer_id': 476923, 'author': 'Paweł Witkowski Photography', 'author_id': 58260, 'author_profile': 'https://Stackoverflow.com/users/58260', 'pm_score': 2, 'selected': False, 'text': '<p>There is also an almost unknown JavaScript syntax:</p>\n\n<pre><code>var a;\na=alert(5),7;\nalert(a);    // alerts undefined\na=7,alert(5);\nalert(a);    // alerts 7\n\na=(3,6);\nalert(a);    // alerts 6\n</code></pre>\n\n<p>More about this <a href="https://stackoverflow.com/questions/476218/javascript-syntax-of-a-object-object">here</a>.</p>\n'}, {'answer_id': 490143, 'author': 'Breton', 'author_id': 51101, 'author_profile': 'https://Stackoverflow.com/users/51101', 'pm_score': 5, 'selected': False, 'text': '<p>You can use objects instead of switches most of the time.</p>\n\n<pre><code>function getInnerText(o){\n    return o === null? null : {\n        string: o,\n        array: o.map(getInnerText).join(""),\n        object:getInnerText(o["childNodes"])\n    }[typeis(o)];\n}\n</code></pre>\n\n<p>Update: if you\'re concerned about the cases evaluating in advance being inefficient (why are you worried about efficiency this early on in the design of the program??) then you can do something like this:</p>\n\n<pre><code>function getInnerText(o){\n    return o === null? null : {\n        string: function() { return o;},\n        array: function() { return o.map(getInnerText).join(""); },\n        object: function () { return getInnerText(o["childNodes"]; ) }\n    }[typeis(o)]();\n}\n</code></pre>\n\n<p>This is more onerous to type (or read) than either a switch or an object, but it preserves the benefits of using an object instead of a switch, detailed in the comments section below. This style also makes it more straightforward to spin this out into a proper "class" once it grows up enough.</p>\n\n<p>update2: with proposed syntax extensions for ES.next, this becomes</p>\n\n<pre><code>let getInnerText = o -&gt; ({\n    string: o -&gt; o,\n    array: o -&gt; o.map(getInnerText).join(""),\n    object: o -&gt; getInnerText(o["childNodes"])\n}[ typeis o ] || (-&gt;null) )(o);\n</code></pre>\n'}, {'answer_id': 490169, 'author': 'Ionuț G. Stan', 'author_id': 58808, 'author_profile': 'https://Stackoverflow.com/users/58808', 'pm_score': 5, 'selected': False, 'text': '<p>You may catch exceptions depending on their type. Quoted from <a href="https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Statements/try...catch" rel="nofollow noreferrer">MDC</a>:</p>\n\n<pre><code>try {\n   myroutine(); // may throw three exceptions\n} catch (e if e instanceof TypeError) {\n   // statements to handle TypeError exceptions\n} catch (e if e instanceof RangeError) {\n   // statements to handle RangeError exceptions\n} catch (e if e instanceof EvalError) {\n   // statements to handle EvalError exceptions\n} catch (e) {\n   // statements to handle any unspecified exceptions\n   logMyErrors(e); // pass exception object to error handler\n}\n</code></pre>\n\n<p><strong>NOTE:</strong> Conditional catch clauses are a Netscape (and hence Mozilla/Firefox) extension that is not part of the ECMAScript specification and hence cannot be relied upon except on particular browsers.</p>\n'}, {'answer_id': 490546, 'author': 'Breton', 'author_id': 51101, 'author_profile': 'https://Stackoverflow.com/users/51101', 'pm_score': 3, 'selected': False, 'text': '<p>You can turn "any* object with integer properties, and a length property into an array proper, and thus endow it with all array methods such as push, pop, splice, map, filter, reduce, etc.</p>\n\n<pre><code>Array.prototype.slice.call({"0":"foo", "1":"bar", 2:"baz", "length":3 }) \n</code></pre>\n\n<p>// returns ["foo", "bar", "baz"]</p>\n\n<p>This works with jQuery objects, html collections, and Array objects from other frames (as one possible solution to the whole array type thing).  I say, if it\'s got a length property, you can turn it into an array and it doesn\'t matter. There\'s lots of non array objects with a length property, beyond the arguments object.</p>\n'}, {'answer_id': 625580, 'author': 'cllpse', 'author_id': 20946, 'author_profile': 'https://Stackoverflow.com/users/20946', 'pm_score': 2, 'selected': False, 'text': "<p><strong>Syntactic sugar: in-line for-loop closures</strong></p>\n\n<pre><code>var i;\n\nfor (i = 0; i &lt; 10; i++) (function ()\n{\n    // do something with i\n}());\n</code></pre>\n\n<p>Breaks almost all of Douglas Crockford's code-conventions, but I think it's quite nice to look at, never the less :)</p>\n\n<hr>\n\n<p>Alternative:</p>\n\n<pre><code>var i;\n\nfor (i = 0; i &lt; 10; i++) (function (j)\n{\n    // do something with j\n}(i));\n</code></pre>\n"}, {'answer_id': 628728, 'author': 'Ates Goral', 'author_id': 23501, 'author_profile': 'https://Stackoverflow.com/users/23501', 'pm_score': 2, 'selected': False, 'text': '<p>This seems to only work on Firefox (SpiderMonkey). Inside a function:</p>\n\n<ul>\n<li><code>arguments[-2]</code> gives the number of arguments (same as <code>arguments.length</code>)</li>\n<li><code>arguments[-3]</code> gives the function that was called  (same as <code>arguments.callee</code>)</li>\n</ul>\n'}, {'answer_id': 645331, 'author': 'nickytonline', 'author_id': 77814, 'author_profile': 'https://Stackoverflow.com/users/77814', 'pm_score': 2, 'selected': False, 'text': '<p>Existence checks. So often I see stuff like this</p>\n\n<pre><code>var a = [0, 1, 2];\n\n// code that might clear the array.\n\nif (a.length &gt; 0) {\n // do something\n}\n</code></pre>\n\n<p>instead for example just do this:</p>\n\n<pre><code>var a = [0, 1, 2];\n\n// code that might clear the array.\n\nif (a.length) { // if length is not equal to 0, this will be true\n // do something\n}\n</code></pre>\n\n<p>There\'s all kinds of existence checks you can do, but this was just a simple example to illustrate a point</p>\n\n<p>Here\'s an example on how to use a default value.</p>\n\n<pre><code>function (someArgument) {\n      someArgument || (someArgument = "This is the deault value");\n}\n</code></pre>\n\n<p>That\'s my two cents. There\'s other nuggets, but that\'s it for now.</p>\n'}, {'answer_id': 692380, 'author': 'Lucent', 'author_id': 6385, 'author_profile': 'https://Stackoverflow.com/users/6385', 'pm_score': 4, 'selected': False, 'text': '<p>You never have to use <code>eval()</code> to assemble global variable names.</p>\n\n<p>That is, if you have several globals (for whatever reason) named <code>spec_grapes, spec_apples</code>, you do not have to access them with <code>eval("spec_" + var)</code>.</p>\n\n<p>All globals are members of <code>window[]</code>, so you can do <code>window["spec_" + var]</code>.</p>\n'}, {'answer_id': 731342, 'author': 'e-satis', 'author_id': 9951, 'author_profile': 'https://Stackoverflow.com/users/9951', 'pm_score': 2, 'selected': False, 'text': '<h2>You can iterate over Arrays using "for in"</h2>\n\n<p>Mark Cidade pointed out the usefullness of the "for in" loop :</p>\n\n<pre><code>// creating an object (the short way, to use it like a hashmap)\nvar diner = {\n"fruit":"apple"\n"veggetable"="bean"\n}\n\n// looping over its properties\nfor (meal_name in diner ) {\n    document.write(meal_name+"&lt;br \\n&gt;");\n}\n</code></pre>\n\n<p>Result :</p>\n\n<pre><code>fruit\nveggetable\n</code></pre>\n\n<p>But there is more. Since you can use an object like an associative array, you can process keys and values,\njust like a foreach loop :</p>\n\n<pre><code>// looping over its properties and values\nfor (meal_name in diner ) {\n    document.write(meal_name+" : "+diner[meal_name]+"&lt;br \\n&gt;");\n}\n</code></pre>\n\n<p>Result :</p>\n\n<pre><code>fruit : apple\nveggetable : bean\n</code></pre>\n\n<p>And since Array are objects too, you can iterate other array the exact same way :</p>\n\n<pre><code>var my_array = [\'a\', \'b\', \'c\'];\nfor (index in my_array ) {\n    document.write(index+" : "+my_array[index]+"&lt;br \\n&gt;");\n}\n</code></pre>\n\n<p>Result :</p>\n\n<pre><code>0 : a\n1 : b\n3 : c\n</code></pre>\n\n<h2>You can remove easily an known element from an array</h2>\n\n<pre><code>var arr = [\'a\', \'b\', \'c\', \'d\'];\nvar pos = arr.indexOf(\'c\');\npos &gt; -1 &amp;&amp; arr.splice( pos, 1 );\n</code></pre>\n\n<h2>You can shuffle easily an array</h2>\n\n<p><strike><code>arr.sort(function() Math.random() - 0.5);</code></strike> – not really random distribution, see comments.</p>\n'}, {'answer_id': 731411, 'author': 'David', 'author_id': 21909, 'author_profile': 'https://Stackoverflow.com/users/21909', 'pm_score': 3, 'selected': False, 'text': '<p>The parentheses are optional when creating new "objects".</p>\n\n<pre><code>function Animal () {\n\n}\n\nvar animal = new Animal();\nvar animal = new Animal;\n</code></pre>\n\n<p>Same thing.</p>\n'}, {'answer_id': 841201, 'author': 'username', 'author_id': 4939, 'author_profile': 'https://Stackoverflow.com/users/4939', 'pm_score': 4, 'selected': False, 'text': '<p>You can assign local variables using [] on the left hand side. Comes in handy if you want to return more than one value from a function without creating a needless array.</p>\n\n<pre><code>function fn(){\n    var cat = "meow";\n    var dog = "woof";\n    return [cat,dog];\n};\n\nvar [cat,dog] = fn();  // Handy!\n\nalert(cat);\nalert(dog);\n</code></pre>\n\n<p><s>It\'s part of core JS but somehow I never realized till this year.</s></p>\n'}, {'answer_id': 843499, 'author': 'Gumbo', 'author_id': 53114, 'author_profile': 'https://Stackoverflow.com/users/53114', 'pm_score': 1, 'selected': False, 'text': '<p><a href="http://code.google.com/p/jslibs/wiki/JavascriptTips" rel="nofollow noreferrer">JavaScript tips</a> or the <a href="http://code.google.com/p/jslibs/" rel="nofollow noreferrer">jslibs project</a>.</p>\n'}, {'answer_id': 865753, 'author': 'Sebastian Schuth', 'author_id': 107339, 'author_profile': 'https://Stackoverflow.com/users/107339', 'pm_score': 2, 'selected': False, 'text': '<p>Maybe one of the lesser-known ones:</p>\n\n<p>arguments.callee.caller + Function#toString()</p>\n\n<pre><code>function called(){\n    alert("Go called by:\\n"+arguments.callee.caller.toString());\n}\n\nfunction iDoTheCall(){\n    called();\n}\n\niDoTheCall();\n</code></pre>\n\n<p>Prints out the source code of <code>iDoTheCall</code> --\nDeprecated, but can be useful sometimes when alerting is your only option....</p>\n'}, {'answer_id': 955784, 'author': 'pawelsto', 'author_id': 109208, 'author_profile': 'https://Stackoverflow.com/users/109208', 'pm_score': 1, 'selected': False, 'text': '<p>You can bind a JavaScript object as a HTML element attribute.</p>\n\n<pre><code>&lt;div id="jsTest"&gt;Klick Me&lt;/div&gt;\n&lt;script type="text/javascript"&gt;\n    var someVariable = \'I was klicked\';\n    var divElement = document.getElementById(\'jsTest\');\n    // binding function/object or anything as attribute\n    divElement.controller = function() { someVariable += \'*\'; alert(\'You can change instance data:\\n\' + someVariable ); };\n    var onclickFunct = new Function( \'this.controller();\' ); // Works in Firefox and Internet Explorer.\n    divElement.onclick = onclickFunct;\n&lt;/script&gt;\n</code></pre>\n'}, {'answer_id': 1024826, 'author': 'Metal', 'author_id': 75025, 'author_profile': 'https://Stackoverflow.com/users/75025', 'pm_score': 3, 'selected': False, 'text': '<p>If you\'re attempting to sandbox javascript code, and disable every possible way to evaluate strings into javascript code, be aware that blocking all the obvious eval/document.write/new Function/setTimeout/setInterval/innerHTML and other DOM manipulations isn\'t enough.</p>\n\n<p>Given any object o, <code>o.constructor.constructor("alert(\'hi\')")()</code> will bring up an alert dialog with the word "hi" in it.</p>\n\n<p>You could rewrite it as</p>\n\n<pre><code>var Z="constructor";\nZ[Z][Z]("alert(\'hi\')")();\n</code></pre>\n\n<p>Fun stuff.</p>\n'}, {'answer_id': 1025127, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 3, 'selected': False, 'text': '<p>The fastest loops in JavaScript are while(i--) ones. In all browsers.\nSo if it\'s not that important for order in which elements of your loop get processed you should be using while(i--) form:</p>\n\n<pre><code>var names = new Array(1024), i = names.length;\nwhile(i--)\n  names[i] = "John" + i;\n</code></pre>\n\n<p>Also, if you have to use for() loop going forward, remember always to cache .length property:</p>\n\n<pre><code>var birds = new Array(1024); \nfor(var i = 0, j = birds.length; i &lt; j; i++)\n  birds[i].fly();\n</code></pre>\n\n<p>To join large strings use Arrays (it\'s faster):</p>\n\n<pre><code>var largeString = new Array(1024), i = largeString.length;\nwhile(i--) {\n  // It\'s faster than for() loop with largeString.push(), obviously :)\n  largeString[i] = i.toString(16);\n}\n\nlargeString = largeString.join("");\n</code></pre>\n\n<p>It\'s much faster than <code>largeString += "something"</code> inside an loop.</p>\n'}, {'answer_id': 1025990, 'author': 'Justin Johnson', 'author_id': 126562, 'author_profile': 'https://Stackoverflow.com/users/126562', 'pm_score': 1, 'selected': False, 'text': '<p>The coalescing operator is very cool and makes for some clean, concise code, especially when you chain it together: <code>a || b || c || "default";</code>  The gotcha is that since it works by evaluating to bool rather than null, if values that evaluate to false are valid, they\'ll often times get over looked.  Not to worry, in these cases just revert to the good ol\' ternary operator.  </p>\n\n<p>I often see code that has given up and used global instead of static variables, so here\'s how (in an example of what I suppose you could call a generic singleton factory):</p>\n\n<pre><code>var getInstance = function(objectName) {\n  if ( !getInstance.instances ) {\n    getInstance.instances = {};\n  }\n\n  if ( !getInstance.instances[objectName] ) {\n    getInstance.instances[objectName] = new window[objectName];\n  }\n\n  return getInstance.instances[objectName];\n};\n</code></pre>\n\n<p>Also, note the <code>new window[objectName];</code> which was the key to generically instantiating objects by name. I just figured that out 2 months ago.</p>\n\n<p>In the same spirit, when working with the DOM, I often bury functioning parameters and/or flags into DOM nodes when I first initialize whatever functionality I\'m adding.  I\'ll add an example if someone squawks.</p>\n\n<p>Surprisingly, no one on the first page has mentioned <code>hasOwnProperty</code>, which is a shame.  When using <code>in</code> for iteration, it\'s good, defensive programming to use the <code>hasOwnProperty</code> method on the container being iterated over to make sure that the member names being used are the ones that you expect.</p>\n\n<pre><code>var x = [1,2,3];\nfor ( i in x ) {\n    if ( !x.hasOwnProperty(i) )  { continue; }\n    console.log(i, x[i]);\n}\n</code></pre>\n\n<p><a href="http://ajaxian.com/archives/fun-with-browsers-for-in-loop" rel="nofollow noreferrer">Read here</a> for more on this.</p>\n\n<p>Lastly, <code>with</code> is almost always a bad idea.</p>\n'}, {'answer_id': 1043658, 'author': 'Blixt', 'author_id': 119081, 'author_profile': 'https://Stackoverflow.com/users/119081', 'pm_score': 1, 'selected': False, 'text': '<p>You can make "classes" that have private (inaccessible outside the "class" definition) static and non-static members, in addition to public members, using closures.</p>\n\n<p>Note that there are two types of public members in the code below. Instance-specific (defined in the constructor) that have access to private <em>instance</em> members, and shared members (defined in the <code>prototype</code> object) that only have access to private <em>static</em> members.</p>\n\n<pre><code>var MyClass = (function () {\n    // private static\n    var nextId = 1;\n\n    // constructor\n    var cls = function () {\n        // private\n        var id = nextId++;\n        var name = \'Unknown\';\n\n        // public (this instance only)\n        this.get_id = function () { return id; };\n\n        this.get_name = function () { return name; };\n        this.set_name = function (value) {\n            if (typeof value != \'string\')\n                throw \'Name must be a string\';\n            if (value.length &lt; 2 || value.length &gt; 20)\n                throw \'Name must be 2-20 characters long.\';\n            name = value;\n        };\n    };\n\n    // public static\n    cls.get_nextId = function () {\n        return nextId;\n    };\n\n    // public (shared across instances)\n    cls.prototype = {\n        announce: function () {\n            alert(\'Hi there! My id is \' + this.get_id() + \' and my name is "\' + this.get_name() + \'"!\\r\\n\' +\n                  \'The next fellow\\\'s id will be \' + MyClass.get_nextId() + \'!\');\n        }\n    };\n\n    return cls;\n})();\n</code></pre>\n\n<p>To test this code:</p>\n\n<pre><code>var mc1 = new MyClass();\nmc1.set_name(\'Bob\');\n\nvar mc2 = new MyClass();\nmc2.set_name(\'Anne\');\n\nmc1.announce();\nmc2.announce();\n</code></pre>\n\n<p>If you have Firebug you\'ll find that there is no way to get access to the private members other than to set a breakpoint inside the closure that defines them.</p>\n\n<p>This pattern is very useful when defining classes that need strict validation on values, and complete control of state changes.</p>\n\n<p>To extend this class, you would put <code>MyClass.call(this);</code> at the top of the constructor in the extending class. You would also need to <strong>copy</strong> the <code>MyClass.prototype</code> object (don\'t reuse it, as you would change the members of <code>MyClass</code> as well.</p>\n\n<p>If you were to replace the <code>announce</code> method, you would call <code>MyClass.announce</code> from it like so: <code>MyClass.prototype.announce.call(this);</code></p>\n'}, {'answer_id': 1131595, 'author': 'RaYell', 'author_id': 137467, 'author_profile': 'https://Stackoverflow.com/users/137467', 'pm_score': 2, 'selected': False, 'text': '<p>JavaScript <code>typeof</code> operator used with arrays or nulls always returns <code>object</code> value which in some cases may not be what programmer would expect.</p>\n\n<p>Here\'s a function that will return proper values for those items as well. Array recognition was copied from Douglas Crockford\'s book "JavaScript: The Good Parts".</p>\n\n<pre><code>function typeOf (value) {\n    var type = typeof value;\n    if (type === \'object\') {\n        if (value === null) {\n             type = \'null\';\n        } else if (typeof value.length === \'number\' &amp;&amp; \n            typeof value.splice === \'function\' &amp;&amp; \n            !value.propertyIsEnumerable(\'length\')) {\n            type = \'array\';\n        }\n    }\n    return type;\n}\n</code></pre>\n'}, {'answer_id': 1162208, 'author': 'gotch4', 'author_id': 138606, 'author_profile': 'https://Stackoverflow.com/users/138606', 'pm_score': 1, 'selected': False, 'text': '<p>Using <strong>Function.apply</strong> to specify the object that the function will work on:</p>\n\n<p>Suppose you have the class</p>\n\n<pre><code>function myClass(){\n this.fun = function(){\n   do something;\n };\n}\n</code></pre>\n\n<p>if later you do:</p>\n\n<pre><code>var a = new myClass();\nvar b = new myClass();\n\nmyClass.fun.apply(b); //this will be like b.fun();\n</code></pre>\n\n<p>You can even specify an array of call parameters as a secondo argument</p>\n\n<p>look this: <a href="https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Function/apply" rel="nofollow noreferrer">https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Function/apply</a></p>\n'}, {'answer_id': 1176498, 'author': 'outis', 'author_id': 90527, 'author_profile': 'https://Stackoverflow.com/users/90527', 'pm_score': 1, 'selected': False, 'text': '<p>My first submission is not so much a hidden feature as a rarely used application of the property re-definition feature. Because you can redefine an object\'s methods, you can cache the result of a method call, which is useful if the calculation is expensive and you want lazy evaluation. This gives the simplest form of <a href="http://en.wikipedia.org/wiki/Memoization" rel="nofollow noreferrer">memoization</a>.</p>\n\n<pre><code>function Circle(r) {\n    this.setR(r);\n}\n\nCircle.prototype = {\n  recalcArea: function() {\n        this.area=function() {\n            area = this.r * this.r * Math.PI;\n            this.area = function() {return area;}\n            return area;\n        }\n    },\n  setR: function (r) {\n      this.r = r;\n      this.invalidateR();\n    },\n  invalidateR: function() {\n        this.recalcArea();\n    }\n}\n</code></pre>\n\n<p>Refactor the code that caches the result into a method and you get:</p>\n\n<pre><code>Object.prototype.cacheResult = function(name, _get) {\n  this[name] = function() {\n    var result = _get.apply(this, arguments);\n    this[name] = function() {\n      return result;\n    }\n    return result;\n  };\n};\n\nfunction Circle(r) {\n    this.setR(r);\n}\n\nCircle.prototype = {\n  recalcArea: function() {\n        this.cacheResult(\'area\', function() { return this.r * this.r * Math.PI; });\n    },\n  setR: function (r) {\n      this.r = r;\n      this.invalidateR();\n    },\n  invalidateR: function() {\n        this.recalcArea();\n    }\n}\n</code></pre>\n\n<p>If you want a memoized function, you can have that instead. Property re-definition isn\'t involved.</p>\n\n<pre><code>Object.prototype.memoize = function(name, implementation) {\n    this[name] = function() {\n        var argStr = Array.toString.call(arguments);\n        if (typeof(this[name].memo[argStr]) == \'undefined\') {\n            this[name].memo[argStr] = implementation.apply(this, arguments);\n        }\n        return this[name].memo[argStr];\n    }\n};\n</code></pre>\n\n<p>Note that this relies on the standard array toString conversion and often won\'t work properly. Fixing it is left as an exercise for the reader.</p>\n\n<p>My second submission is getters and setters. I\'m surprised they haven\'t been mentioned yet. Because the official standard differs from the de facto standard (defineProperty vs. <strong>define[GS]etter</strong>) and Internet Explorer barely supports the official standard, they aren\'t generally useful.  Maybe that\'s why they weren\'t mentioned. Note that you can combine getters and result caching rather nicely:</p>\n\n<pre><code>Object.prototype.defineCacher = function(name, _get) {\n    this.__defineGetter__(name, function() {\n        var result = _get.call(this);\n        this.__defineGetter__(name, function() { return result; });\n        return result;\n    })\n};\n\nfunction Circle(r) {\n    this.r = r;\n}\n\nCircle.prototype = {\n  invalidateR: function() {\n        this.recalcArea();\n    },\n  recalcArea: function() {\n        this.defineCacher(\'area\', function() {return this.r * this.r * Math.PI; });\n    },\n  get r() { return this._r; }\n  set r(r) { this._r = r; this.invalidateR(); }\n}\n\nvar unit = new Circle(1);\nunit.area;\n</code></pre>\n\n<p>Efficiently combining getters, setters and result caching is a little messier because you have to prevent the invalidation or do without automatic invalidation on set, which is what the following example does. It\'s mostly an issue if changing one property will invalidate multiple others (imagine there\'s a "diameter" property in these examples).</p>\n\n<pre><code>Object.prototype.defineRecalcer = function(name, _get) {\n  var recalcFunc;\n  this[recalcFunc=\'recalc\'+name.toCapitalized()] = function() {\n    this.defineCacher(name, _get);\n  };\n  this[recalcFunc]();\n  this.__defineSetter__(name, function(value) {\n      _set.call(this, value);\n      this.__defineGetter__(name, function() {return value; });\n  });\n};\n\nfunction Circle(r) {\n    this.defineRecalcer(\'area\',\n             function() {return this.r * this.r * Math.PI;},\n             function(area) {this._r = Math.sqrt(area / Math.PI);},\n    );\n    this.r = r;\n}\n\nCircle.prototype = {\n  invalidateR: function() {\n        this.recalcArea();\n    },\n  get r() { return this._r; }\n  set r(r) { this._r = r; this.invalidateR(); }\n}\n</code></pre>\n'}, {'answer_id': 1211874, 'author': 'Fabian Jakobs', 'author_id': 129322, 'author_profile': 'https://Stackoverflow.com/users/129322', 'pm_score': 3, 'selected': False, 'text': '<p><strong>The <a href="http://yuiblog.com/blog/2007/06/12/module-pattern/" rel="nofollow noreferrer">Module Pattern</a></strong></p>\n\n<pre><code>&lt;script type="text/javascript"&gt;\n(function() {\n\nfunction init() {\n  // ...\n}\n\nwindow.onload = init;\n})();\n&lt;/script&gt;\n</code></pre>\n\n<p>Variables and functions declared without the <code>var</code> statement or outside of a function will be defined in the global scope. If a variable/function of the same name already exists it will be silently overridden, which can lead to very hard to find errors. A common solution is to wrap the whole code body into an anonymous function and immediately execute it. This way all variables/functions are defined in the scope of the anonymous function and don\'t leak into the global scope.</p>\n\n<p>To explicitly define a variable/function in the global scope they have to be prefixed with <code>window</code>:</p>\n\n<pre><code>window.GLOBAL_VAR = 12;\nwindow.global_function = function() {};\n</code></pre>\n'}, {'answer_id': 1211921, 'author': 'Fabian Jakobs', 'author_id': 129322, 'author_profile': 'https://Stackoverflow.com/users/129322', 'pm_score': 3, 'selected': False, 'text': '<p><strong><a href="http://www.dustindiaz.com/namespace-your-javascript/" rel="nofollow noreferrer">Namespaces</a></strong></p>\n\n<p>In larger JavaScript applications or frameworks it can be useful to organize the code in namespaces. JavaScript doesn\'t have a module or namespace concept buildin but it is easy to emulate using JavaScript objects. This would create a namespace called <code>ns</code>and attaches the function <code>foo</code>to it.</p>\n\n<pre><code>if (!window.ns) {\n  window.ns = {};\n}\n\nwindow.ns.foo = function() {};\n</code></pre>\n\n<p>It is common to use the same global namespace prefix throughout a project and use sub namespaces for each JavaScript file. The name of the sub namespace often matches the file\'s name.</p>\n\n<p>The header of a file called <code>ns/button.js</code>could look like this:</p>\n\n<pre><code>if (!window.ns) {\n  window.ns = {};\n}\nif (!window.ns.button) {\n  window.ns.button = {};\n}\n\n// attach methods to the ns.button namespace\nwindow.ns.button.create = function() {};\n</code></pre>\n'}, {'answer_id': 1318068, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 1, 'selected': False, 'text': '<p>Here\'s a simple way of thinking about \'this\'. \'This\' inside a function will refer to future object instances of the function, usually created with operator new. So clearly \'this\' of an inner function will never refer to an instance of an outer function. </p>\n\n<p>The above should keep one out of trouble. But there are more complicated things you can do with \'this.\' </p>\n\n<hr>\n\n<p>Example 1:</p>\n\n<pre><code>\n     function DriveIn()\n     {\n          this.car = \'Honda\';\n          alert(this.food);  //\'food\' is the attribute of a future object \n                             //and DriveIn does not define it.\n     }\n\n     var A = {food:\'chili\', q:DriveIn};  //create object A whose q attribute \n                                         //is the function DriveIn;\n\n     alert(A.car); //displays \'undefined\' \n     A.q();        //displays \'chili\' but also defines this.car.\n     alert(A.car); //displays \'Honda\' \n\n</code></pre>\n\n<hr>\n\n<p>The Rule of This: </p>\n\n<p>Whenever a function is called as the attribute of an object, any occurrence of \'this\' inside the function (but outside any inner functions) refers to the object.</p>\n\n<p>We need to make clear that "The Rule of This" applies even when operator new is used. Behind the scenes new attaches \'this\' to the object through the object\'s constructor attribute.</p>\n\n<hr>\n\n<p>Example 2: </p>\n\n<pre><code>\n      function Insect ()\n      {\n           this.bug = "bee";\n           this.bugFood = function()\n           {\n               alert("nectar");\n           }\n       }\n\n      var B = new Insect();\n      alert(B.constructor); //displays "Insect"; By "The Rule of This" any\n                            //ocurrence of \'this\' inside Insect now refers \n                            //to B.    \n</code></pre>\n\n<p>To make this even clearer, we can create an Insect instance without using operator new.</p>\n\n<p>Example 3:</p>\n\n<pre><code>   \n    var C = {constructor:Insect};  //Assign the constructor attribute of C, \n                                   //the value Insect.\n    C.constructor();               //Call Insect through the attribute. \n                                   //C is now an Insect instance as though it \n                                   //were created with operator new. [*]\n    alert(C.bug);                  //Displays "bee." \n    C.bugFood();                   //Displays "nectar." \n\n</code></pre>   \n\n<p>[*] The only actual difference I can discern is that in example 3, \'constructor\' is an enumerable attribute. When operator new is used \'constructor\' becomes an attribute but is not enumerable. An attribute is enumerable if the for-in operation "for(var name in object)" returns the name of the attribute.</p>\n'}, {'answer_id': 1365822, 'author': 'pramodc84', 'author_id': 40614, 'author_profile': 'https://Stackoverflow.com/users/40614', 'pm_score': 6, 'selected': False, 'text': '<p><strong><em>Know how many parameters are expected by a function</em></strong></p>\n\n<pre><code>function add_nums(num1, num2, num3 ){\n    return num1 + num2 + num3;\n}\nadd_nums.length // 3 is the number of parameters expected.\n</code></pre>\n\n<p><strong><em>Know how many parameters are received by the function</em></strong></p>\n\n<pre><code>function add_many_nums(){\n    return arguments.length;\n}    \nadd_many_nums(2,1,122,12,21,89); //returns 6\n</code></pre>\n'}, {'answer_id': 1394655, 'author': 'vsync', 'author_id': 104380, 'author_profile': 'https://Stackoverflow.com/users/104380', 'pm_score': -1, 'selected': False, 'text': "<p>Well, it's not much of a feature, but it is very useful:</p>\n\n<p>Shows selectable and formatted alerts:</p>\n\n<pre><code>alert(prompt('',something.innerHTML ));\n</code></pre>\n"}, {'answer_id': 1416391, 'author': 'Kris Kowal', 'author_id': 42586, 'author_profile': 'https://Stackoverflow.com/users/42586', 'pm_score': 2, 'selected': False, 'text': '<p>These are not <em>always</em> a good idea, but you can convert most things with terse expressions.  The important point here is that not every value in JavaScript is an object, so these expressions will succeed where member access on non-objects like null and undefined will fail.  Particularly, beware that typeof null == "object", but you can\'t null.toString(), or ("name" in null).</p>\n\n<p>Convert anything to a Number:</p>\n\n<pre><code>+anything\nNumber(anything)\n</code></pre>\n\n<p>Convert anything to an unsigned four-byte integer:</p>\n\n<pre><code>anything &gt;&gt;&gt; 0\n</code></pre>\n\n<p>Convert anything to a String:</p>\n\n<pre><code>\'\' + anything\nString(anything)\n</code></pre>\n\n<p>Convert anything to a Boolean:</p>\n\n<pre><code>!!anything\nBoolean(anything)\n</code></pre>\n\n<p>Also, using the type name without "new" behaves differently for String, Number, and Boolean, returning a primitive number, string, or boolean value, but with "new" these will returned "boxed" object types, which are nearly useless.</p>\n'}, {'answer_id': 1462261, 'author': 'Seth', 'author_id': 65295, 'author_profile': 'https://Stackoverflow.com/users/65295', 'pm_score': 4, 'selected': False, 'text': '<p>My favorite trick is using <code>apply</code> to perform a callback to an object\'s method and maintain the correct "this" variable. </p>\n\n<pre><code>function MakeCallback(obj, method) {\n    return function() {\n        method.apply(obj, arguments);\n    };\n}\n\nvar SomeClass = function() { \n     this.a = 1;\n};\nSomeClass.prototype.addXToA = function(x) {\n     this.a = this.a + x;\n};\n\nvar myObj = new SomeClass();\n\nbrokenCallback = myObj.addXToA;\nbrokenCallback(1); // Won\'t work, wrong "this" variable\nalert(myObj.a); // 1\n\n\nvar myCallback = MakeCallback(myObj, myObj.addXToA);\nmyCallback(1);  // Works as expected because of apply\nalert(myObj.a); // 2\n</code></pre>\n'}, {'answer_id': 1682820, 'author': 'Lyubomyr Shaydariv', 'author_id': 166589, 'author_profile': 'https://Stackoverflow.com/users/166589', 'pm_score': 2, 'selected': False, 'text': "<p>Hm, I didn't read the whole topic though it's quite interesting for me, but let me make a little donation:</p>\n\n<pre><code>// forget the debug alerts\nvar alertToFirebugConsole = function() {\n    if ( window.console &amp;&amp; window.console.log ) {\n        window.alert = console.log;\n    }\n}\n</code></pre>\n"}, {'answer_id': 1712004, 'author': 'Kenneth J', 'author_id': 195456, 'author_profile': 'https://Stackoverflow.com/users/195456', 'pm_score': 1, 'selected': False, 'text': '<p>function can have methods.</p>\n\n<p>I use this pattern of AJAX form submissions.</p>\n\n<pre><code>var fn = (function() {\n        var ready = true;\n        function fnX() {\n            ready = false;\n            // AJAX return function\n            function Success() {\n                ready = true;\n            }\n            Success();\n            return "this is a test";\n        }\n\n        fnX.IsReady = function() {\n            return ready;\n        }\n        return fnX;\n    })();\n\n    if (fn.IsReady()) {\n        fn();\n    }\n</code></pre>\n'}, {'answer_id': 2042069, 'author': 'Anil Namde', 'author_id': 237743, 'author_profile': 'https://Stackoverflow.com/users/237743', 'pm_score': 2, 'selected': False, 'text': '<p>JavaScript is considered to be very good at exposing all its object so no matter if its window object itself.</p>\n\n<p>So if i would like to override the browser alert with JQuery/YUI div popup which too accepts string as parameter it can be done simply using following snippet.</p>\n\n<pre>\n<code>\nfunction divPopup(str)\n{\n    //code to show the divPopup\n}\nwindow.alert = divPopup;\n</code>\n</pre>\n\n<p>With this change all the calls to the alert() will show the good new div based popup instead of the browser specific alert.</p>\n'}, {'answer_id': 2047391, 'author': 'slebetman', 'author_id': 167735, 'author_profile': 'https://Stackoverflow.com/users/167735', 'pm_score': 4, 'selected': False, 'text': "<p><strong>The Zen of Closures</strong></p>\n\n<p>Other people have mentioned closures. But it's surprising how many people know about closures, write code using closures, yet still have the wrong perception of what closures really are. Some people confuse first-class functions with closures. Yet others see it as a kind of static variable.</p>\n\n<p>To me a closure is a kind of <em>'private'</em> global variable. That is, a kind of variable that some functions see as global but other functions can't see. Now, I know this is playing fast and loose with the description of the underlying mechanism but that is how it feels like and behaves. To illustrate:</p>\n\n<pre><code>// Say you want three functions to share a single variable:\n\n// Use a self-calling function to create scope:\n(function(){\n\n    var counter = 0; // this is the variable we want to share;\n\n    // Declare global functions using function expressions:\n    increment = function(){\n        return ++counter;\n    }\n    decrement = function(){\n        return --counter;\n    }\n    value = function(){\n        return counter;\n    }\n})()\n</code></pre>\n\n<p>now the three function <code>increment</code>, <code>decrement</code> and <code>value</code> share the variable <code>counter</code> without <code>counter</code> being an actual global variable. This is the true nature of closures:</p>\n\n<pre><code>increment();\nincrement();\ndecrement();\nalert(value()); // will output 1\n</code></pre>\n\n<p>The above is not a really useful use of closures. In fact, I'd say that using it this way is an anti-pattern. But it is useful in understanding the nature of closures. For example, most people get caught when they try to do something like the following:</p>\n\n<pre><code>for (var i=1;i&lt;=10;i++) {\n    document.getElementById('span'+i).onclick = function () {\n        alert('this is span number '+i);\n    }\n}\n// ALL spans will generate alert: this span is span number 10\n</code></pre>\n\n<p>That's because they don't understand the nature of closures. They think that they are passing the value of <code>i</code> into the functions when in fact the functions are sharing a single variable <code>i</code>. Like I said before, a special kind of global variable.</p>\n\n<p>To get around this you need <em>detach</em>* the closure:</p>\n\n<pre><code>function makeClickHandler (j) {\n    return function () {alert('this is span number '+j)};\n}\n\nfor (var i=1;i&lt;=10;i++) {\n    document.getElementById('span'+i).onclick = makeClickHandler(i);\n}\n// this works because i is passed by reference \n// (or value in this case, since it is a number)\n// instead of being captured by a closure\n</code></pre>\n\n<p>*note: I don't know the correct terminology here.</p>\n"}, {'answer_id': 2243631, 'author': 'Andy E', 'author_id': 94197, 'author_profile': 'https://Stackoverflow.com/users/94197', 'pm_score': 6, 'selected': False, 'text': '<p>I know I\'m late to the party, but I just can\'t believe the <code>+</code> operator\'s usefulness hasn\'t been mentioned beyond "convert anything to a number".  Maybe that\'s how well hidden a feature it is?</p>\n\n<pre><code>// Quick hex to dec conversion:\n+"0xFF";              // -&gt; 255\n\n// Get a timestamp for now, the equivalent of `new Date().getTime()`:\n+new Date();\n\n// Safer parsing than parseFloat()/parseInt()\nparseInt("1,000");    // -&gt; 1, not 1000\n+"1,000";             // -&gt; NaN, much better for testing user input\nparseInt("010");      // -&gt; 8, because of the octal literal prefix\n+"010";               // -&gt; 10, `Number()` doesn\'t parse octal literals \n\n// A use case for this would be rare, but still useful in cases\n// for shortening something like if (someVar === null) someVar = 0;\n+null;                // -&gt; 0;\n\n// Boolean to integer\n+true;                // -&gt; 1;\n+false;               // -&gt; 0;\n\n// Other useful tidbits:\n+"1e10";              // -&gt; 10000000000\n+"1e-4";              // -&gt; 0.0001\n+"-12";               // -&gt; -12\n</code></pre>\n\n<p>Of course, you can do all this using <code>Number()</code> instead, but the <code>+</code> operator is so much prettier!</p>\n\n<p>You can also define a numeric return value for an object by overriding the prototype\'s <code>valueOf()</code> method.  Any number conversion performed on that object will not result in <code>NaN</code>, but the return value of the <code>valueOf()</code> method:</p>\n\n<pre><code>var rnd = {\n    "valueOf": function () { return Math.floor(Math.random()*1000); }\n};\n+rnd;               // -&gt; 442;\n+rnd;               // -&gt; 727;\n+rnd;               // -&gt; 718;\n</code></pre>\n'}, {'answer_id': 2303653, 'author': 'cllpse', 'author_id': 20946, 'author_profile': 'https://Stackoverflow.com/users/20946', 'pm_score': 2, 'selected': False, 'text': '<h2>JavaScript versatility - Overriding default functionality</h2>\n\n<p><br />\nHere\'s the code for overriding the <code>window.alert</code> function with jQuery UI\'s <a href="http://jqueryui.com/demos/dialog/" rel="nofollow noreferrer">Dialog widget</a>. I did this as a jQuery plug-in. And you can read about it on my blog; <a href="http://roosteronacid.com/blog/index.php/2010/01/20/jquery-plug-in-personalized-alert-messages/" rel="nofollow noreferrer"><em>altAlert, a jQuery plug-in for personalized alert messages</em></a>.</p>\n\n<pre><code>jQuery.altAlert = function (options)  \n{  \n    var defaults = {  \n        title: "Alert",  \n        buttons: {  \n            "Ok": function()  \n            {  \n                jQuery(this).dialog("close");  \n            }  \n        }  \n    };  \n\n    jQuery.extend(defaults, options);  \n\n    delete defaults.autoOpen;  \n\n    window.alert = function ()  \n    {  \n        jQuery("&lt;div /&gt;", {\n            html: arguments[0].replace(/\\n/, "&lt;br /&gt;")\n        }).dialog(defaults);  \n    };  \n};\n</code></pre>\n'}, {'answer_id': 2479026, 'author': 'adamJLev', 'author_id': 26192, 'author_profile': 'https://Stackoverflow.com/users/26192', 'pm_score': 1, 'selected': False, 'text': '<p>Simple self-contained function return value caching:</p>\n\n<pre><code>function isRunningLocally(){\n    var runningLocally = ....; // Might be an expensive check, check whatever needs to be checked.\n\n    return (isRunningLocally = function(){\n        return runningLocally;\n    })();\n},\n</code></pre>\n\n<p>The expensive part is only performed on the first call, and after that all the function does is return this value. Of course this is only useful for functions that will always return the same thing.</p>\n'}, {'answer_id': 2709783, 'author': 'Harmen', 'author_id': 176603, 'author_profile': 'https://Stackoverflow.com/users/176603', 'pm_score': 4, 'selected': False, 'text': '<p>In a function, you can return the function itself:</p>\n\n<pre><code>function showSomething(a){\n   alert(a);\n   return arguments.callee;\n}\n\n// Alerts: \'a\', \'b\', \'c\'\nshowSomething(\'a\')(\'b\')(\'c\');\n\n// Or what about this:\n(function (a){\n   alert(a);\n   return arguments.callee;\n}\u200b)(\'a\')(\'b\')(\'c\');\u200b\u200b\u200b\u200b\n</code></pre>\n\n<p>I don\'t know when it could be useful, anyway, it\'s pretty weird and fun:</p>\n\n<pre><code>var count = function(counter){\n   alert(counter);\n   if(counter &lt; 10){\n      return arguments.callee(counter+1);\n   }\n   return arguments.callee;\n};\n\ncount(5)(9); // Will alert 5, 6, 7, 8, 9, 10 and 9, 10\n</code></pre>\n\n<hr>\n\n<p>Actually, the <a href="https://github.com/jed/fab" rel="nofollow noreferrer">FAB framework</a> for Node.js seems to have implemented this feature; see <a href="https://stackoverflow.com/questions/3799238/javascript-fab-framework-on-node-js">this topic</a> for example.</p>\n'}, {'answer_id': 2920211, 'author': 'wnrph', 'author_id': 345520, 'author_profile': 'https://Stackoverflow.com/users/345520', 'pm_score': 1, 'selected': False, 'text': '<p>Closures:</p>\n\n<pre><code>function f() { \n    var a; \n    function closureGet(){ return a; }\n    function closureSet(val){ a=val;}\n    return [closureGet,closureSet];\n}\n\n[closureGet,closureSet]=f(); \nclosureSet(5);\nalert(closureGet()); // gives 5\n\nclosureSet(15);\nalert(closureGet()); // gives 15\n</code></pre>\n\n<p>The closure thing here is not the so-called destructuring assignment (<code>[c,d] = [1,3]</code> is equivalent to <code>c=1; d=3;</code>) but the fact that the occurences of <code>a</code> in closureGet and closureSet still refer to the same variable.  Even after closureSet has assigned <code>a</code> a new value!</p>\n'}, {'answer_id': 2921079, 'author': 'Tgr', 'author_id': 323407, 'author_profile': 'https://Stackoverflow.com/users/323407', 'pm_score': 3, 'selected': False, 'text': '<p>This is a hidden feature of jQuery, not Javascript, but since there will never be a "hidden features of jQuery" question...</p>\n\n<p>You can define your own <code>:something</code> selectors in jQuery:</p>\n\n<pre><code>$.extend($.expr[\':\'], {\n  foo: function(node, index, args, stack) {\n    // decide if selectors matches node, return true or false\n  }\n});\n</code></pre>\n\n<p>For selections using <code>:foo</code>, such as <code>$(\'div.block:foo("bar,baz") span\')</code>, the function <code>foo</code> will be called for all nodes which match the already processed part of the selector. The meaning of the arguments:</p>\n\n<ul>\n<li><code>node</code> holds the current node</li>\n<li><code>index</code> is the index of the node in the node set</li>\n<li><code>args</code> is an array that is useful if the selector has an argument or multiple names:\n\n<ul>\n<li><code>args[0]</code> is the whole selector text (e.g. <code>:foo("bar, baz")</code>)</li>\n<li><code>args[1]</code> is the selector name (e.g. <code>foo</code>)</li>\n<li><code>args[2]</code> is the quote character used to wrap the argument \n(e.g. <code>"</code> for <code>:foo("bar, baz")</code>) or an empty string if there is no quoting \n(<code>:foo(bar, baz)</code>) or undefined if there is no argument</li>\n<li><code>args[3]</code> is the argument, including any quotes, (e.g. <code>"bar, baz"</code>) \nor undefined if there are no arguments</li>\n</ul></li>\n<li><code>stack</code> is the node set (an array holding all nodes which are matched at that point)</li>\n</ul>\n\n<p>The function should return <code>true</code> if the selector matches, <code>false</code> otherwise.</p>\n\n<p>For example, the following code will enable selecting nodes based on a full-text regexp search:</p>\n\n<pre><code>$.extend($.expr[\':\'], {\n  matches: function(node, index, args, stack) {\n    if (!args.re) { // args is a good place for caching\n      var re = args[3];\n      if (args[2]) { // get rid of quotes\n        re = re.slice(1,-1);\n      }\n      var separator = re[0];\n      var pos = re.lastIndexOf(separator);\n      var modifiers = re.substr(pos+1);\n      var code = re.substr(1, pos-1);\n      args.re = new RegExp(code, modifiers);\n    }\n    return $(node).text().match(args.re);\n  }\n});\n\n// find the answers on this page which contain /**/-style comments\n$(\'.answer .post-text code:matches(!/\\\\*[\\\\s\\\\S]*\\\\*/!)\');\n</code></pre>\n\n<p>You could reach a similar effect with the callback version of <a href="http://api.jquery.com/filter/" rel="nofollow noreferrer">.filter()</a>, but custom selectors are much more flexible and usually more readable.</p>\n'}, {'answer_id': 3110886, 'author': 'Edgar Klerks', 'author_id': 375367, 'author_profile': 'https://Stackoverflow.com/users/375367', 'pm_score': 1, 'selected': False, 'text': '<p>When you are write callbacks you have a lot of code, which will look like this: </p>\n\n<pre><code>callback: function(){\n  stuff(arg1,arg2);\n}\n</code></pre>\n\n<p>You can use the function below, to make it somewhat cleaner. </p>\n\n<pre><code>callback: _(stuff, arg1, arg2) \n</code></pre>\n\n<p>It uses a less well known function of the Function object of javascript, apply. </p>\n\n<p>It also shows another character you can use as functionname: _.</p>\n\n<pre><code>function _(){\n        var func;\n        var args = new Array();\n        for(var i = 0; i &lt; arguments.length; i++){\n                if( i == 0){\n                        func = arguments[i];\n                } else {\n                        args.push(arguments[i]);\n                }\n        }\n        return function(){\n                return func.apply(func, args);\n        }\n}\n</code></pre>\n'}]
['https://Stackoverflow.com/questions/61088', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2443/']