Skip to content

Instantly share code, notes, and snippets.

@sasikanth513
Last active April 29, 2018 16:45
Show Gist options
  • Save sasikanth513/70264e7463097274d841c0f913346448 to your computer and use it in GitHub Desktop.
Save sasikanth513/70264e7463097274d841c0f913346448 to your computer and use it in GitHub Desktop.
[
{
"Author": "stackoverflow",
"url": "https://stackoverflow.com",
"format": "html",
"tips": [
{
"title": "How do JavaScript closures work?",
"body": "<h1>JavaScript closures for beginners</h1>\n\n<blockquote>Submitted by Morris on Tue, 2006-02-21 10:19. Community-edited since.</blockquote>\n\n<h2>Closures are not magic</h2>\n\n<p>This page explains closures so that a programmer can understand them &mdash; using working JavaScript code. It is not for gurus or functional programmers.</p>\n\n<p>Closures are <em>not hard</em> to understand once the core concept is grokked. However, they are impossible to understand by reading any academic papers or academically oriented information about them!</p>\n\n<p>This article is intended for programmers with some programming experience in a mainstream language, and who can read the following JavaScript function:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function sayHello(name) {\r\n var text = 'Hello ' + name;\r\n var say = function() { console.log(text); }\r\n say();\r\n}\r\nsayHello('Joe');</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<h2>An example of a closure</h2>\n\n<p>Two one sentence summaries:</p>\n\n<ul>\n<li><p>A closure is one way of supporting <a href=\"https://en.wikipedia.org/wiki/First-class_function\" rel=\"noreferrer\">first-class functions</a>; it is an expression that can reference variables within its scope (when it was first declared), be assigned to a variable, be passed as an argument to a function, or be returned as a function result. </p></li>\n<li><p>Or, a closure is a stack frame which is allocated when a function starts its execution, and <em>not freed</em> after the function returns (as if a 'stack frame' were allocated on the heap rather than the stack!).</p></li>\n</ul>\n\n<p>The following code returns a reference to a function:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function sayHello2(name) {\r\n var text = 'Hello ' + name; // Local variable\r\n var say = function() { console.log(text); }\r\n return say;\r\n}\r\nvar say2 = sayHello2('Bob');\r\nsay2(); // logs \"Hello Bob\"</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>Most JavaScript programmers will understand how a reference to a function is returned to a variable (<code>say2</code>) in the above code. If you don't, then you need to look at that before you can learn closures. A programmer using C would think of the function as returning a pointer to a function, and that the variables <code>say</code> and <code>say2</code> were each a pointer to a function.</p>\n\n<p>There is a critical difference between a C pointer to a function and a JavaScript reference to a function. In JavaScript, you can think of a function reference variable as having both a pointer to a function <em>as well</em> as a hidden pointer to a closure.</p>\n\n<p>The above code has a closure because the anonymous function <code>function() { console.log(text); }</code> is declared <em>inside</em> another function, <code>sayHello2()</code> in this example. In JavaScript, if you use the <code>function</code> keyword inside another function, you are creating a closure.</p>\n\n<p>In C and most other common languages, <em>after</em> a function returns, all the local variables are no longer accessible because the stack-frame is destroyed.</p>\n\n<p>In JavaScript, if you declare a function within another function, then the local variables can remain accessible after returning from the function you called. This is demonstrated above, because we call the function <code>say2()</code> after we have returned from <code>sayHello2()</code>. Notice that the code that we call references the variable <code>text</code>, which was a <em>local variable</em> of the function <code>sayHello2()</code>.</p>\n\n<pre><code>function() { console.log(text); } // Output of say2.toString();\n</code></pre>\n\n<p>Looking at the output of <code>say2.toString()</code>, we can see that the code refers to the variable <code>text</code>. The anonymous function can reference <code>text</code> which holds the value <code>'Hello Bob'</code> because the local variables of <code>sayHello2()</code> are kept in a closure.</p>\n\n<p>The magic is that in JavaScript a function reference also has a secret reference to the closure it was created in &mdash; similar to how delegates are a method pointer plus a secret reference to an object.</p>\n\n<h2>More examples</h2>\n\n<p>For some reason, closures seem really hard to understand when you read about them, but when you see some examples it becomes clear how they work (it took me a while).\nI recommend working through the examples carefully until you understand how they work. If you start using closures without fully understanding how they work, you would soon create some very weird bugs!</p>\n\n<h3>Example 3</h3>\n\n<p>This example shows that the local variables are not copied &mdash; they are kept by reference. It is kind of like keeping a stack-frame in memory when the outer function exits!</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function say667() {\r\n // Local variable that ends up within closure\r\n var num = 42;\r\n var say = function() { console.log(num); }\r\n num++;\r\n return say;\r\n}\r\nvar sayNumber = say667();\r\nsayNumber(); // logs 43</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<h3>Example 4</h3>\n\n<p>All three global functions have a common reference to the <em>same</em> closure because they are all declared within a single call to <code>setupSomeGlobals()</code>.</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>var gLogNumber, gIncreaseNumber, gSetNumber;\r\nfunction setupSomeGlobals() {\r\n // Local variable that ends up within closure\r\n var num = 42;\r\n // Store some references to functions as global variables\r\n gLogNumber = function() { console.log(num); }\r\n gIncreaseNumber = function() { num++; }\r\n gSetNumber = function(x) { num = x; }\r\n}\r\n\r\nsetupSomeGlobals();\r\ngIncreaseNumber();\r\ngLogNumber(); // 43\r\ngSetNumber(5);\r\ngLogNumber(); // 5\r\n\r\nvar oldLog = gLogNumber;\r\n\r\nsetupSomeGlobals();\r\ngLogNumber(); // 42\r\n\r\noldLog() // 5</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>The three functions have shared access to the same closure &mdash; the local variables of <code>setupSomeGlobals()</code> when the three functions were defined.</p>\n\n<p>Note that in the above example, if you call <code>setupSomeGlobals()</code> again, then a new closure (stack-frame!) is created. The old <code>gLogNumber</code>, <code>gIncreaseNumber</code>, <code>gSetNumber</code> variables are overwritten with <em>new</em> functions that have the new closure. (In JavaScript, whenever you declare a function inside another function, the inside function(s) is/are recreated again <em>each</em> time the outside function is called.)</p>\n\n<h3>Example 5</h3>\n\n<p>This one is a real gotcha for many people, so you need to understand it. Be very careful if you are defining a function within a loop: the local variables from the closure do not act as you might first think.</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function buildList(list) {\r\n var result = [];\r\n for (var i = 0; i &lt; list.length; i++) {\r\n var item = 'item' + i;\r\n result.push( function() {console.log(item + ' ' + list[i])} );\r\n }\r\n return result;\r\n}\r\n\r\nfunction testList() {\r\n var fnlist = buildList([1,2,3]);\r\n // Using j only to help prevent confusion -- could use i.\r\n for (var j = 0; j &lt; fnlist.length; j++) {\r\n fnlist[j]();\r\n }\r\n}\r\n\r\n testList() //logs \"item2 undefined\" 3 times</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>The line <code>result.push( function() {console.log(item + ' ' + list[i])}</code> adds a reference to an anonymous function three times to the result array. If you are not so familiar with anonymous functions think of it like:</p>\n\n<pre><code>pointer = function() {console.log(item + ' ' + list[i])};\nresult.push(pointer);\n</code></pre>\n\n<p>Note that when you run the example, <code>\"item2 undefined\"</code> is alerted three times! This is because just like previous examples, there is only one closure for the local variables for <code>buildList</code>. When the anonymous functions are called on the line <code>fnlist[j]()</code>; they all use the same single closure, and they use the current value for <code>i</code> and <code>item</code> within that one closure (where <code>i</code> has a value of <code>3</code> because the loop had completed, and <code>item</code> has a value of <code>'item2'</code>). Note we are indexing from 0 hence <code>item</code> has a value of <code>item2</code>. And the i++ will increment <code>i</code> to the value <code>3</code>.</p>\n\n<h3>Example 6</h3>\n\n<p>This example shows that the closure contains any local variables that were declared inside the outer function before it exited. Note that the variable <code>alice</code> is actually declared after the anonymous function. The anonymous function is declared first; and when that function is called it can access the <code>alice</code> variable because <code>alice</code> is in the same scope (JavaScript does <a href=\"https://stackoverflow.com/a/3725763/1269037\">variable hoisting</a>).\nAlso <code>sayAlice()()</code> just directly calls the function reference returned from <code>sayAlice()</code> &mdash; it is exactly the same as what was done previously but without the temporary variable.</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function sayAlice() {\r\n var say = function() { console.log(alice); }\r\n // Local variable that ends up within closure\r\n var alice = 'Hello Alice';\r\n return say;\r\n}\r\nsayAlice()();// logs \"Hello Alice\"</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>Tricky: note also that the <code>say</code> variable is also inside the closure, and could be accessed by any other function that might be declared within <code>sayAlice()</code>, or it could be accessed recursively within the inside function.</p>\n\n<h3>Example 7</h3>\n\n<p>This final example shows that each call creates a separate closure for the local variables. There is <em>not</em> a single closure per function declaration. There is a closure for <em>each call</em> to a function.</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function newClosure(someNum, someRef) {\r\n // Local variables that end up within closure\r\n var num = someNum;\r\n var anArray = [1,2,3];\r\n var ref = someRef;\r\n return function(x) {\r\n num += x;\r\n anArray.push(num);\r\n console.log('num: ' + num +\r\n '; anArray: ' + anArray.toString() +\r\n '; ref.someVar: ' + ref.someVar + ';');\r\n }\r\n}\r\nobj = {someVar: 4};\r\nfn1 = newClosure(4, obj);\r\nfn2 = newClosure(5, obj);\r\nfn1(1); // num: 5; anArray: 1,2,3,5; ref.someVar: 4;\r\nfn2(1); // num: 6; anArray: 1,2,3,6; ref.someVar: 4;\r\nobj.someVar++;\r\nfn1(2); // num: 7; anArray: 1,2,3,5,7; ref.someVar: 5;\r\nfn2(2); // num: 8; anArray: 1,2,3,6,8; ref.someVar: 5;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<h2>Summary</h2>\n\n<p>If everything seems completely unclear then the best thing to do is to play with the examples. Reading an explanation is much harder than understanding examples.\nMy explanations of closures and stack-frames, etc. are not technically correct &mdash; they are gross simplifications intended to help understanding. Once the basic idea is grokked, you can pick up the details later.</p>\n\n<h2>Final points:</h2>\n\n<ul>\n<li>Whenever you use <code>function</code> inside another function, a closure is used.</li>\n<li>Whenever you use <code>eval()</code> inside a function, a closure is used. The text you <code>eval</code> can reference local variables of the function, and within <code>eval</code> you can even create new local variables by using <code>eval('var foo = …')</code></li>\n<li>When you use <code>new Function(…)</code> (the <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function\" rel=\"noreferrer\">Function constructor</a>) inside a function, it does not create a closure. (The new function cannot reference the local variables of the outer function.)</li>\n<li>A closure in JavaScript is like keeping a copy of all the local variables, just as they were when a function exited.</li>\n<li>It is probably best to think that a closure is always created just an entry to a function, and the local variables are added to that closure.</li>\n<li>A new set of local variables is kept every time a function with a closure is called (given that the function contains a function declaration inside it, and a reference to that inside function is either returned or an external reference is kept for it in some way).</li>\n<li>Two functions might look like they have the same source text, but have completely different behaviour because of their 'hidden' closure. I don't think JavaScript code can actually find out if a function reference has a closure or not.</li>\n<li>If you are trying to do any dynamic source code modifications (for example: <code>myFunction = Function(myFunction.toString().replace(/Hello/,'Hola'));</code>), it won't work if <code>myFunction</code> is a closure (of course, you would never even think of doing source code string substitution at runtime, but...).</li>\n<li>It is possible to get function declarations within function declarations within functions &mdash; and you can get closures at more than one level.</li>\n<li>I think normally a closure is the term for both the function along with the variables that are captured. Note that I do not use that definition in this article!</li>\n<li>I suspect that closures in JavaScript differ from those normally found in functional languages.</li>\n</ul>\n\n<h2>Links</h2>\n\n<ul>\n<li>Douglas Crockford's simulated <a href=\"http://www.crockford.com/javascript/private.html\" rel=\"noreferrer\">private attributes and private methods</a> for an object, using closures.</li>\n<li>A great explanation of how closures can <a href=\"https://www.codeproject.com/Articles/12231/Memory-Leakage-in-Internet-Explorer-revisited\" rel=\"noreferrer\">cause memory leaks in IE</a> if you are not careful.</li>\n</ul>\n\n<h2>Thanks</h2>\n\n<p>If you have <em>just</em> learned closures (here or elsewhere!), then I am interested in any feedback from you about any changes you might suggest that could make this article clearer. Send an email to morrisjohns.com (morris_closure @). Please note that I am not a guru on JavaScript &mdash; nor on closures.</p>\n\n<hr>\n\n<p>Original post by Morris can be found in the <a href=\"http://web.archive.org/web/20080209105120/http:/blog.morrisjohns.com/javascript_closures_for_dummies\" rel=\"noreferrer\">Internet Archive</a>.</p>\n",
"source": "so",
"questionId": 111102
},
{
"title": "How to check whether a string contains a substring in JavaScript?",
"body": "<p>Here is a list of current possibilities:</p>\n\n<p><strong>1. (ES6) <code>includes</code></strong>—<a href=\"https://stackoverflow.com/a/14193950/2689455\">go to answer</a></p>\n\n<pre><code>var string = \"foo\",\n substring = \"oo\";\nstring.includes(substring);\n</code></pre>\n\n<p><strong>2. ES5 and older <code>indexOf</code></strong></p>\n\n<pre><code>var string = \"foo\",\n substring = \"oo\";\nstring.indexOf(substring) !== -1;\n</code></pre>\n\n<p><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/indexOf\" rel=\"noreferrer\"><code>String.prototype.indexOf</code></a> returns the position of the string in the other string. If not found, it will return <code>-1</code>.</p>\n\n<p><strong>3. <code>search</code></strong>—<a href=\"https://stackoverflow.com/a/2385801/2689455\">go to answer</a></p>\n\n<pre><code>var string = \"foo\",\n expr = /oo/;\nstring.search(expr);\n</code></pre>\n\n<p><strong>4. lodash includes</strong>—<a href=\"https://stackoverflow.com/a/20575032/2689455\">go to answer</a></p>\n\n<pre><code>var string = \"foo\",\n substring = \"oo\";\n_.includes(string, substring);\n</code></pre>\n\n<p><strong>5. RegExp</strong>—<a href=\"https://stackoverflow.com/a/1789980/2689455\">go to answer</a></p>\n\n<pre><code>var string = \"foo\",\n expr = /oo/; // no quotes here\nexpr.test(string);\n</code></pre>\n\n<p><strong>6. Match</strong>—<a href=\"https://stackoverflow.com/a/12652006/2689455\">go to answer</a></p>\n\n<pre><code>var string = \"foo\",\n expr = /oo/;\nstring.match(expr);\n</code></pre>\n\n<hr>\n\n<p><a href=\"http://jsben.ch/#/RVYk7\" rel=\"noreferrer\">Performance tests</a> are showing that <code>indexOf</code> might be the best choice, if it comes to a point where speed matters.</p>\n",
"source": "so",
"questionId": 1789945
},
{
"title": "What does &amp;quot;use strict&amp;quot; do in JavaScript, and what is the reasoning behind it?",
"body": "<p>This article about Javascript Strict Mode might interest you: <a href=\"http://ejohn.org/blog/ecmascript-5-strict-mode-json-and-more/\" rel=\"noreferrer\">John Resig - ECMAScript 5 Strict Mode, JSON, and More</a></p>\n\n<p>To quote some interesting parts:</p>\n\n<blockquote>\n <p>Strict Mode is a new feature in ECMAScript 5 that allows you to place a program, or a function, in a \"strict\" operating context. This strict context prevents certain actions from being taken and throws more exceptions.</p>\n</blockquote>\n\n<p>And:</p>\n\n<blockquote>\n <p>Strict mode helps out in a couple ways:</p>\n \n <ul>\n <li>It catches some common coding bloopers, throwing exceptions.</li>\n <li>It prevents, or throws errors, when relatively \"unsafe\" actions are taken (such as gaining access to the global object).</li>\n <li>It disables features that are confusing or poorly thought out.</li>\n </ul>\n</blockquote>\n\n<p>Also note you can apply \"strict mode\" to the whole file... Or you can use it only for a specific function <em>(still quoting from John Resig's article)</em>:</p>\n\n<blockquote>\n<pre><code>// Non-strict code...\n\n(function(){\n \"use strict\";\n\n // Define your library strictly...\n})();\n\n// Non-strict code... \n</code></pre>\n</blockquote>\n\n<p>Which might be helpful if you have to mix old and new code ;-)</p>\n\n<p>So, I suppose it's a bit like the <code>\"use strict\"</code> you can use in Perl <em>(hence the name?)</em>: it helps you make fewer errors, by detecting more things that could lead to breakages.</p>\n\n<p>Currently, it's <a href=\"http://caniuse.com/#use-strict\" rel=\"noreferrer\"><strong>supported by all major browsers</strong></a> <em>(bar IE 9 and below)</em>.</p>\n",
"source": "so",
"questionId": 1335851
},
{
"title": "How do I check if an element is hidden in jQuery?",
"body": "<p>Since the question refers to a single element, this code might be more suitable:</p>\n\n<pre><code>// Checks css for display:[none|block], ignores visibility:[true|false]\n$(element).is(\":visible\"); \n</code></pre>\n\n<p>Same as <a href=\"https://stackoverflow.com/questions/178325/how-do-you-test-if-something-is-hidden-in-jquery/178386#178386\">twernt's suggestion</a>, but applied to a single element; and it <a href=\"https://stackoverflow.com/a/4685330/49942\">matches the algorithm recommended in the jQuery FAQ</a></p>\n",
"source": "so",
"questionId": 178325
},
{
"title": "var functionName = function() {} vs function functionName() {}",
"body": "<p>The difference is that <code>functionOne</code> is a function expression and so only defined when that line is reached, whereas <code>functionTwo</code> is a function declaration and is defined as soon as its surrounding function or script is executed (due to <a href=\"http://adripofjavascript.com/blog/drips/variable-and-function-hoisting.html\" rel=\"noreferrer\">hoisting</a>). </p>\n\n<p>For example, a function expression:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>// TypeError: undefined is not a function\r\nfunctionOne();\r\n\r\nvar functionOne = function() {\r\n console.log(\"Hello!\");\r\n};</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>And, a function declaration: </p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>// Outputs: \"Hello!\"\r\nfunctionTwo();\r\n\r\nfunction functionTwo() {\r\n console.log(\"Hello!\");\r\n}</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>This also means you can't conditionally define functions using function declarations:</p>\n\n<pre><code>if (test) {\n // Error or misbehavior\n function functionThree() { doSomething(); }\n}\n</code></pre>\n\n<p>The above actually defines <code>functionThree</code> irrespective of <code>test</code>'s value &mdash; unless <code>use strict</code> is in effect, in which case it simply raises an error.</p>\n",
"source": "so",
"questionId": 336859
},
{
"title": "How do I remove a particular element from an array in JavaScript?",
"body": "<p>First, find the <code>index</code> of the element you want to remove:</p>\n\n<pre><code>var array = [2, 5, 9];\nvar index = array.indexOf(5);\n</code></pre>\n\n<p><em>Note: <a href=\"http://kangax.github.io/compat-table/es5/#test-Array.prototype.indexOf\" rel=\"noreferrer\">browser support for indexOf</a> is limited</em>; it is not supported in Internet&nbsp;Explorer 7 and 8.</p>\n\n<p>Then remove it with <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice\" rel=\"noreferrer\"><code>splice</code></a>:</p>\n\n<pre><code>if (index &gt; -1) {\n array.splice(index, 1);\n}\n</code></pre>\n\n<p>The second parameter of <code>splice</code> is the number of elements to remove. Note that <code>splice</code> modifies the array in place and returns a new array containing the elements that have been removed.</p>\n\n<hr>\n\n<p>If you need <code>indexOf</code> in an unsupported browser, try the following <code>polyfill</code>. Find more info about this <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf#Polyfill\" rel=\"noreferrer\"><strong><em><code>polyfill</code> here</em></strong></a>.</p>\n\n<pre><code>Array.prototype.indexOf || (Array.prototype.indexOf = function(d, e) {\n var a;\n if (null == this) throw new TypeError('\"this\" is null or not defined');\n var c = Object(this),\n b = c.length &gt;&gt;&gt; 0;\n if (0 === b) return -1;\n a = +e || 0;\n Infinity === Math.abs(a) &amp;&amp; (a = 0);\n if (a &gt;= b) return -1;\n for (a = Math.max(0 &lt;= a ? a : b - Math.abs(a), 0); a &lt; b;) {\n if (a in c &amp;&amp; c[a] === d) return a;\n a++\n }\n return -1\n});\n</code></pre>\n",
"source": "so",
"questionId": 5767325
},
{
"title": "Which equals operator (== vs ===) should be used in JavaScript comparisons?",
"body": "<p>The identity (<code>===</code>) operator behaves identically to the equality (<code>==</code>) operator except no type conversion is done, and the types must be the same to be considered equal.</p>\n\n<p>Reference: <a href=\"http://www.c-point.com/javascript_tutorial/jsgrpComparison.htm\" rel=\"noreferrer\">Javascript Tutorial: Comparison Operators</a></p>\n\n<p>The <code>==</code> operator will compare for equality <em>after doing any necessary type conversions</em>. The <code>===</code> operator will <strong>not</strong> do the conversion, so if two values are not the same type <code>===</code> will simply return <code>false</code>. Both are equally quick.</p>\n\n<p>To quote Douglas Crockford's excellent <a href=\"https://rads.stackoverflow.com/amzn/click/0596517742\" rel=\"noreferrer\">JavaScript: The Good Parts</a>,</p>\n\n<blockquote>\n <p>JavaScript has two sets of equality operators: <code>===</code> and <code>!==</code>, and their evil twins <code>==</code> and <code>!=</code>. The good ones work the way you would expect. If the two operands are of the same type and have the same value, then <code>===</code> produces <code>true</code> and <code>!==</code> produces <code>false</code>. The evil twins do the right thing when the operands are of the same type, but if they are of different types, they attempt to coerce the values. the rules by which they do that are complicated and unmemorable. These are some of the interesting cases:</p>\n\n<pre><code>'' == '0' // false\n0 == '' // true\n0 == '0' // true\n\nfalse == 'false' // false\nfalse == '0' // true\n\nfalse == undefined // false\nfalse == null // false\nnull == undefined // true\n\n' \\t\\r\\n ' == 0 // true\n</code></pre>\n \n <p>The lack of transitivity is alarming. My advice is to never use the evil twins. Instead, always use <code>===</code> and <code>!==</code>. All of the comparisons just shown produce <code>false</code> with the <code>===</code> operator.</p>\n</blockquote>\n\n<hr>\n\n<h3>Update:</h3>\n\n<p>A good point was brought up by <a href=\"https://stackoverflow.com/users/165495/casebash\">@Casebash</a> in the comments and in <a href=\"https://stackoverflow.com/users/113570/philippe-leybaert\">@Phillipe Laybaert's</a> <a href=\"https://stackoverflow.com/a/957602/1288\">answer</a> concerning reference types. For reference types <code>==</code> and <code>===</code> act consistently with one another (except in a special case).</p>\n\n<pre><code>var a = [1,2,3];\nvar b = [1,2,3];\n\nvar c = { x: 1, y: 2 };\nvar d = { x: 1, y: 2 };\n\nvar e = \"text\";\nvar f = \"te\" + \"xt\";\n\na == b // false\na === b // false\n\nc == d // false\nc === d // false\n\ne == f // true\ne === f // true\n</code></pre>\n\n<p>The special case is when you compare a literal with an object that evaluates to the same literal, due to its <code>toString</code> or <code>valueOf</code> method. For example, consider the comparison of a string literal with a string object created by the <code>String</code> constructor.</p>\n\n<pre><code>\"abc\" == new String(\"abc\") // true\n\"abc\" === new String(\"abc\") // false\n</code></pre>\n\n<p>Here the <code>==</code> operator is checking the values of the two objects and returning <code>true</code>, but the <code>===</code> is seeing that they're not the same type and returning <code>false</code>. Which one is correct? That really depends on what you're trying to compare. My advice is to bypass the question entirely and just don't use the <code>String</code> constructor to create string objects.</p>\n\n<p><strong>Reference</strong><br>\n<a href=\"http://www.ecma-international.org/ecma-262/5.1/#sec-11.9.3\" rel=\"noreferrer\">http://www.ecma-international.org/ecma-262/5.1/#sec-11.9.3</a></p>\n",
"source": "so",
"questionId": 359494
},
{
"title": "How do I remove a property from a JavaScript object?",
"body": "<p>Like this:</p>\n\n<pre><code>delete myObject.regex;\n// or,\ndelete myObject['regex'];\n// or,\nvar prop = \"regex\";\ndelete myObject[prop];\n</code></pre>\n\n<p>Demo\n<div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>var myObject = {\r\n \"ircEvent\": \"PRIVMSG\",\r\n \"method\": \"newURI\",\r\n \"regex\": \"^http://.*\"\r\n};\r\ndelete myObject.regex;\r\n\r\nconsole.log(myObject);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>For anyone interested in reading more about it, Stack Overflow user <a href=\"https://stackoverflow.com/users/130652/kangax\">kangax</a> has written an incredibly in-depth blog post about the <code>delete</code> statement on their blog, <em><a href=\"http://perfectionkills.com/understanding-delete/\" rel=\"noreferrer\">Understanding delete</a></em>. It is highly recommended.</p>\n",
"source": "so",
"questionId": 208105
},
{
"title": "What is the most efficient way to deep clone an object in JavaScript?",
"body": "<blockquote>\n <p><strong>Note:</strong> This is a reply to another answer, not a proper response to this question. If you wish to have fast object cloning please follow <a href=\"https://stackoverflow.com/a/5344074/1438393\">Corban's advice in their answer</a> to this question.</p>\n</blockquote>\n\n<hr>\n\n<p>I want to note that the <a href=\"http://api.jquery.com/clone/\" rel=\"noreferrer\"><code>.clone()</code></a> method in <strong>jQuery</strong> only clones DOM elements. In order to clone JavaScript objects, you would do:</p>\n\n<pre><code>// Shallow copy\nvar newObject = jQuery.extend({}, oldObject);\n\n// Deep copy\nvar newObject = jQuery.extend(true, {}, oldObject);\n</code></pre>\n\n<p>More information can be found in the <a href=\"http://api.jquery.com/jQuery.extend/\" rel=\"noreferrer\">jQuery documentation</a>.</p>\n\n<p>I also want to note that the deep copy is actually much smarter than what is shown above – it's able to avoid many traps (trying to deep extend a DOM element, for example). It's used frequently in jQuery core and in plugins to great effect.</p>\n",
"source": "so",
"questionId": 122102
},
{
"title": "How do I return the response from an asynchronous call?",
"body": "<blockquote>\n <p><em><code>-&gt;</code> For a more general explanation of async behaviour with different examples, please see</em> <a href=\"https://stackoverflow.com/q/23667086/218196\">Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference</a> </p>\n \n <p><em><code>-&gt;</code> If you already understand the problem, skip to the possible solutions below.</em></p>\n</blockquote>\n\n<h1>The problem</h1>\n\n<p>The <strong>A</strong> in <a href=\"https://en.wikipedia.org/wiki/Ajax_(programming)\" rel=\"noreferrer\">Ajax</a> stands for <a href=\"https://www.merriam-webster.com/dictionary/asynchronous\" rel=\"noreferrer\"><strong>asynchronous</strong></a> . That means sending the request (or rather receiving the response) is taken out of the normal execution flow. In your example, <code>$.ajax</code> returns immediately and the next statement, <code>return result;</code>, is executed before the function you passed as <code>success</code> callback was even called.</p>\n\n<p>Here is an analogy which hopefully makes the difference between synchronous and asynchronous flow clearer: </p>\n\n<h2>Synchronous</h2>\n\n<p>Imagine you make a phone call to a friend and ask him to look something up for you. Although it might take a while, you wait on the phone and stare into space, until your friend gives you the answer that you needed.</p>\n\n<p>The same is happening when you make a function call containing \"normal\" code:</p>\n\n<pre><code>function findItem() {\n var item;\n while(item_not_found) {\n // search\n }\n return item;\n}\n\nvar item = findItem();\n\n// Do something with item\ndoSomethingElse();\n</code></pre>\n\n<p>Even though <code>findItem</code> might take a long time to execute, any code coming after <code>var item = findItem();</code> has to <em>wait</em> until the function returns the result.</p>\n\n<h2>Asynchronous</h2>\n\n<p>You call your friend again for the same reason. But this time you tell him that you are in a hurry and he should <em>call you back</em> on your mobile phone. You hang up, leave the house and do whatever you planned to do. Once your friend calls you back, you are dealing with the information he gave to you.</p>\n\n<p>That's exactly what's happening when you do an Ajax request. </p>\n\n<pre><code>findItem(function(item) {\n // Do something with item\n});\ndoSomethingElse();\n</code></pre>\n\n<p>Instead of waiting for the response, the execution continues immediately and the statement after the Ajax call is executed. To get the response eventually, you provide a function to be called once the response was received, a <em>callback</em> (notice something? <em>call back</em> ?). Any statement coming after that call is executed before the callback is called.</p>\n\n<hr>\n\n<hr>\n\n<h1>Solution(s)</h1>\n\n<p><strong>Embrace the asynchronous nature of JavaScript!</strong> While certain asynchronous operations provide synchronous counterparts (so does \"Ajax\"), it's generally discouraged to use them, especially in a browser context.</p>\n\n<p>Why is it bad do you ask?</p>\n\n<p>JavaScript runs in the UI thread of the browser and any long running process will lock the UI, making it unresponsive. Additionally, there is an upper limit on the execution time for JavaScript and the browser will ask the user whether to continue the execution or not. </p>\n\n<p>All of this is really bad user experience. The user won't be able to tell whether everything is working fine or not. Furthermore, the effect will be worse for users with a slow connection.</p>\n\n<p>In the following we will look at three different solutions that are all building on top of each other:</p>\n\n<ul>\n<li><strong>Promises with <code>async/await</code></strong> (ES2017+, available in older browsers if you use a transpiler or regenerator)</li>\n<li><strong>Callbacks</strong> (popular in node)</li>\n<li><strong>Promises with <code>then()</code></strong> (ES2015+, available in older browsers if you use one of the many promise libraries)</li>\n</ul>\n\n<p><strong>All three are available in current browsers, and node 7+.</strong> </p>\n\n<hr>\n\n<h2>ES2017+: Promises with <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function\" rel=\"noreferrer\"><code>async/await</code></a></h2>\n\n<p>The new ECMAScript version released in 2017 introduced <em>syntax-level support</em> for asynchronous functions. With the help of <code>async</code> and <code>await</code>, you can write asynchronous in a \"synchronous style\". Make no mistake though: The code is still asynchronous, but it's easier to read/understand.</p>\n\n<p><code>async/await</code> builds on top of promises: an <code>async</code> function always returns a promise. <code>await</code> \"unwraps\" a promise and either result in the value the promise was resolved with or throws an error if the promise was rejected.</p>\n\n<p><strong>Important:</strong> You can only use <code>await</code> inside an <code>async</code> function. That means that at the very top level, you still have to work directly with the promise.</p>\n\n<p>You can read more about <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function\" rel=\"noreferrer\"><code>async</code></a> and <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await\" rel=\"noreferrer\"><code>await</code></a> on MDN.</p>\n\n<p>Here is an example that builds on top of delay above:</p>\n\n<pre><code>// Using 'superagent' which will return a promise.\nvar superagent = require('superagent')\n\n// This is isn't declared as `async` because it already returns a promise\nfunction delay() {\n // `delay` returns a promise\n return new Promise(function(resolve, reject) {\n // Only `delay` is able to resolve or reject the promise\n setTimeout(function() {\n resolve(42); // After 3 seconds, resolve the promise with value 42\n }, 3000);\n });\n}\n\n\nasync function getAllBooks() {\n try {\n // GET a list of book IDs of the current user\n var bookIDs = await superagent.get('/user/books');\n // wait for a second (just for the sake of this example)\n await delay(1000);\n // GET information about each book\n return await superagent.get('/books/ids='+JSON.stringify(bookIDs));\n } catch(error) {\n // If any of the awaited promises was rejected, this catch block\n // would catch the rejection reason\n return null;\n }\n}\n\n// Async functions always return a promise\ngetAllBooks()\n .then(function(books) {\n console.log(books);\n });\n</code></pre>\n\n<p>Newer <a href=\"https://kangax.github.io/compat-table/es2016plus/#test-async_functions\" rel=\"noreferrer\">browser</a> and <a href=\"http://node.green/#ES2017-features-async-functions\" rel=\"noreferrer\">node</a> versions support <code>async/await</code>. You can also support older environments by transforming your code to ES5 with the help of <a href=\"https://github.com/facebook/regenerator\" rel=\"noreferrer\">regenerator</a> (or tools that use regenerator, such as <a href=\"https://babeljs.io/\" rel=\"noreferrer\">Babel</a>).</p>\n\n<hr>\n\n<h2>Let functions accept <em>callbacks</em></h2>\n\n<p>A callback is simply a function passed to another function. That other function can call the function passed whenever it is ready. In the context of an asynchronous process, the callback will be called whenever the asynchronous process is done. Usually, the result is passed to the callback.</p>\n\n<p>In the example of the question, you can make <code>foo</code> accept a callback and use it as <code>success</code> callback. So this</p>\n\n<pre><code>var result = foo();\n// Code that depends on 'result'\n</code></pre>\n\n<p>becomes</p>\n\n<pre><code>foo(function(result) {\n // Code that depends on 'result'\n});\n</code></pre>\n\n<p>Here we defined the function \"inline\" but you can pass any function reference:</p>\n\n<pre><code>function myCallback(result) {\n // Code that depends on 'result'\n}\n\nfoo(myCallback);\n</code></pre>\n\n<p><code>foo</code> itself is defined as follows:</p>\n\n<pre><code>function foo(callback) {\n $.ajax({\n // ...\n success: callback\n });\n}\n</code></pre>\n\n<p><code>callback</code> will refer to the function we pass to <code>foo</code> when we call it and we simply pass it on to <code>success</code>. I.e. once the Ajax request is successful, <code>$.ajax</code> will call <code>callback</code> and pass the response to the callback (which can be referred to with <code>result</code>, since this is how we defined the callback).</p>\n\n<p>You can also process the response before passing it to the callback:</p>\n\n<pre><code>function foo(callback) {\n $.ajax({\n // ...\n success: function(response) {\n // For example, filter the response\n callback(filtered_response);\n }\n });\n}\n</code></pre>\n\n<p>It's easier to write code using callbacks than it may seem. After all, JavaScript in the browser is heavily event-driven (DOM events). Receiving the Ajax response is nothing else but an event.<br>\nDifficulties could arise when you have to work with third-party code, but most problems can be solved by just thinking through the application flow.</p>\n\n<hr>\n\n<h2>ES2015+: Promises with <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise\" rel=\"noreferrer\">then()</a></h2>\n\n<p>The <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise\" rel=\"noreferrer\">Promise API</a> is a new feature of ECMAScript 6 (ES2015), but it has good <a href=\"http://caniuse.com/#feat=promises\" rel=\"noreferrer\" title=\"caniuse\">browser support</a> already. There are also many libraries which implement the standard Promises API and provide additional methods to ease the use and composition of asynchronous functions (e.g. <a href=\"https://github.com/petkaantonov/bluebird\" rel=\"noreferrer\">bluebird</a>).</p>\n\n<p>Promises are containers for <em>future</em> values. When the promise receives the value (it is <em>resolved</em>) or when it is cancelled (<em>rejected</em>), it notifies all of its \"listeners\" who want to access this value.</p>\n\n<p>The advantage over plain callbacks is that they allow you to decouple your code and they are easier to compose.</p>\n\n<p>Here is a simple example of using a promise:</p>\n\n<pre><code>function delay() {\n // `delay` returns a promise\n return new Promise(function(resolve, reject) {\n // Only `delay` is able to resolve or reject the promise\n setTimeout(function() {\n resolve(42); // After 3 seconds, resolve the promise with value 42\n }, 3000);\n });\n}\n\ndelay()\n .then(function(v) { // `delay` returns a promise\n console.log(v); // Log the value once it is resolved\n })\n .catch(function(v) {\n // Or do something else if it is rejected \n // (it would not happen in this example, since `reject` is not called).\n });\n</code></pre>\n\n<p>Applied to our Ajax call we could use promises like this:</p>\n\n<pre><code>function ajax(url) {\n return new Promise(function(resolve, reject) {\n var xhr = new XMLHttpRequest();\n xhr.onload = function() {\n resolve(this.responseText);\n };\n xhr.onerror = reject;\n xhr.open('GET', url);\n xhr.send();\n });\n}\n\najax(\"/echo/json\")\n .then(function(result) {\n // Code depending on result\n })\n .catch(function() {\n // An error occurred\n });\n</code></pre>\n\n<p>Describing all the advantages that promise offer is beyond the scope of this answer, but if you write new code, you should seriously consider them. They provide a great abstraction and separation of your code.</p>\n\n<p>More information about promises: <a href=\"http://www.html5rocks.com/en/tutorials/es6/promises/\" rel=\"noreferrer\">HTML5 rocks - JavaScript Promises</a></p>\n\n<h3>Side note: jQuery's deferred objects</h3>\n\n<p><a href=\"https://stackoverflow.com/questions/4866721/what-are-deferred-objects\">Deferred objects</a> are jQuery's custom implementation of promises (before the Promise API was standardized). They behave almost like promises but expose a slightly different API.</p>\n\n<p>Every Ajax method of jQuery already returns a \"deferred object\" (actually a promise of a deferred object) which you can just return from your function:</p>\n\n<pre><code>function ajax() {\n return $.ajax(...);\n}\n\najax().done(function(result) {\n // Code depending on result\n}).fail(function() {\n // An error occurred\n});\n</code></pre>\n\n<h3>Side note: Promise gotchas</h3>\n\n<p>Keep in mind that promises and deferred objects are just <em>containers</em> for a future value, they are not the value itself. For example, suppose you had the following:</p>\n\n<pre><code>function checkPassword() {\n return $.ajax({\n url: '/password',\n data: {\n username: $('#username').val(),\n password: $('#password').val()\n },\n type: 'POST',\n dataType: 'json'\n });\n}\n\nif (checkPassword()) {\n // Tell the user they're logged in\n}\n</code></pre>\n\n<p>This code misunderstands the above asynchrony issues. Specifically, <code>$.ajax()</code> doesn't freeze the code while it checks the '/password' page on your server - it sends a request to the server and while it waits, immediately returns a jQuery Ajax Deferred object, not the response from the server. That means the <code>if</code> statement is going to always get this Deferred object, treat it as <code>true</code>, and proceed as though the user is logged in. Not good.</p>\n\n<p>But the fix is easy:</p>\n\n<pre><code>checkPassword()\n.done(function(r) {\n if (r) {\n // Tell the user they're logged in\n } else {\n // Tell the user their password was bad\n }\n})\n.fail(function(x) {\n // Tell the user something bad happened\n});\n</code></pre>\n\n<hr>\n\n<hr>\n\n<h2>Not recommended: Synchronous \"Ajax\" calls</h2>\n\n<p>As I mentioned, some(!) asynchronous operations have synchronous counterparts. I don't advocate their use, but for completeness' sake, here is how you would perform a synchronous call:</p>\n\n<h3>Without jQuery</h3>\n\n<p>If you directly use a <a href=\"http://www.w3.org/TR/XMLHttpRequest/\" rel=\"noreferrer\"><code>XMLHTTPRequest</code></a> object, pass <code>false</code> as third argument to <a href=\"http://www.w3.org/TR/XMLHttpRequest/#the-open%28%29-method\" rel=\"noreferrer\"><code>.open</code></a>.</p>\n\n<h3>jQuery</h3>\n\n<p>If you use <a href=\"http://api.jquery.com/jQuery.ajax/\" rel=\"noreferrer\">jQuery</a>, you can set the <code>async</code> option to <code>false</code>. Note that this option is <em>deprecated</em> since jQuery 1.8.\nYou can then either still use a <code>success</code> callback or access the <code>responseText</code> property of the <a href=\"http://api.jquery.com/jQuery.ajax/#jqXHR\" rel=\"noreferrer\">jqXHR object</a>:</p>\n\n<pre><code>function foo() {\n var jqXHR = $.ajax({\n //...\n async: false\n });\n return jqXHR.responseText;\n}\n</code></pre>\n\n<p>If you use any other jQuery Ajax method, such as <code>$.get</code>, <code>$.getJSON</code>, etc., you have to change it to <code>$.ajax</code> (since you can only pass configuration parameters to <code>$.ajax</code>).</p>\n\n<p><strong>Heads up!</strong> It is not possible to make a synchronous <a href=\"https://stackoverflow.com/questions/2067472/please-explain-jsonp\">JSONP</a> request. JSONP by its very nature is always asynchronous (one more reason to not even consider this option).</p>\n",
"source": "so",
"questionId": 14220321
},
{
"title": "How do I include a JavaScript file in another JavaScript file?",
"body": "<p>The old versions of JavaScript had no import, include, or require, so many different approaches to this problem have been developed.</p>\n\n<p>But recent versions of JavaScript have standards like <a href=\"http://exploringjs.com/es6/ch_modules.html\" rel=\"noreferrer\">ES6 modules</a> to import modules, although this is not supported yet by most browsers. Many people using modules with browser applications use <a href=\"https://webpack.github.io/\" rel=\"noreferrer\">build</a> and/or <a href=\"https://babeljs.io/\" rel=\"noreferrer\">transpilation</a> tools to make it practical to use new syntax with features like modules.</p>\n\n<h3>ES6 Modules</h3>\n\n<p>Note that currently, browser support for ES6 Modules is not particularly great, but it is on its way. According to <a href=\"https://stackoverflow.com/a/44086319\">this StackOverflow answer</a>, they are supported in Chrome 61, Firefox 54(behind the <code>dom.moduleScripts.enabled</code> setting in <code>about:config</code>) and MS Edge 16, with only Safari 10.1 providing support without flags.</p>\n\n<p>Thus, you will currently still need to use build and/or transpilation tools to valid JavaScript that will run in without any requirement for the user to use those browser versions or enable any flags.</p>\n\n<p>Once ES6 Modules are commonplace, here is how you would go about using them:</p>\n\n<pre class=\"lang-javascript prettyprint-override\"><code>// module.js\nexport function hello() {\n return \"Hello\";\n}\n</code></pre>\n\n<pre class=\"lang-javascript prettyprint-override\"><code>// main.js\nimport {hello} from 'module'; // or './module'\nlet val = hello(); // val is \"Hello\";\n</code></pre>\n\n<h3>Node.js require</h3>\n\n<p>Node.js is currently using a <a href=\"https://nodejs.org/api/modules.html\" rel=\"noreferrer\">module.exports/require</a> system. You can use <code>babel</code> to transpile if you want the <code>import</code> syntax. </p>\n\n<pre class=\"lang-javascript prettyprint-override\"><code>// mymodule.js\nmodule.exports = {\n hello: function() {\n return \"Hello\";\n }\n}\n</code></pre>\n\n<pre class=\"lang-javascript prettyprint-override\"><code>// server.js\nconst myModule = require('./mymodule');\nlet val = myModule.hello(); // val is \"Hello\" \n</code></pre>\n\n<p>There are other ways for JavaScript to include external JavaScript contents in browsers that do not require preprocessing.</p>\n\n<h3>AJAX Loading</h3>\n\n<p>You could load an additional script with an AJAX call and then use <code>eval</code> to run it. This is the most straightforward way, but it is limited to your domain because of the JavaScript sandbox security model. Using <code>eval</code> also opens the door to bugs, hacks and security issues.</p>\n\n<h3>jQuery Loading</h3>\n\n<p>The <a href=\"http://jquery.com/\" rel=\"noreferrer\">jQuery</a> library provides loading functionality <a href=\"http://api.jquery.com/jQuery.getScript/\" rel=\"noreferrer\">in one line</a>:</p>\n\n<pre class=\"lang-javascript prettyprint-override\"><code>$.getScript(\"my_lovely_script.js\", function() {\n alert(\"Script loaded but not necessarily executed.\");\n});\n</code></pre>\n\n<h3>Dynamic Script Loading</h3>\n\n<p>You could add a script tag with the script URL into the HTML. To avoid the overhead of jQuery, this is an ideal solution.</p>\n\n<p>The script can even reside on a different server. Furthermore, the browser evaluates the code. The <code>&lt;script&gt;</code> tag can be injected into either the web page <code>&lt;head&gt;</code>, or inserted just before the closing <code>&lt;/body&gt;</code> tag.</p>\n\n<p>Here is an example of how this could work:</p>\n\n<pre class=\"lang-javascript prettyprint-override\"><code>function dynamicallyLoadScript(url) {\n var script = document.createElement(\"script\"); // Make a script DOM node\n script.src = url; // Set it's src to the provided URL\n\n document.head.appendChild(script); // Add it to the end of the head section of the page (could change 'head' to 'body' to add it to the end of the body section instead)\n}\n</code></pre>\n\n<p>This function will add a new <code>&lt;script&gt;</code> tag to end of the head section of the page, where the <code>src</code> attribute is set to the URL which is given to the function as the first parameter.</p>\n\n<p>Both of these solutions are discussed and illustrated in <a href=\"http://unixpapa.com/js/dyna.html\" rel=\"noreferrer\">JavaScript Madness: Dynamic Script Loading</a>.</p>\n\n<h2>Detecting when the script has been executed</h2>\n\n<p>Now, there is a big issue you must know about. Doing that implies that <em>you remotely load the code</em>. Modern web browsers will load the file and keep executing your current script because they load everything asynchronously to improve performance. (This applies to both the jQuery method and the manual dynamic script loading method.)</p>\n\n<p>It means that if you use these tricks directly, <em>you won't be able to use your newly loaded code the next line after you asked it to be loaded</em>, because it will be still loading.</p>\n\n<p>For example: <code>my_lovely_script.js</code> contains <code>MySuperObject</code>:</p>\n\n<pre class=\"lang-javascript prettyprint-override\"><code>var js = document.createElement(\"script\");\n\njs.type = \"text/javascript\";\njs.src = jsFilePath;\n\ndocument.body.appendChild(js);\n\nvar s = new MySuperObject();\n\nError : MySuperObject is undefined\n</code></pre>\n\n<p>Then you reload the page hitting <kbd>F5</kbd>. And it works! Confusing...</p>\n\n<p><strong>So what to do about it ?</strong></p>\n\n<p>Well, you can use the hack the author suggests in the link I gave you. In summary, for people in a hurry, he uses an event to run a callback function when the script is loaded. So you can put all the code using the remote library in the callback function. For example:</p>\n\n<pre class=\"lang-javascript prettyprint-override\"><code>function loadScript(url, callback)\n{\n // Adding the script tag to the head as suggested before\n var head = document.getElementsByTagName('head')[0];\n var script = document.createElement('script');\n script.type = 'text/javascript';\n script.src = url;\n\n // Then bind the event to the callback function.\n // There are several events for cross browser compatibility.\n script.onreadystatechange = callback;\n script.onload = callback;\n\n // Fire the loading\n head.appendChild(script);\n}\n</code></pre>\n\n<p>Then you write the code you want to use AFTER the script is loaded in a <a href=\"http://en.wikipedia.org/wiki/Anonymous_function\" rel=\"noreferrer\">lambda function</a>:</p>\n\n<pre class=\"lang-javascript prettyprint-override\"><code>var myPrettyCode = function() {\n // Here, do whatever you want\n};\n</code></pre>\n\n<p>Then you run all that:</p>\n\n<pre class=\"lang-javascript prettyprint-override\"><code>loadScript(\"my_lovely_script.js\", myPrettyCode);\n</code></pre>\n\n<p>Note that the script may execute after the DOM has loaded, or before, depending on the browser and whether you included the line <code>script.async = false;</code>. There's a <a href=\"http://www.html5rocks.com/en/tutorials/speed/script-loading/\" rel=\"noreferrer\">great article on Javascript loading in general</a> which discusses this.</p>\n\n<h3>Source Code Merge/Preprocessing</h3>\n\n<p>As mentioned at the top of this answer, many developers now use build/transpilation tool(s) like WebPack, Babel, or Gulp in their projects, allowing them to use new syntax and support modules better, combine files, minify, etc.</p>\n",
"source": "so",
"questionId": 950087
},
{
"title": "For-each over an array in JavaScript?",
"body": "\n\n<p><strong>TL;DR</strong></p>\n\n<ul>\n<li>Don't use <code>for-in</code> unless you use it with safeguards or are at least aware of why it might bite you.</li>\n<li><p>Your best bets are usually</p>\n\n<ul>\n<li>a <code>for-of</code> loop (ES2015+ only),</li>\n<li><code>Array#forEach</code> (<a href=\"http://www.ecma-international.org/ecma-262/6.0/index.html#sec-array.prototype.foreach\" rel=\"noreferrer\"><code>spec</code></a> | <a href=\"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach\" rel=\"noreferrer\"><code>MDN</code></a>) (or its relatives <code>some</code> and such) (ES5+ only),</li>\n<li>a simple old-fashioned <code>for</code> loop,</li>\n<li>or <code>for-in</code> with safeguards.</li>\n</ul></li>\n</ul>\n\n<p>But there's <strong>lots</strong> more to explore, read on...</p>\n\n<hr>\n\n<p>JavaScript has powerful semantics for looping through arrays and array-like objects. I've split the answer into two parts: Options for genuine arrays, and options for things that are just array-<em>like</em>, such as the <code>arguments</code> object, other iterable objects (ES2015+), DOM collections, and so on.</p>\n\n<p>I'll quickly note that you can use the ES2015 options <em>now</em>, even on ES5 engines, by <em>transpiling</em> ES2015 to ES5. Search for \"ES2015 transpiling\" / \"ES6 transpiling\" for more...</p>\n\n<p>Okay, let's look at our options:</p>\n\n<h2>For Actual Arrays</h2>\n\n<p>You have three options in <a href=\"http://ecma-international.org/ecma-262/5.1/\" rel=\"noreferrer\">ECMAScript&nbsp;5</a> (\"ES5\"), the version most broadly supported at the moment, and will soon have two more in <a href=\"http://www.ecma-international.org/ecma-262/6.0/index.html\" rel=\"noreferrer\">ECMAScript&nbsp;2015</a> (\"ES2015\", \"ES6\"), the latest version of JavaScript that vendors are working on supporting:</p>\n\n<ol>\n<li>Use <code>forEach</code> and related (ES5+)</li>\n<li>Use a simple <code>for</code> loop</li>\n<li>Use <code>for-in</code> <em>correctly</em></li>\n<li>Use <code>for-of</code> (use an iterator implicitly) (ES2015+)</li>\n<li>Use an iterator explicitly (ES2015+)</li>\n</ol>\n\n<p>Details:</p>\n\n<h3>1. Use <code>forEach</code> and related</h3>\n\n<p>If you're using an environment that supports the <code>Array</code> features of ES5 (directly or using a shim), you can use the new <code>forEach</code> (<a href=\"http://www.ecma-international.org/ecma-262/6.0/index.html#sec-array.prototype.foreach\" rel=\"noreferrer\"><code>spec</code></a> | <a href=\"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach\" rel=\"noreferrer\"><code>MDN</code></a>):</p>\n\n<pre><code>var a = [\"a\", \"b\", \"c\"];\na.forEach(function(entry) {\n console.log(entry);\n});\n</code></pre>\n\n<p><code>forEach</code> accepts an iterator function and, optionally, a value to use as <code>this</code> when calling that iterator function (not used above). The iterator function is called for each entry in the array, in order, skipping non-existent entries in sparse arrays. Although I only used one argument above, the iterator function is called with three: The value of each entry, the index of that entry, and a reference to the array you're iterating over (in case your function doesn't already have it handy).</p>\n\n<p>Unless you're supporting obsolete browsers like IE8 (which NetApps shows at just over 4% market share as of this writing in September&nbsp;2016), you can happily use <code>forEach</code> in a general-purpose web page without a shim. If you do need to support obsolete browsers, shimming/polyfilling <code>forEach</code> is easily done (search for \"es5 shim\" for several options).</p>\n\n<p><code>forEach</code> has the benefit that you don't have to declare indexing and value variables in the containing scope, as they're supplied as arguments to the iteration function, and so nicely scoped to just that iteration.</p>\n\n<p>If you're worried about the runtime cost of making a function call for each array entry, don't be; <a href=\"http://blog.niftysnippets.org/2012/02/foreach-and-runtime-cost.html\" rel=\"noreferrer\">details</a>.</p>\n\n<p>Additionally, <code>forEach</code> is the \"loop through them all\" function, but ES5 defined several other useful \"work your way through the array and do things\" functions, including:</p>\n\n<ul>\n<li><a href=\"http://www.ecma-international.org/ecma-262/6.0/index.html#sec-array.prototype.every\" rel=\"noreferrer\"><code>every</code></a> (stops looping the first time the iterator returns <code>false</code> or something falsey)</li>\n<li><a href=\"http://www.ecma-international.org/ecma-262/6.0/index.html#sec-array.prototype.some\" rel=\"noreferrer\"><code>some</code></a> (stops looping the first time the iterator returns <code>true</code> or something truthy)</li>\n<li><a href=\"http://www.ecma-international.org/ecma-262/6.0/index.html#sec-array.prototype.filter\" rel=\"noreferrer\"><code>filter</code></a> (creates a new array including elements where the filter function returns <code>true</code> and omitting the ones where it returns <code>false</code>)</li>\n<li><a href=\"http://www.ecma-international.org/ecma-262/6.0/index.html#sec-array.prototype.map\" rel=\"noreferrer\"><code>map</code></a> (creates a new array from the values returned by the iterator function)</li>\n<li><a href=\"http://www.ecma-international.org/ecma-262/6.0/index.html#sec-array.prototype.reduce\" rel=\"noreferrer\"><code>reduce</code></a> (builds up a value by repeated calling the iterator, passing in previous values; see the spec for the details; useful for summing the contents of an array and many other things)</li>\n<li><a href=\"http://www.ecma-international.org/ecma-262/6.0/index.html#sec-array.prototype.reduceright\" rel=\"noreferrer\"><code>reduceRight</code></a> (like <code>reduce</code>, but works in descending rather than ascending order)</li>\n</ul>\n\n<h3>2. Use a simple <code>for</code> loop</h3>\n\n<p>Sometimes the old ways are the best:</p>\n\n<pre><code>var index;\nvar a = [\"a\", \"b\", \"c\"];\nfor (index = 0; index &lt; a.length; ++index) {\n console.log(a[index]);\n}\n</code></pre>\n\n<p>If the length of the array won't change during the loop, and it's in performance-sensitive code (unlikely), a slightly more complicated version grabbing the length up front might be a <strong><em>tiny</em></strong> bit faster:</p>\n\n<pre><code>var index, len;\nvar a = [\"a\", \"b\", \"c\"];\nfor (index = 0, len = a.length; index &lt; len; ++index) {\n console.log(a[index]);\n}\n</code></pre>\n\n<p>And/or counting backward:</p>\n\n<pre><code>var index;\nvar a = [\"a\", \"b\", \"c\"];\nfor (index = a.length - 1; index &gt;= 0; --index) {\n console.log(a[index]);\n}\n</code></pre>\n\n<p>But with modern JavaScript engines, it's rare you need to eke out that last bit of juice.</p>\n\n<p>In ES2015 and higher, you can make your index and value variables local to the <code>for</code> loop:</p>\n\n<pre><code>let a = [\"a\", \"b\", \"c\"];\nfor (let index = 0; index &lt; a.length; ++index) {\n let value = a[index];\n}\n//console.log(index); // Would cause \"ReferenceError: index is not defined\"\n//console.log(value); // Would cause \"ReferenceError: value is not defined\"\n</code></pre>\n\n<p>And when you do that, not just <code>value</code> but also <code>index</code> is recreated for each loop iteration, meaning closures created in the loop body keep a reference to the <code>index</code> (and <code>value</code>) created for that specific iteration:</p>\n\n<pre><code>let divs = document.querySelectorAll(\"div\");\nfor (let index = 0; index &lt; divs.length; ++index) {\n divs[index].addEventListener('click', e =&gt; {\n alert(\"Index is: \" + index);\n });\n}\n</code></pre>\n\n<p>If you had five divs, you'd get \"Index is: 0\" if you clicked the first and \"Index is: 4\" if you clicked the last. This does <strong>not</strong> work if you use <code>var</code> instead of <code>let</code>.</p>\n\n<h3>3. Use <code>for-in</code> <em>correctly</em></h3>\n\n<p>You'll get people telling you to use <code>for-in</code>, but <a href=\"http://blog.niftysnippets.org/2010/11/myths-and-realities-of-forin.html\" rel=\"noreferrer\">that's not what <code>for-in</code> is for</a>. <code>for-in</code> loops through the <em>enumerable properties of an object</em>, not the indexes of an array. <strong>The order is not guaranteed</strong>, not even in ES2015 (ES6). ES2015 does define an order to object properties (via <a href=\"http://www.ecma-international.org/ecma-262/6.0/index.html#sec-ordinary-object-internal-methods-and-internal-slots-ownpropertykeys\" rel=\"noreferrer\"><code>[[OwnPropertyKeys]]</code></a>, <a href=\"http://www.ecma-international.org/ecma-262/6.0/index.html#sec-ordinary-object-internal-methods-and-internal-slots-enumerate\" rel=\"noreferrer\"><code>[[Enumerate]]</code></a>, and things that use them like <a href=\"http://www.ecma-international.org/ecma-262/6.0/index.html#sec-object.getownpropertynames\" rel=\"noreferrer\"><code>Object.getOwnPropertyKeys</code></a>), but it <strong>does not</strong> define that <code>for-in</code> will follow that order. (Details in <a href=\"https://stackoverflow.com/a/30919039/157247\">this other answer</a>.)</p>\n\n<p>Still, it <em>can</em> be useful, particularly for <a href=\"http://en.wikipedia.org/wiki/Sparse_array\" rel=\"noreferrer\"><em>sparse</em> arrays</a>, if you use appropriate safeguards:</p>\n\n<pre><code>// `a` is a sparse array\nvar key;\nvar a = [];\na[0] = \"a\";\na[10] = \"b\";\na[10000] = \"c\";\nfor (key in a) {\n if (a.hasOwnProperty(key) &amp;&amp; // These are explained\n /^0$|^[1-9]\\d*$/.test(key) &amp;&amp; // and then hidden\n key &lt;= 4294967294 // away below\n ) {\n console.log(a[key]);\n }\n}\n</code></pre>\n\n<p>Note the two checks:</p>\n\n<ol>\n<li><p>That the object has its <em>own</em> property by that name (not one it inherits from its prototype), and</p></li>\n<li><p>That the key is a base-10 numeric string in its normal string form and its value is &lt;= 2^32 - 2 (which is 4,294,967,294). Where does that number come from? It's part of the definition of an array index <a href=\"http://www.ecma-international.org/ecma-262/5.1/#sec-15.4\" rel=\"noreferrer\">in the specification</a>. Other numbers (non-integers, negative numbers, numbers greater than 2^32 - 2) are not array indexes. The reason it's 2^32 - <strong>2</strong> is that that makes the greatest index value one lower than 2^32 - <strong>1</strong>, which is the maximum value an array's <code>length</code> can have. (E.g., an array's length fits in a 32-bit unsigned integer.) <em>(Props to RobG for pointing out in a comment <a href=\"http://blog.niftysnippets.org/2010/11/myths-and-realities-of-forin.html\" rel=\"noreferrer\">on my blog post</a> that my previous test wasn't quite right.)</em></p></li>\n</ol>\n\n<p>That's a tiny bit of added overhead per loop iteration on most arrays, but if you have a <em>sparse</em> array, it can be a more efficient way to loop because it only loops for entries that actually exist. E.g., for the array above, we loop a total of three times (for keys <code>\"0\"</code>, <code>\"10\"</code>, and <code>\"10000\"</code>&nbsp;&mdash; remember, they're strings), not 10,001 times.</p>\n\n<p>Now, you won't want to write that every time, so you might put this in your toolkit:</p>\n\n<pre><code>function arrayHasOwnIndex(array, prop) {\n return array.hasOwnProperty(prop) &amp;&amp; /^0$|^[1-9]\\d*$/.test(prop) &amp;&amp; prop &lt;= 4294967294; // 2^32 - 2\n}\n</code></pre>\n\n<p>And then we'd use it like this:</p>\n\n<pre><code>for (key in a) {\n if (arrayHasOwnIndex(a, key)) {\n console.log(a[key]);\n }\n}\n</code></pre>\n\n<p>Or if you're interested in just a \"good enough for most cases\" test, you could use this, but while it's close, it's not quite correct:</p>\n\n<pre><code>for (key in a) {\n // \"Good enough\" for most cases\n if (String(parseInt(key, 10)) === key &amp;&amp; a.hasOwnProperty(key)) {\n console.log(a[key]);\n }\n}\n</code></pre>\n\n<h3>4. Use <code>for-of</code> (use an iterator implicitly) (ES2015+)</h3>\n\n<p>ES2015 adds <em>iterators</em> to JavaScript. The easiest way to use iterators is the new <code>for-of</code> statement. It looks like this:</p>\n\n<pre><code>var val;\nvar a = [\"a\", \"b\", \"c\"];\nfor (val of a) {\n console.log(val);\n}\n</code></pre>\n\n<p>Output:</p>\n\n<pre>\na\nb\nc\n</pre>\n\n<p>Under the covers, that gets an <em>iterator</em> from the array and loops through it, getting the values from it. This doesn't have the issue that using <code>for-in</code> has, because it uses an iterator defined by the object (the array), and arrays define that their iterators iterate through their <em>entries</em> (not their properties). Unlike <code>for-in</code> in ES5, the order in which the entries are visited is the numeric order of their indexes.</p>\n\n<h3>5. Use an iterator explicitly (ES2015+)</h3>\n\n<p>Sometimes, you might want to use an iterator <em>explicitly</em>. You can do that, too, although it's a lot clunkier than <code>for-of</code>. It looks like this:</p>\n\n<pre><code>var a = [\"a\", \"b\", \"c\"];\nvar it = a.values();\nvar entry;\nwhile (!(entry = it.next()).done) {\n console.log(entry.value);\n}\n</code></pre>\n\n<p>The iterator is a function (specifically, a <em>generator</em>) that returns a new object each time you call <code>next</code>. The object returned by the iterator has a property, <code>done</code>, telling us whether it's done, and a property <code>value</code> with the value for that iteration.</p>\n\n<p>The meaning of <code>value</code> varies depending on the iterator; arrays support (at least) three functions that return iterators:</p>\n\n<ul>\n<li><code>values()</code>: This is the one I used above. It returns an iterator where each <code>value</code> is the value for that iteration.</li>\n<li><code>keys()</code>: Returns an iterator where each <code>value</code> is the key for that iteration (so for our <code>a</code> above, that would be <code>\"0\"</code>, then <code>\"1\"</code>, then <code>\"2\"</code>).</li>\n<li><code>entries()</code>: Returns an iterator where each <code>value</code> is an array in the form <code>[key, value]</code> for that iteration.</li>\n</ul>\n\n<p>(As of this writing, Firefox 29 supports <code>entries</code> and <code>keys</code> but not <code>values</code>.)</p>\n\n<h2>For Array-Like Objects</h2>\n\n<p>Aside from true arrays, there are also <em>array-like</em> objects that have a <code>length</code> property and properties with numeric names: <code>NodeList</code> instances, the <code>arguments</code> object, etc. How do we loop through their contents?</p>\n\n<h3>Use any of the options above for arrays</h3>\n\n<p>At least some, and possibly most or even all, of the array approaches above frequently apply equally well to array-like objects:</p>\n\n<ol>\n<li><p><strong>Use <code>forEach</code> and related (ES5+)</strong></p>\n\n<p>The various functions on <code>Array.prototype</code> are \"intentionally generic\" and can usually be used on array-like objects via <a href=\"http://www.ecma-international.org/ecma-262/6.0/index.html#sec-function.prototype.call\" rel=\"noreferrer\"><code>Function#call</code></a> or <a href=\"http://www.ecma-international.org/ecma-262/6.0/index.html#sec-function.prototype.apply\" rel=\"noreferrer\"><code>Function#apply</code></a>. (See the <em>Caveat for host-provided objects</em> at the end of this answer, but it's a rare issue.)</p>\n\n<p>Suppose you wanted to use <code>forEach</code> on a <code>Node</code>'s <code>childNodes</code> property. You'd do this:</p>\n\n<pre><code>Array.prototype.forEach.call(node.childNodes, function(child) {\n // Do something with `child`\n});\n</code></pre>\n\n<p>If you're going to do that a lot, you might want to grab a copy of the function reference into a variable for reuse, e.g.:</p>\n\n<pre><code>// (This is all presumably in some scoping function)\nvar forEach = Array.prototype.forEach;\n\n// Then later...\nforEach.call(node.childNodes, function(child) {\n // Do something with `child`\n});\n</code></pre></li>\n<li><p><strong>Use a simple <code>for</code> loop</strong></p>\n\n<p>Obviously, a simple <code>for</code> loop applies to array-like objects.</p></li>\n<li><p><strong>Use <code>for-in</code> <em>correctly</em></strong></p>\n\n<p><code>for-in</code> with the same safeguards as with an array should work with array-like objects as well; the caveat for host-provided objects on #1 above may apply.</p></li>\n<li><p><strong>Use <code>for-of</code> (use an iterator implicitly) (ES2015+)</strong></p>\n\n<p><code>for-of</code> will use the iterator provided by the object (if any); we'll have to see how this plays with the various array-like objects, particularly host-provided ones.</p></li>\n<li><p><strong>Use an iterator explicitly (ES2015+)</strong></p>\n\n<p>See #4, we'll have to see how iterators play out.</p></li>\n</ol>\n\n<h3>Create a true array</h3>\n\n<p>Other times, you may want to convert an array-like object into a true array. Doing that is surprisingly easy:</p>\n\n<ol>\n<li><p><strong>Use the <a href=\"http://www.ecma-international.org/ecma-262/6.0/index.html#sec-array.prototype.slice\" rel=\"noreferrer\"><code>slice</code></a> method of arrays</strong></p>\n\n<p>We can use the <code>slice</code> method of arrays, which like the other methods mentioned above is \"intentionally generic\" and so can be used with array-like objects, like this:</p>\n\n<pre><code>var trueArray = Array.prototype.slice.call(arrayLikeObject);\n</code></pre>\n\n<p>So for instance, if we want to convert a <code>NodeList</code> into a true array, we could do this:</p>\n\n<pre><code>var divs = Array.prototype.slice.call(document.querySelectorAll(\"div\"));\n</code></pre>\n\n<p>See the <em>Caveat for host-provided objects</em> below. In particular, note that this will fail in IE8 and earlier, which don't let you use host-provided objects as <code>this</code> like that.</p></li>\n<li><p><strong>Use <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_operator\" rel=\"noreferrer\">spread notation (<code>...</code>)</a></strong></p>\n\n<p>It's also possible to use ES2015's <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_operator\" rel=\"noreferrer\">spread notation</a> (MDN currently calls it an operator; it isn't one), with JavaScript engines that support this feature:</p>\n\n<pre><code>var trueArray = [...iterableObject];\n</code></pre>\n\n<p>So for instance, if we want to convert a <code>NodeList</code> into a true array, with spread syntax this becomes quite succinct:</p>\n\n<pre><code>var divs = [...document.querySelectorAll(\"div\")];\n</code></pre></li>\n<li><p><strong>Use <code>Array.from</code></strong> <a href=\"http://www.ecma-international.org/ecma-262/6.0/index.html#sec-array.from\" rel=\"noreferrer\">(spec)</a> | <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from\" rel=\"noreferrer\">(MDN)</a></p>\n\n<p><code>Array.from</code> (ES2015, but shimmable) creates an array from an array-like object, optionally passing the entries through a mapping function first. So:</p>\n\n<pre><code>var divs = Array.from(document.querySelectorAll(\"div\"));\n</code></pre>\n\n<p>Or if you wanted to get an array of the tag names of the elements with a given class, you'd use the mapping function:</p>\n\n<pre><code>// Arrow function (ES2015):\nvar divs = Array.from(document.querySelectorAll(\".some-class\"), element =&gt; element.tagName);\n\n// Standard function (since `Array.from` can be shimmed):\nvar divs = Array.from(document.querySelectorAll(\".some-class\"), function(element) {\n return element.tagName;\n});\n</code></pre></li>\n</ol>\n\n<h3>Caveat for host-provided objects</h3>\n\n<p>If you use <code>Array.prototype</code> functions with <em>host-provided</em> array-like objects (DOM lists and other things provided by the browser rather than the JavaScript engine), you need to be sure to test in your target environments to make sure the host-provided object behaves properly. <strong>Most do behave properly</strong> (now), but it's important to test. The reason is that most of the <code>Array.prototype</code> methods you're likely to want to use rely on the host-provided object giving an honest answer to the abstract <a href=\"http://www.ecma-international.org/ecma-262/5.1/#sec-8.6.2\" rel=\"noreferrer\"><code>[[HasProperty]]</code></a> operation. As of this writing, browsers do a very good job of this, but the ES5 spec did allow for the possibility a host-provided object may not be honest; it's in <a href=\"http://www.ecma-international.org/ecma-262/5.1/#sec-8.6.2\" rel=\"noreferrer\">§8.6.2</a> (several paragraphs below the big table near the beginning of that section), where it says:</p>\n\n<blockquote>\n <p>Host objects may implement these internal methods in any manner unless specified otherwise; for example, one possibility is that <code>[[Get]]</code> and <code>[[Put]]</code> for a particular host object indeed fetch and store property values but <code>[[HasProperty]]</code> always generates <strong>false</strong>.</p>\n</blockquote>\n\n<p>(I couldn't find the equivalent verbiage in the ES2015 spec, but it's bound to still be the case.) Again, as of this writing the common host-provided array-like objects in modern browsers (<code>NodeList</code> instances, for instance) <strong>do</strong> handle <code>[[HasProperty]]</code> correctly, but it's important to test.</p>\n",
"source": "so",
"questionId": 9329446
},
{
"title": "Which &quot;href&quot; value should I use for JavaScript links, &quot;#&quot; or &quot;javascript:void(0)&quot;?",
"body": "<p>I use <code>javascript:void(0)</code>.</p>\n\n<p>Three reasons. Encouraging the use of <code>#</code> amongst a team of developers inevitably leads to some using the return value of the function called like this:</p>\n\n<pre><code>function doSomething() {\n //Some code\n return false;\n}\n</code></pre>\n\n<p>But then they forget to use <code>return doSomething()</code> in the onclick and just use <code>doSomething()</code>.</p>\n\n<p>A second reason for avoiding <code>#</code> is that the final <code>return false;</code> will not execute if the called function throws an error. Hence the developers have to also remember to handle any error appropriately in the called function.</p>\n\n<p>A third reason is that there are cases where the <code>onclick</code> event property is assigned dynamically. I prefer to be able to call a function or assign it dynamically without having to code the function specifically for one method of attachment or another. Hence my <code>onclick</code> (or on anything) in HTML markup look like this:</p>\n\n<pre><code>onclick=\"someFunc.call(this)\"\n</code></pre>\n\n<p>OR</p>\n\n<pre><code>onclick=\"someFunc.apply(this, arguments)\"\n</code></pre>\n\n<p>Using <code>javascript:void(0)</code> avoids all of the above headaches, and I haven't found any examples of a downside.</p>\n\n<p>So if you're a lone developer then you can clearly make your own choice, but if you work as a team you have to either state:</p>\n\n<p>Use <code>href=\"#\"</code>, make sure <code>onclick</code> always contains <code>return false;</code> at the end, that any called function does not throw an error and if you attach a function dynamically to the <code>onclick</code> property make sure that as well as not throwing an error it returns <code>false</code>.</p>\n\n<p>OR</p>\n\n<p>Use <code>href=\"javascript:void(0)\"</code></p>\n\n<p>The second is clearly much easier to communicate.</p>\n",
"source": "so",
"questionId": 134845
},
{
"title": "Setting &quot;checked&quot; for a checkbox with jQuery?",
"body": "<h2>jQuery 1.6+</h2>\n\n<p>Use the new <a href=\"https://api.jquery.com/prop\" rel=\"noreferrer\"><code>.prop()</code></a> method:</p>\n\n<pre><code>$('.myCheckbox').prop('checked', true);\n$('.myCheckbox').prop('checked', false);\n</code></pre>\n\n<h2>jQuery 1.5.x and below</h2>\n\n<p>The <code>.prop()</code> method is not available, so you need to use <a href=\"https://api.jquery.com/attr\" rel=\"noreferrer\"><code>.attr()</code></a>.</p>\n\n<pre><code>$('.myCheckbox').attr('checked', true);\n$('.myCheckbox').attr('checked', false);\n</code></pre>\n\n<p>Note that this is <a href=\"https://github.com/jquery/jquery/blob/1.5.2/test/unit/attributes.js#L157\" rel=\"noreferrer\">the approach used by jQuery's unit tests prior to version 1.6</a> and is preferable to using</p>\n\n<pre><code>$('.myCheckbox').removeAttr('checked');\n</code></pre>\n\n<p>since the latter will, if the box was initially checked, change the behaviour of a call to <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement.reset\" rel=\"noreferrer\"><code>.reset()</code></a> on any form that contains it - a subtle but probably unwelcome behaviour change.</p>\n\n<p>For more context, some incomplete discussion of the changes to the handling of the <code>checked</code> attribute/property in the transition from 1.5.x to 1.6 can be found in the <a href=\"https://blog.jquery.com/2011/05/03/jquery-16-released/\" rel=\"noreferrer\">version 1.6 release notes</a> and the <strong>Attributes vs. Properties</strong> section of the <a href=\"https://api.jquery.com/prop/\" rel=\"noreferrer\"><code>.prop()</code> documentation</a>.</p>\n\n<h2>Any version of jQuery</h2>\n\n<p>If you're working with just one element, you can always just modify the <a href=\"https://developer.mozilla.org/en/docs/Web/API/HTMLInputElement\" rel=\"noreferrer\"><code>HTMLInputElement</code></a>'s <code>.checked</code> property:</p>\n\n<pre><code>$('.myCheckbox')[0].checked = true;\n$('.myCheckbox')[0].checked = false;\n</code></pre>\n\n<p>The benefit to using the <code>.prop()</code> and <code>.attr()</code> methods instead of this is that they will operate on all matched elements.</p>\n",
"source": "so",
"questionId": 426258
},
{
"title": "Why does Google prepend while(1); to their JSON responses?",
"body": "<p>It prevents <a href=\"http://haacked.com/archive/2009/06/25/json-hijacking.aspx\" rel=\"noreferrer\">JSON hijacking</a>.</p>\n\n<p>Contrived example: say Google has a URL like <code>mail.google.com/json?action=inbox</code> which returns the first 50 messages of your inbox in JSON format. Evil websites on other domains can't make AJAX requests to get this data due to the same-origin policy, but they can include the URL via a <code>&lt;script&gt;</code> tag. The URL is visited with <em>your</em> cookies, and by <a href=\"http://ejohn.org/blog/re-securing-json/\" rel=\"noreferrer\">overriding the global array constructor or accessor methods</a> they can have a method called whenever an object (array or hash) attribute is set, allowing them to read the JSON content.</p>\n\n<p>The <code>while(1);</code> or <code>&amp;&amp;&amp;BLAH&amp;&amp;&amp;</code> prevents this: an AJAX request at <code>mail.google.com</code> will have full access to the text content, and can strip it away. But a <code>&lt;script&gt;</code> tag insertion blindly executes the JavaScript without any processing, resulting in either an infinite loop or a syntax error.</p>\n\n<p>This does not address the issue of <a href=\"https://en.wikipedia.org/wiki/Cross-site_request_forgery\" rel=\"noreferrer\">cross-site request forgery</a>.</p>\n",
"source": "so",
"questionId": 2669690
},
{
"title": "How do you get a timestamp in JavaScript?",
"body": "<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>var timeStampInMs = window.performance &amp;&amp; window.performance.now &amp;&amp; window.performance.timing &amp;&amp; window.performance.timing.navigationStart ? window.performance.now() + window.performance.timing.navigationStart : Date.now();\r\n\r\nconsole.log(timeStampInMs, Date.now());</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p><strong>Short &amp; Snazzy:</strong></p>\n\n<pre><code>+ new Date()\n</code></pre>\n\n<p>A unary operator like <code>plus</code> triggers the <code>valueOf</code> method in the <code>Date</code> object and it returns the timestamp (without any alteration).</p>\n\n<p><strong>Details:</strong></p>\n\n<p>On almost all current browsers you can use <a href=\"http://www.ecma-international.org/ecma-262/5.1/#sec-15.9.4.4\" rel=\"noreferrer\"><code>Date.now()</code></a> to get the UTC timestamp in <strong>milliseconds</strong>; a notable exception to this is IE8 and earlier (see <a href=\"http://kangax.github.io/compat-table/es5/#Date.now\" rel=\"noreferrer\">compatibility table</a>).</p>\n\n<p>You can easily make a shim for this, though:</p>\n\n<pre><code>if (!Date.now) {\n Date.now = function() { return new Date().getTime(); }\n}\n</code></pre>\n\n<p>To get the timestamp in <strong>seconds</strong>, you can use:</p>\n\n<pre><code>Math.floor(Date.now() / 1000)\n</code></pre>\n\n<p>Or alternatively you could use:</p>\n\n<pre><code>Date.now() / 1000 | 0\n</code></pre>\n\n<p>Which should be slightly faster, but also less readable (also <a href=\"https://stackoverflow.com/questions/7487977/using-bitwise-or-0-to-floor-a-number\">see this answer</a>).</p>\n\n<p>I would recommend using <code>Date.now()</code> (with compatibility shim). It's slightly better because it's shorter &amp; doesn't create a new <code>Date</code> object. However, if you don't want a shim &amp; maximum compatibility, you could use the \"old\" method to get the timestamp in <strong>milliseconds</strong>:</p>\n\n<pre><code>new Date().getTime()\n</code></pre>\n\n<p>Which you can then convert to seconds like this:</p>\n\n<pre><code>Math.round(new Date().getTime()/1000)\n</code></pre>\n\n<p>And you can also use the <code>valueOf</code> method which we showed above:</p>\n\n<pre><code>new Date().valueOf()\n</code></pre>\n",
"source": "so",
"questionId": 221294
},
{
"title": "How do I check if an array includes an object in JavaScript?",
"body": "<p>Current browsers have <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes#Browser_compatibility\" rel=\"noreferrer\"><code>Array#includes</code></a>, which does <em>exactly</em> that, <a href=\"https://kangax.github.io/compat-table/es2016plus/#test-Array.prototype.includes\" rel=\"noreferrer\">is widely supported</a>, and has a <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes#Polyfill\" rel=\"noreferrer\">polyfill</a> for older browsers.</p>\n\n<p>You can also use <a href=\"https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/indexOf\" rel=\"noreferrer\"><code>Array#indexOf</code></a>, which is less direct, but doesn't require Polyfills for out of date browsers.</p>\n\n<p>jQuery offers <a href=\"http://api.jquery.com/jquery.inarray/\" rel=\"noreferrer\"><code>$.inArray</code></a>, which is functionally equivalent to <code>Array#indexOf</code>.</p>\n\n<p><a href=\"http://underscorejs.org/#\" rel=\"noreferrer\">underscore.js</a>, a JavaScript utility library, offers <a href=\"http://underscorejs.org/#contains\" rel=\"noreferrer\"><code>_.contains(list, value)</code></a>, alias <code>_.include(list, value)</code>, both of which use <a href=\"http://underscorejs.org/#indexOf\" rel=\"noreferrer\">indexOf</a> internally if passed a JavaScript array.</p>\n\n<p>Some other frameworks offer similar methods:</p>\n\n<ul>\n<li>Dojo Toolkit: <a href=\"http://dojotoolkit.org/reference-guide/dojo/indexOf.html\" rel=\"noreferrer\"><code>dojo.indexOf(array, value, [fromIndex, findLast])</code></a></li>\n<li>Prototype: <a href=\"http://api.prototypejs.org/language/Array/prototype/indexOf/\" rel=\"noreferrer\"><code>array.indexOf(value)</code></a></li>\n<li>MooTools: <a href=\"https://mootools.net/core/docs/1.6.0/Types/Array#Array:indexOf\" rel=\"noreferrer\"><code>array.indexOf(value)</code></a></li>\n<li>MochiKit: <a href=\"http://mochi.github.io/mochikit/doc/html/MochiKit/Base.html#fn-findvalue\" rel=\"noreferrer\"><code>findValue(array, value)</code></a></li>\n<li>MS Ajax: <a href=\"http://www.asp.net/ajaxlibrary/Reference.Array-indexOf-Function.ashx\" rel=\"noreferrer\"><code>array.indexOf(value)</code></a></li>\n<li>Ext: <a href=\"http://docs.sencha.com/extjs/4.0.0/#/api/Ext.Array-method-contains\" rel=\"noreferrer\"><code>Ext.Array.contains(array, value)</code></a></li>\n<li>Lodash: <a href=\"https://lodash.com/docs#includes\" rel=\"noreferrer\"><code>_.includes(array, value, [from])</code></a> (is <code>_.contains</code> prior 4.0.0)</li>\n<li>ECMAScript 2016: <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes\" rel=\"noreferrer\"><code>array.includes(value)</code></a></li>\n</ul>\n\n<p>Notice that some frameworks implement this as a function, while others add the function to the array prototype.</p>\n",
"source": "so",
"questionId": 237104
},
{
"title": "Create GUID / UUID in JavaScript?",
"body": "<p>There have been a couple attempts at this. The question is: do you want actual GUIDs, or just random numbers that <em>look</em> like GUIDs? It's easy enough to generate random numbers.</p>\n\n<pre><code>function guid() {\n function s4() {\n return Math.floor((1 + Math.random()) * 0x10000)\n .toString(16)\n .substring(1);\n }\n return s4() + s4() + '-' + s4() + '-' + s4() + '-' + s4() + '-' + s4() + s4() + s4();\n}\n</code></pre>\n\n<p>However, note that such values <strong>are not genuine GUIDs</strong>.</p>\n\n<p><strike>\nThere's no way to generate real GUIDs in Javascript, because they depend on properties of the local computer that browsers do not expose. You'll need to use OS-specific services like ActiveX: <a href=\"http://p2p.wrox.com/topicindex/20339.htm\" rel=\"noreferrer\">http://p2p.wrox.com/topicindex/20339.htm</a>\n</strike></p>\n\n<p>Edit: not correct - RFC4122 allows random (\"version 4\") GUIDs. See other answers for specifics.</p>\n\n<p><strong>Note</strong>: the provided code snippet does not follow RFC4122 which requires that the version (<code>4</code>) has to be integrated into the generated output string. <strong>Do not use this answer</strong> if you need compliant GUIDs.</p>\n\n<p>Use:</p>\n\n<pre><code>var uuid = guid();\n</code></pre>\n\n<h1>Demo:</h1>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"false\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function guid() {\r\n return s4() + s4() + '-' + s4() + '-' + s4() + '-' +\r\n s4() + '-' + s4() + s4() + s4();\r\n}\r\n\r\nfunction s4() {\r\n return Math.floor((1 + Math.random()) * 0x10000)\r\n .toString(16)\r\n .substring(1);\r\n}\r\n\r\ndocument.getElementById('jsGenId').addEventListener('click', function() {\r\n document.getElementById('jsIdResult').value = guid();\r\n})</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>input { font-family: monospace; }</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;button id=\"jsGenId\" type=\"button\"&gt;Generate GUID&lt;/button&gt;\r\n&lt;br&gt;\r\n&lt;input id=\"jsIdResult\" type=\"text\" placeholder=\"Results will be placed here...\" readonly size=\"40\"/&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"source": "so",
"questionId": 105034
},
{
"title": "How to validate an email address in JavaScript?",
"body": "<p>Using <a href=\"http://en.wikipedia.org/wiki/Regular_expression\" rel=\"noreferrer\">regular expressions</a> is probably the best way. You can see a bunch of tests <a href=\"http://jsfiddle.net/ghvj4gy9/embedded/result,js/\" rel=\"noreferrer\">here</a> (taken from <a href=\"https://code.google.com/p/chromium/codesearch#chromium/src/third_party/WebKit/LayoutTests/fast/forms/resources/ValidityState-typeMismatch-email.js&amp;sq=package:chromium&amp;type=cs\" rel=\"noreferrer\">chromium</a>)</p>\n\n<pre><code>function validateEmail(email) {\n var re = /^(([^&lt;&gt;()\\[\\]\\\\.,;:\\s@\"]+(\\.[^&lt;&gt;()\\[\\]\\\\.,;:\\s@\"]+)*)|(\".+\"))@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\])|(([a-zA-Z\\-0-9]+\\.)+[a-zA-Z]{2,}))$/;\n return re.test(String(email).toLowerCase());\n}\n</code></pre>\n\n<p>Here's the example of regular expresion that accepts unicode:</p>\n\n<pre><code>var re = /^(([^&lt;&gt;()\\[\\]\\.,;:\\s@\\\"]+(\\.[^&lt;&gt;()\\[\\]\\.,;:\\s@\\\"]+)*)|(\\\".+\\\"))@(([^&lt;&gt;()[\\]\\.,;:\\s@\\\"]+\\.)+[^&lt;&gt;()[\\]\\.,;:\\s@\\\"]{2,})$/i;\n</code></pre>\n\n<p>But keep in mind that one should not rely only upon JavaScript validation. JavaScript can easily be disabled. This should be validated on the server side as well.</p>\n\n<p>Here's an example of the above in action:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function validateEmail(email) {\r\n var re = /^(([^&lt;&gt;()[\\]\\\\.,;:\\s@\\\"]+(\\.[^&lt;&gt;()[\\]\\\\.,;:\\s@\\\"]+)*)|(\\\".+\\\"))@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\])|(([a-zA-Z\\-0-9]+\\.)+[a-zA-Z]{2,}))$/;\r\n return re.test(email);\r\n}\r\n\r\nfunction validate() {\r\n var $result = $(\"#result\");\r\n var email = $(\"#email\").val();\r\n $result.text(\"\");\r\n\r\n if (validateEmail(email)) {\r\n $result.text(email + \" is valid :)\");\r\n $result.css(\"color\", \"green\");\r\n } else {\r\n $result.text(email + \" is not valid :(\");\r\n $result.css(\"color\", \"red\");\r\n }\r\n return false;\r\n}\r\n\r\n$(\"#validate\").bind(\"click\", validate);</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;script src=\"https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js\"&gt;&lt;/script&gt;\r\n\r\n&lt;form&gt;\r\n &lt;p&gt;Enter an email address:&lt;/p&gt;\r\n &lt;input id='email'&gt;\r\n &lt;button type='submit' id='validate'&gt;Validate!&lt;/button&gt;\r\n&lt;/form&gt;\r\n\r\n&lt;h2 id='result'&gt;&lt;/h2&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"source": "so",
"questionId": 46155
},
{
"title": "What&#39;s the difference between using &quot;let&quot; and &quot;var&quot; to declare a variable in JavaScript?",
"body": "<p>The difference is scoping. <code>var</code> is scoped to the nearest function block and <code>let</code> is scoped to the nearest <em>enclosing</em> block, which can be smaller than a function block. Both are global if outside any block.</p>\n\n<p>Also, variables declared with <code>let</code> are not accessible before they are declared in their enclosing block. As seen in the demo, this will throw a ReferenceError exception.</p>\n\n<p><strong><a href=\"http://jsfiddle.net/tcCp5/182/\" rel=\"noreferrer\">Demo</a>:</strong> </p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>var html = '';\r\n\r\nwrite('#### global ####\\n');\r\nwrite('globalVar: ' + globalVar); //undefined, but visible\r\n\r\ntry {\r\n write('globalLet: ' + globalLet); //undefined, *not* visible\r\n} catch (exception) {\r\n write('globalLet: exception');\r\n}\r\n\r\nwrite('\\nset variables');\r\n\r\nvar globalVar = 'globalVar';\r\nlet globalLet = 'globalLet';\r\n\r\nwrite('\\nglobalVar: ' + globalVar);\r\nwrite('globalLet: ' + globalLet);\r\n\r\nfunction functionScoped() {\r\n write('\\n#### function ####');\r\n write('\\nfunctionVar: ' + functionVar); //undefined, but visible\r\n\r\n try {\r\n write('functionLet: ' + functionLet); //undefined, *not* visible\r\n } catch (exception) {\r\n write('functionLet: exception');\r\n }\r\n\r\n write('\\nset variables');\r\n\r\n var functionVar = 'functionVar';\r\n let functionLet = 'functionLet';\r\n\r\n write('\\nfunctionVar: ' + functionVar);\r\n write('functionLet: ' + functionLet);\r\n}\r\n\r\nfunction blockScoped() {\r\n write('\\n#### block ####');\r\n write('\\nblockVar: ' + blockVar); //undefined, but visible\r\n\r\n try {\r\n write('blockLet: ' + blockLet); //undefined, *not* visible\r\n } catch (exception) {\r\n write('blockLet: exception');\r\n }\r\n\r\n for (var blockVar = 'blockVar', blockIndex = 0; blockIndex &lt; 1; blockIndex++) {\r\n write('\\nblockVar: ' + blockVar); // visible here and whole function\r\n };\r\n\r\n for (let blockLet = 'blockLet', letIndex = 0; letIndex &lt; 1; letIndex++) {\r\n write('blockLet: ' + blockLet); // visible only here\r\n };\r\n\r\n write('\\nblockVar: ' + blockVar);\r\n\r\n try {\r\n write('blockLet: ' + blockLet); //undefined, *not* visible\r\n } catch (exception) {\r\n write('blockLet: exception');\r\n }\r\n}\r\n\r\nfunction write(line) {\r\n html += (line ? line : '') + '&lt;br /&gt;';\r\n}\r\n\r\nfunctionScoped();\r\nblockScoped();\r\n\r\ndocument.getElementById('results').innerHTML = html;</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;pre id=\"results\"&gt;&lt;/pre&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<h3>Global:</h3>\n\n<p>They are very similar when used like this outside a function block.</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>let me = 'go'; // globally scoped\nvar i = 'able'; // globally scoped\n</code></pre>\n\n<p>However, global variables defined with <code>let</code> will not be added as properties on the global <code>window</code> object like those defined with <code>var</code>.</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>console.log(window.me); // undefined\nconsole.log(window.i); // 'able'\n</code></pre>\n\n<h3>Function:</h3>\n\n<p>They are identical when used like this in a function block.</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>function ingWithinEstablishedParameters() {\n let terOfRecommendation = 'awesome worker!'; //function block scoped\n var sityCheerleading = 'go!'; //function block scoped\n}\n</code></pre>\n\n<h3>Block:</h3>\n\n<p>Here is the difference. <code>let</code> is only visible in the <code>for()</code> loop and <code>var</code> is visible to the whole function.</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>function allyIlliterate() {\n //tuce is *not* visible out here\n\n for( let tuce = 0; tuce &lt; 5; tuce++ ) {\n //tuce is only visible in here (and in the for() parentheses)\n //and there is a separate tuce variable for each iteration of the loop\n }\n\n //tuce is *not* visible out here\n}\n\nfunction byE40() {\n //nish *is* visible out here\n\n for( var nish = 0; nish &lt; 5; nish++ ) {\n //nish is visible to the whole function\n }\n\n //nish *is* visible out here\n}\n</code></pre>\n\n<h3>Redeclaration:</h3>\n\n<p>Assuming strict mode, <code>var</code> will let you re-declare the same variable in the same scope. On the other hand, <code>let</code> will not:</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>'use strict';\nlet me = 'foo';\nlet me = 'bar'; // SyntaxError: Identifier 'me' has already been declared\n</code></pre>\n\n<pre class=\"lang-js prettyprint-override\"><code>'use strict';\nvar me = 'foo';\nvar me = 'bar'; // No problem, `me` is replaced.\n</code></pre>\n",
"source": "so",
"questionId": 762011
},
{
"title": "How to replace all occurrences of a string in JavaScript?",
"body": "<p>For the sake of completeness, I got to thinking about which method I should use to do this. There are basically two ways to do this as suggested by the other answers on this page.</p>\n\n<p><strong>Note:</strong> In general, extending the built-in prototypes in JavaScript is generally not recommended. I am providing as extensions on the String prototype simply for purposes of illustration, showing different implementations of a hypothetical standard method on the <code>String</code> built-in prototype.</p>\n\n<hr>\n\n<h3>Regular Expression Based Implementation</h3>\n\n<pre><code>String.prototype.replaceAll = function(search, replacement) {\n var target = this;\n return target.replace(new RegExp(search, 'g'), replacement);\n};\n</code></pre>\n\n<h3>Split and Join (Functional) Implementation</h3>\n\n<pre><code>String.prototype.replaceAll = function(search, replacement) {\n var target = this;\n return target.split(search).join(replacement);\n};\n</code></pre>\n\n<hr>\n\n<p>Not knowing too much about how regular expressions work behind the scenes in terms of efficiency, I tended to lean toward the split and join implementation in the past without thinking about performance. When I did wonder which was more efficient, and by what margin, I used it as an excuse to find out.</p>\n\n<p>On my Chrome Windows&nbsp;8 machine, <strong>the regular expression based implementation is the fastest</strong>, with the <strong>split and join implementation being 53% slower</strong>. Meaning the regular expressions are twice as fast for the lorem ipsum input I used.</p>\n\n<p>Check out this <a href=\"http://jsben.ch/#/LFfWA\" rel=\"noreferrer\"><strong>benchmark</strong></a> running these two implementations against each other.</p>\n\n<hr>\n\n<p>As noted in the comment below by @ThomasLeduc and others, there could be an issue with the regular expression-based implementation if <code>search</code> contains certain characters which are reserved as <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions#Using_special_characters\" rel=\"noreferrer\">special characters in regular expressions</a>. The implementation assumes that the caller will escape the string beforehand or will only pass strings that are without the characters in the table in <em><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions#Using_special_characters\" rel=\"noreferrer\">Regular Expressions</a></em> (MDN).</p>\n\n<p>MDN also provides an implementation to escape our strings. It would be nice if this was also standardized as <code>RegExp.escape(str)</code>, but alas, it does not exist:</p>\n\n<pre><code>function escapeRegExp(str) {\n return str.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&amp;\"); // $&amp; means the whole matched string\n}\n</code></pre>\n\n<p>We could call <code>escapeRegExp</code> within our <code>String.prototype.replaceAll</code> implementation, however, I'm not sure how much this will affect the performance (potentially even for strings for which the escape is not needed, like all alphanumeric strings).</p>\n",
"source": "so",
"questionId": 1144783
},
{
"title": "How do I make the first letter of a string uppercase in JavaScript?",
"body": "<pre><code>function capitalizeFirstLetter(string) {\n return string.charAt(0).toUpperCase() + string.slice(1);\n}\n</code></pre>\n\n<p>Some other answers modify <code>String.prototype</code> (this answer used to as well), but I would advise against this now due to maintainability (hard to find out where the function is being added to the <code>prototype</code> and could cause conflicts if other code uses the same name / a browser adds a native function with that same name in future).</p>\n",
"source": "so",
"questionId": 1026069
},
{
"title": "How to append something to an array?",
"body": "<p>Use the <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push\" rel=\"noreferrer\"><code>push()</code></a> function to append to an array:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>// initialize array\r\nvar arr = [\r\n \"Hi\",\r\n \"Hello\",\r\n \"Bonjour\"\r\n];\r\n\r\n// append new value to the array\r\narr.push(\"Hola\");\r\n\r\nconsole.log(arr);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>Will print</p>\n\n<pre><code>[\"Hi\", \"Hello\", \"Bonjour\", \"Hola\"]\n</code></pre>\n\n<hr>\n\n<p>You can use the <code>push()</code> function to append more than one value to an array in a single call:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>// initialize array\r\nvar arr = [ \"Hi\", \"Hello\", \"Bonjour\", \"Hola\" ];\r\n\r\n// append multiple values to the array\r\narr.push(\"Salut\", \"Hey\");\r\n\r\n// display all values\r\nfor (var i = 0; i &lt; arr.length; i++) {\r\n console.log(arr[i]);\r\n}</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>Will print</p>\n\n<pre><code>Hi\nHello\nBonjour\nHola \nSalut\nHey\n</code></pre>\n\n<hr>\n\n<p><strong>Update</strong></p>\n\n<p>If you want to add the items of one array to another array, you can use <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/concat\" rel=\"noreferrer\"><code>firstArray.concat(secondArray)</code></a>:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>var arr = [\r\n \"apple\",\r\n \"banana\",\r\n \"cherry\"\r\n];\r\n\r\narr = arr.concat([\r\n \"dragonfruit\",\r\n \"elderberry\",\r\n \"fig\"\r\n]);\r\n\r\nconsole.log(arr);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>Will print</p>\n\n<pre><code>[\"apple\", \"banana\", \"cherry\", \"dragonfruit\", \"elderberry\", \"fig\"]\n</code></pre>\n",
"source": "so",
"questionId": 351409
},
{
"title": "How can I get query string values in JavaScript?",
"body": "<p>You don't need jQuery for that purpose. You can use just some pure JavaScript:</p>\n\n<pre><code>function getParameterByName(name, url) {\n if (!url) url = window.location.href;\n name = name.replace(/[\\[\\]]/g, \"\\\\$&amp;\");\n var regex = new RegExp(\"[?&amp;]\" + name + \"(=([^&amp;#]*)|&amp;|#|$)\"),\n results = regex.exec(url);\n if (!results) return null;\n if (!results[2]) return '';\n return decodeURIComponent(results[2].replace(/\\+/g, \" \"));\n}\n</code></pre>\n\n<p><strong>Usage:</strong></p>\n\n<pre><code>// query string: ?foo=lorem&amp;bar=&amp;baz\nvar foo = getParameterByName('foo'); // \"lorem\"\nvar bar = getParameterByName('bar'); // \"\" (present with empty value)\nvar baz = getParameterByName('baz'); // \"\" (present with no value)\nvar qux = getParameterByName('qux'); // null (absent)\n</code></pre>\n\n<p><br>\nNote: If a parameter is present several times (<code>?foo=lorem&amp;foo=ipsum</code>), you will get the first value (<code>lorem</code>). There is no standard about this and usages vary, see for example this question: <a href=\"https://stackoverflow.com/questions/1746507/authoritative-position-of-duplicate-http-get-query-keys\">Authoritative position of duplicate HTTP GET query keys</a>.</p>\n\n<hr>\n\n<p>This is an update based on the new <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams\" rel=\"noreferrer\">URLSearchParams specs</a> to achieve the same result more succinctly. See answer titled \"<a href=\"https://stackoverflow.com/questions/901115/how-can-i-get-query-string-values-in-javascript/901144#12151322\">URLSearchParams</a>\" below.</p>\n",
"source": "so",
"questionId": 901115
},
{
"title": "What is the difference between call and apply?",
"body": "<p>The difference is that <code>apply</code> lets you invoke the function with <code>arguments</code> as an array; <code>call</code> requires the parameters be listed explicitly. A useful mnemonic is <em>\"<strong>A</strong> for <strong>a</strong>rray and <strong>C</strong> for <strong>c</strong>omma.\"</em></p>\n\n<p>See MDN's documentation on <a href=\"https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/apply\" rel=\"noreferrer\">apply</a> and <a href=\"https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/call\" rel=\"noreferrer\">call</a>.</p>\n\n<p>Pseudo syntax:</p>\n\n<p><code>theFunction.apply(valueForThis, arrayOfArgs)</code></p>\n\n<p><code>theFunction.call(valueForThis, arg1, arg2, ...)</code></p>\n\n<p>There is also, as of ES6, the possibility to <a href=\"https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Spread_operator\" rel=\"noreferrer\"><code>spread</code></a> the array for use with the <code>call</code> function, you can see the compatibilities <a href=\"http://kangax.github.io/compat-table/es6/\" rel=\"noreferrer\">here</a>.</p>\n\n<p>Sample code:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function theFunction(name, profession) {\r\n console.log(\"My name is \" + name + \" and I am a \" + profession +\".\");\r\n}\r\ntheFunction(\"John\", \"fireman\");\r\ntheFunction.apply(undefined, [\"Susan\", \"school teacher\"]);\r\ntheFunction.call(undefined, \"Claude\", \"mathematician\");\r\ntheFunction.call(undefined, ...[\"Matthew\", \"physicist\"]); // used with the spread operator</code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"source": "so",
"questionId": 1986896
},
{
"title": "event.preventDefault() vs. return false",
"body": "<p><code>return false</code> from <em>within a jQuery event handler</em> is effectively the same as calling both <code>e.preventDefault</code> and <code>e.stopPropagation</code> on the passed <a href=\"http://api.jquery.com/category/events/event-object/\" rel=\"noreferrer\">jQuery.Event object.</a></p>\n\n<p><code>e.preventDefault()</code> will prevent the default event from occuring, <code>e.stopPropagation()</code> will prevent the event from bubbling up and <code>return false</code> will do both. Note that this behaviour differs from <em>normal</em> (non-jQuery) event handlers, in which, notably, <code>return false</code> does <em>not</em> stop the event from bubbling up.</p>\n\n<p>Source: <a href=\"http://ejohn.org/\" rel=\"noreferrer\">John Resig</a></p>\n\n<p><a href=\"http://www.mail-archive.com/[email protected]/msg71371.html\" rel=\"noreferrer\"><strong>Any benefit to using event.preventDefault() over \"return false\" to cancel out an href click?</strong></a></p>\n",
"source": "so",
"questionId": 1357118
},
{
"title": "How do I copy to the clipboard in JavaScript?",
"body": "<h1>Overview</h1>\n\n<p>There are 3 primary browser APIs for copying to the clipboard:</p>\n\n<ol>\n<li><a href=\"https://www.w3.org/TR/clipboard-apis/#async-clipboard-api\" rel=\"noreferrer\">Async Clipboard API</a> <code>[navigator.clipboard.writeText]</code>\n\n<ul>\n<li>Text-focused portion available in <a href=\"https://developers.google.com/web/updates/2018/03/clipboardapi\" rel=\"noreferrer\">Chrome 66 (March 2018)</a></li>\n<li>Access is asynchronous and uses <a href=\"https://developers.google.com/web/fundamentals/primers/promises\" rel=\"noreferrer\">JavaScript Promises</a>, can be written so security user prompts (if displayed) don't interrupt the JavaScript in page.</li>\n<li>Text can be copied to the clipboard directly from a variable.</li>\n<li>Only supported on pages served over HTTPS.</li>\n<li>In Chrome 66 pages in active tabs can write to the clipboard without a permissions prompt.</li>\n</ul></li>\n<li><code>document.execCommand('copy')</code>\n\n<ul>\n<li>Most browsers support this as of ~April 2015 (see Browser Support below).</li>\n<li>Access is synchronous, i.e. stops JavaScript in the page until complete including displaying and user interacting with any security prompts.</li>\n<li>Text is read from the DOM and placed on the clipboard.</li>\n<li>During testing ~April 2015 only Internet Explorer was noted as displaying permissions prompts whilst writing to the clipboard.</li>\n</ul></li>\n<li>Overriding the copy event\n\n<ul>\n<li>See Clipboard API documentation on <a href=\"https://w3c.github.io/clipboard-apis/#override-copy\" rel=\"noreferrer\">Overriding the copy event</a>.</li>\n<li>Allows you to modify what appear on the clipboard from any copy event, can include other formats of data other than plain text.</li>\n<li>Not covered here as it doesn't directly answer the question.</li>\n</ul></li>\n</ol>\n\n<h1>General development notes</h1>\n\n<p>Don't expect clipboard related commands to work whilst you testing code in the console. Generally the page is required to be active (Async Clipboard API) or requires user interaction (e.g. a user click) to allow (<code>document.execCommand('copy')</code>) to access the clipboard see below for more detail.</p>\n\n<h1>Async + Fallback</h1>\n\n<p>Due to the level of browser support for the new Async Clipboard API you will likely want to fallback to the <code>document.execCommand('copy')</code> method to get good browser coverage.</p>\n\n<p>Here is a simple example:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function fallbackCopyTextToClipboard(text) {\r\n var textArea = document.createElement(\"textarea\");\r\n textArea.value = text;\r\n document.body.appendChild(textArea);\r\n textArea.focus();\r\n textArea.select();\r\n\r\n try {\r\n var successful = document.execCommand('copy');\r\n var msg = successful ? 'successful' : 'unsuccessful';\r\n console.log('Fallback: Copying text command was ' + msg);\r\n } catch (err) {\r\n console.error('Fallback: Oops, unable to copy', err);\r\n }\r\n\r\n document.body.removeChild(textArea);\r\n}\r\nfunction copyTextToClipboard(text) {\r\n if (!navigator.clipboard) {\r\n fallbackCopyTextToClipboard(text);\r\n return;\r\n }\r\n navigator.clipboard.writeText(text).then(function() {\r\n console.log('Async: Copying to clipboard was successful!');\r\n }, function(err) {\r\n console.error('Async: Could not copy text: ', err);\r\n });\r\n}\r\n\r\nvar copyBobBtn = document.querySelector('.js-copy-bob-btn'),\r\n copyJaneBtn = document.querySelector('.js-copy-jane-btn');\r\n\r\ncopyBobBtn.addEventListener('click', function(event) {\r\n copyTextToClipboard('Bob');\r\n});\r\n\r\n\r\ncopyJaneBtn.addEventListener('click', function(event) {\r\n copyTextToClipboard('Jane');\r\n});</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;div style=\"display:inline-block; vertical-align:top;\"&gt;\r\n &lt;button class=\"js-copy-bob-btn\"&gt;Set clipboard to BOB&lt;/button&gt;&lt;br /&gt;&lt;br /&gt;\r\n &lt;button class=\"js-copy-jane-btn\"&gt;Set clipboard to JANE&lt;/button&gt;\r\n&lt;/div&gt;\r\n&lt;div style=\"display:inline-block;\"&gt;\r\n &lt;textarea class=\"js-test-textarea\" cols=\"35\" rows=\"4\"&gt;Try pasting into here to see what you have on your clipboard:\r\n \r\n &lt;/textarea&gt;\r\n&lt;/div&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>Note that this snippet is not working well in StackOverflow's embedded preview you can try it here:\n<a href=\"https://codepen.io/DeanMarkTaylor/pen/RMRaJX?editors=1011\" rel=\"noreferrer\">https://codepen.io/DeanMarkTaylor/pen/RMRaJX?editors=1011</a></p>\n\n<h1>Async Clipboard API</h1>\n\n<ul>\n<li><a href=\"https://developers.google.com/web/updates/2018/03/clipboardapi\" rel=\"noreferrer\">Chrome 66 announcement post (March 2018)</a></li>\n<li>Reference <a href=\"https://www.w3.org/TR/clipboard-apis/#async-clipboard-api\" rel=\"noreferrer\">Async Clipboard API</a> draft documentation</li>\n</ul>\n\n<p>Note that there is an ability to \"request permission\" and test for access to the clipboard via the permissions API in Chrome 66.</p>\n\n<pre><code>var text = \"Example text to appear on clipboard\";\nnavigator.clipboard.writeText(text).then(function() {\n console.log('Async: Copying to clipboard was successful!');\n}, function(err) {\n console.error('Async: Could not copy text: ', err);\n});\n</code></pre>\n\n<h1>document.execCommand('copy')</h1>\n\n<p>The rest of this post goes into the nuances and detail of the <code>document.execCommand('copy')</code> API.</p>\n\n<h2>Browser Support</h2>\n\n<p>The JavaScript <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Document/execCommand\" rel=\"noreferrer\"><code>document.execCommand('copy')</code></a> support has grown, see the links below for browser updates:</p>\n\n<ul>\n<li>IE10+ (although <a href=\"https://msdn.microsoft.com/en-us/library/ms537834(v=vs.85).aspx\" rel=\"noreferrer\">this document</a> indicates some support was there from IE5.5+).</li>\n<li><a href=\"https://developers.google.com/web/updates/2015/04/cut-and-copy-commands?hl=en\" rel=\"noreferrer\">Google Chrome 43+ (~April 2015)</a></li>\n<li><a href=\"https://developer.mozilla.org/en-US/Firefox/Releases/41#Interfaces.2FAPIs.2FDOM\" rel=\"noreferrer\">Mozilla Firefox 41+ (shipping ~September 2015)</a></li>\n<li><a href=\"https://dev.opera.com/blog/opera-29/#cut-and-copy-commands\" rel=\"noreferrer\">Opera 29+ (based on Chromium 42, ~April 2015)</a> </li>\n</ul>\n\n<h2>Simple Example</h2>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>var copyTextareaBtn = document.querySelector('.js-textareacopybtn');\r\n\r\ncopyTextareaBtn.addEventListener('click', function(event) {\r\n var copyTextarea = document.querySelector('.js-copytextarea');\r\n copyTextarea.focus();\r\n copyTextarea.select();\r\n\r\n try {\r\n var successful = document.execCommand('copy');\r\n var msg = successful ? 'successful' : 'unsuccessful';\r\n console.log('Copying text command was ' + msg);\r\n } catch (err) {\r\n console.log('Oops, unable to copy');\r\n }\r\n});</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;p&gt;\r\n &lt;button class=\"js-textareacopybtn\" style=\"vertical-align:top;\"&gt;Copy Textarea&lt;/button&gt;\r\n &lt;textarea class=\"js-copytextarea\"&gt;Hello I'm some text&lt;/textarea&gt;\r\n&lt;/p&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<h2>Complex Example: Copy to clipboard without displaying input</h2>\n\n<p>The above simple example works great if there is a <code>textarea</code> or <code>input</code> element visible on screen. </p>\n\n<p>In some cases you might wish to copy text to the clipboard without displaying an <code>input</code> / <code>textarea</code> element. This is one example of a way to work around this (basically insert element, copy to clipboard, remove element):</p>\n\n<p>Tested with Google Chrome 44, Firefox 42.0a1 and IE 11.0.8600.17814.</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function copyTextToClipboard(text) {\r\n var textArea = document.createElement(\"textarea\");\r\n\r\n //\r\n // *** This styling is an extra step which is likely not required. ***\r\n //\r\n // Why is it here? To ensure:\r\n // 1. the element is able to have focus and selection.\r\n // 2. if element was to flash render it has minimal visual impact.\r\n // 3. less flakyness with selection and copying which **might** occur if\r\n // the textarea element is not visible.\r\n //\r\n // The likelihood is the element won't even render, not even a flash,\r\n // so some of these are just precautions. However in IE the element\r\n // is visible whilst the popup box asking the user for permission for\r\n // the web page to copy to the clipboard.\r\n //\r\n\r\n // Place in top-left corner of screen regardless of scroll position.\r\n textArea.style.position = 'fixed';\r\n textArea.style.top = 0;\r\n textArea.style.left = 0;\r\n\r\n // Ensure it has a small width and height. Setting to 1px / 1em\r\n // doesn't work as this gives a negative w/h on some browsers.\r\n textArea.style.width = '2em';\r\n textArea.style.height = '2em';\r\n\r\n // We don't need padding, reducing the size if it does flash render.\r\n textArea.style.padding = 0;\r\n\r\n // Clean up any borders.\r\n textArea.style.border = 'none';\r\n textArea.style.outline = 'none';\r\n textArea.style.boxShadow = 'none';\r\n\r\n // Avoid flash of white box if rendered for any reason.\r\n textArea.style.background = 'transparent';\r\n\r\n\r\n textArea.value = text;\r\n\r\n document.body.appendChild(textArea);\r\n textArea.focus();\r\n textArea.select();\r\n\r\n try {\r\n var successful = document.execCommand('copy');\r\n var msg = successful ? 'successful' : 'unsuccessful';\r\n console.log('Copying text command was ' + msg);\r\n } catch (err) {\r\n console.log('Oops, unable to copy');\r\n }\r\n\r\n document.body.removeChild(textArea);\r\n}\r\n\r\n\r\nvar copyBobBtn = document.querySelector('.js-copy-bob-btn'),\r\n copyJaneBtn = document.querySelector('.js-copy-jane-btn');\r\n\r\ncopyBobBtn.addEventListener('click', function(event) {\r\n copyTextToClipboard('Bob');\r\n});\r\n\r\n\r\ncopyJaneBtn.addEventListener('click', function(event) {\r\n copyTextToClipboard('Jane');\r\n});</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;div style=\"display:inline-block; vertical-align:top;\"&gt;\r\n &lt;button class=\"js-copy-bob-btn\"&gt;Set clipboard to BOB&lt;/button&gt;&lt;br /&gt;&lt;br /&gt;\r\n &lt;button class=\"js-copy-jane-btn\"&gt;Set clipboard to JANE&lt;/button&gt;\r\n&lt;/div&gt;\r\n&lt;div style=\"display:inline-block;\"&gt;\r\n &lt;textarea class=\"js-test-textarea\" cols=\"35\" rows=\"4\"&gt;Try pasting into here to see what you have on your clipboard:\r\n \r\n &lt;/textarea&gt;\r\n&lt;/div&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<h2>Additional notes</h2>\n\n<h3>Only works if the user takes an action</h3>\n\n<p>All <code>document.execCommand('copy')</code> calls must take place as a direct result of a user action, e.g. click event handler. This is a measure to prevent messing with the users clipboard when they don't expect it.</p>\n\n<p>See the <a href=\"https://developers.google.com/web/updates/2015/04/cut-and-copy-commands?hl=en\" rel=\"noreferrer\">Google Developers post here</a> for more info.</p>\n\n<h3>Clipboard API</h3>\n\n<p>Note the full Clipboard API draft specification can be found here:\n<a href=\"https://w3c.github.io/clipboard-apis/\" rel=\"noreferrer\">https://w3c.github.io/clipboard-apis/</a></p>\n\n<h3>Is it supported?</h3>\n\n<ul>\n<li><code>document.queryCommandSupported('copy')</code> should return <code>true</code> if the command \"is supported by the browser\".</li>\n<li>and <code>document.queryCommandEnabled('copy')</code> return <code>true</code> if the <code>document.execCommand('copy')</code> will succeed if called now. Checking to ensure the command was called from a user-initiated thread and other requirements are met.</li>\n</ul>\n\n<p>However as an example of browser compatibility issues, Google Chrome from ~April to ~October 2015 only returned <code>true</code> from <code>document.queryCommandSupported('copy')</code> if the command was called from a user-initiated thread.</p>\n\n<p>Note compatibility detail below.</p>\n\n<h3>Browser Compatibility Detail</h3>\n\n<p>Whilst a simple call to <code>document.execCommand('copy')</code> wrapped in a <code>try</code>/<code>catch</code> block called as a result of a user click will get you the most compatibility use the following has some provisos:</p>\n\n<p>Any call to <code>document.execCommand</code>, <code>document.queryCommandSupported</code> or <code>document.queryCommandEnabled</code> should be wrapped in a <code>try</code>/<code>catch</code> block.</p>\n\n<p>Different browser implementations and browser versions throw differing types of exceptions when called instead of returning <code>false</code>.</p>\n\n<p>Different browser implementations are still in flux and the <a href=\"https://w3c.github.io/clipboard-apis/\" rel=\"noreferrer\">Clipboard API</a> is still in draft, so remember to do your testing.</p>\n",
"source": "so",
"questionId": 400212
},
{
"title": "How can I upload files asynchronously?",
"body": "<p>With <a href=\"http://en.wikipedia.org/wiki/HTML5\" rel=\"noreferrer\">HTML5</a> you can make file uploads with Ajax and jQuery. Not only that, you can do file validations (name, size, and MIME type) or handle the progress event with the HTML5 progress tag (or a div). Recently I had to make a file uploader, but I didn't want to use <a href=\"http://en.wikipedia.org/wiki/Adobe_Flash\" rel=\"noreferrer\">Flash</a> nor Iframes or plugins and after some research I came up with the solution.</p>\n\n<p>The HTML:</p>\n\n<pre><code>&lt;form enctype=\"multipart/form-data\"&gt;\n &lt;input name=\"file\" type=\"file\" /&gt;\n &lt;input type=\"button\" value=\"Upload\" /&gt;\n&lt;/form&gt;\n&lt;progress&gt;&lt;/progress&gt;\n</code></pre>\n\n<p>First, you can do some validation if you want. For example, in the onChange event of the file:</p>\n\n<pre><code>$(':file').on('change', function() {\n var file = this.files[0];\n if (file.size &gt; 1024) {\n alert('max upload size is 1k')\n }\n\n // Also see .name, .type\n});\n</code></pre>\n\n<p>Now the Ajax submit with the button's click:</p>\n\n<pre><code>$(':button').on('click', function() {\n $.ajax({\n // Your server script to process the upload\n url: 'upload.php',\n type: 'POST',\n\n // Form data\n data: new FormData($('form')[0]),\n\n // Tell jQuery not to process data or worry about content-type\n // You *must* include these options!\n cache: false,\n contentType: false,\n processData: false,\n\n // Custom XMLHttpRequest\n xhr: function() {\n var myXhr = $.ajaxSettings.xhr();\n if (myXhr.upload) {\n // For handling the progress of the upload\n myXhr.upload.addEventListener('progress', function(e) {\n if (e.lengthComputable) {\n $('progress').attr({\n value: e.loaded,\n max: e.total,\n });\n }\n } , false);\n }\n return myXhr;\n }\n });\n});\n</code></pre>\n\n<p>As you can see, with HTML5 (and some research) file uploading not only becomes possible but super easy. Try it with <a href=\"http://en.wikipedia.org/wiki/Google_Chrome\" rel=\"noreferrer\">Google Chrome</a> as some of the HTML5 components of the examples aren't available in every browser.</p>\n",
"source": "so",
"questionId": 166221
},
{
"title": "Get the current URL with JavaScript?",
"body": "<p>Use:</p>\n\n<pre><code>window.location.href \n</code></pre>\n\n<p>As noted in the comments, the line below works, but it is bugged for Firefox.</p>\n\n<pre><code>document.URL;\n</code></pre>\n\n<p>See <strong><a href=\"https://web.archive.org/web/20170327080647/http://www.w3.org/TR/DOM-Level-2-HTML/html.html#ID-46183437\" rel=\"noreferrer\">URL of type DOMString, readonly</a></strong>.</p>\n",
"source": "so",
"questionId": 1034621
},
{
"title": "Detecting an undefined object property",
"body": "<p>Use:</p>\n\n<pre><code>if (typeof something === \"undefined\") {\n alert(\"something is undefined\");\n}\n</code></pre>\n\n<p>If an object variable which have some properties you can use same thing like this:</p>\n\n<pre><code>if (typeof my_obj.someproperties === \"undefined\"){\n console.log('the property is not available...'); // print into console\n}\n</code></pre>\n",
"source": "so",
"questionId": 27509
},
{
"title": "Loop through an array in JavaScript",
"body": "<p>Use a sequential <code>for</code> loop:</p>\n\n<pre><code>var myStringArray = [\"Hello\",\"World\"];\nvar arrayLength = myStringArray.length;\nfor (var i = 0; i &lt; arrayLength; i++) {\n alert(myStringArray[i]);\n //Do something\n}\n</code></pre>\n\n<p>@zipcodeman suggests the use of the <code>for...in</code> statement, but for iterating arrays <code>for-in</code> should be avoided, that statement is meant to <strong>enumerate</strong> object properties.</p>\n\n<p>It shouldn't be used for array-like objects because:</p>\n\n<ul>\n<li>The order of iteration is not guaranteed, the array indexes may not be visited in numeric order.</li>\n<li>Inherited properties are also enumerated.</li>\n</ul>\n\n<p>The second point is that it can give you a lot of problems, for example, if you extend the <code>Array.prototype</code> object to include a method there, that property will be also enumerated.</p>\n\n<p>For example:</p>\n\n<pre><code>Array.prototype.foo = \"foo!\";\nvar array = ['a', 'b', 'c'];\n\nfor (var i in array) {\n alert(array[i]);\n}\n</code></pre>\n\n<p>The above code will alert, \"a\", \"b\", \"c\" and \"foo!\".</p>\n\n<p>That be particularly a problem if you use some library that relies heavily on native prototypes augmention (such as MooTools for example).</p>\n\n<p>The <code>for-in</code> statement as I said before is there to <em>enumerate</em> object properties, for example:</p>\n\n<pre><code>var obj = {\n \"a\": 1,\n \"b\": 2,\n \"c\": 3\n};\n\nfor (var prop in obj) {\n if (obj.hasOwnProperty(prop)) { \n // or if (Object.prototype.hasOwnProperty.call(obj,prop)) for safety...\n alert(\"prop: \" + prop + \" value: \" + obj[prop])\n }\n}\n</code></pre>\n\n<p>In the above example the <code>hasOwnProperty</code> method allows you to enumerate only <em>own properties</em>, that's it, only the properties that the object physically has, no inherited properties.</p>\n\n<p>I would recommend you to read the following article:</p>\n\n<ul>\n<li><a href=\"http://web.archive.org/web/20101213150231/http://dhtmlkitchen.com/?category=/JavaScript/&amp;date=2007/10/21/&amp;entry=Iteration-Enumeration-Primitives-and-Objects\" rel=\"noreferrer\">Enumeration VS Iteration</a></li>\n</ul>\n",
"source": "so",
"questionId": 3010840
},
{
"title": "How do I correctly clone a JavaScript object?",
"body": "<h1>Updated answer</h1>\n\n<p>Just use <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign\" rel=\"noreferrer\">Object.assign()</a> as suggested <a href=\"https://stackoverflow.com/a/30042948/4031815\">here</a></p>\n\n<hr>\n\n<h1>Outdated answer</h1>\n\n<p>To do this for any object in JavaScript will not be simple or straightforward. You will run into the problem of erroneously picking up attributes from the object's prototype that should be left in the prototype and not copied to the new instance. If, for instance, you are adding a <code>clone</code> method to <code>Object.prototype</code>, as some answers depict, you will need to explicitly skip that attribute. But what if there are other additional methods added to <code>Object.prototype</code>, or other intermediate prototypes, that you don't know about? In that case, you will copy attributes you shouldn't, so you need to detect unforeseen, non-local attributes with the <a href=\"https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Object/hasOwnProperty\" rel=\"noreferrer\" title=\"Mozilla JavaScript Reference: Object.hasOwnProperty\"><code>hasOwnProperty</code></a> method.</p>\n\n<p>In addition to non-enumerable attributes, you'll encounter a tougher problem when you try to copy objects that have hidden properties. For example, <code>prototype</code> is a hidden property of a function. Also, an object's prototype is referenced with the attribute <code>__proto__</code>, which is also hidden, and will not be copied by a for/in loop iterating over the source object's attributes. I think <code>__proto__</code> might be specific to Firefox's JavaScript interpreter and it may be something different in other browsers, but you get the picture. Not everything is enumerable. You can copy a hidden attribute if you know its name, but I don't know of any way to discover it automatically.</p>\n\n<p>Yet another snag in the quest for an elegant solution is the problem of setting up the prototype inheritance correctly. If your source object's prototype is <code>Object</code>, then simply creating a new general object with <code>{}</code> will work, but if the source's prototype is some descendant of <code>Object</code>, then you are going to be missing the additional members from that prototype which you skipped using the <code>hasOwnProperty</code> filter, or which were in the prototype, but weren't enumerable in the first place. One solution might be to call the source object's <code>constructor</code> property to get the initial copy object and then copy over the attributes, but then you still will not get non-enumerable attributes. For example, a <a href=\"https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Date\" rel=\"noreferrer\" title=\"Mozilla JavaScript Reference: Date\"><code>Date</code></a> object stores its data as a hidden member:</p>\n\n<pre><code>function clone(obj) {\n if (null == obj || \"object\" != typeof obj) return obj;\n var copy = obj.constructor();\n for (var attr in obj) {\n if (obj.hasOwnProperty(attr)) copy[attr] = obj[attr];\n }\n return copy;\n}\n\nvar d1 = new Date();\n\n/* Executes function after 5 seconds. */\nsetTimeout(function(){\n var d2 = clone(d1);\n alert(\"d1 = \" + d1.toString() + \"\\nd2 = \" + d2.toString());\n}, 5000);\n</code></pre>\n\n<p>The date string for <code>d1</code> will be 5 seconds behind that of <code>d2</code>. A way to make one <code>Date</code> the same as another is by calling the <code>setTime</code> method, but that is specific to the <code>Date</code> class. I don't think there is a bullet-proof general solution to this problem, though I would be happy to be wrong!</p>\n\n<p>When I had to implement general deep copying I ended up compromising by assuming that I would only need to copy a plain <code>Object</code>, <code>Array</code>, <code>Date</code>, <code>String</code>, <code>Number</code>, or <code>Boolean</code>. The last 3 types are immutable, so I could perform a shallow copy and not worry about it changing. I further assumed that any elements contained in <code>Object</code> or <code>Array</code> would also be one of the 6 simple types in that list. This can be accomplished with code like the following:</p>\n\n<pre><code>function clone(obj) {\n var copy;\n\n // Handle the 3 simple types, and null or undefined\n if (null == obj || \"object\" != typeof obj) return obj;\n\n // Handle Date\n if (obj instanceof Date) {\n copy = new Date();\n copy.setTime(obj.getTime());\n return copy;\n }\n\n // Handle Array\n if (obj instanceof Array) {\n copy = [];\n for (var i = 0, len = obj.length; i &lt; len; i++) {\n copy[i] = clone(obj[i]);\n }\n return copy;\n }\n\n // Handle Object\n if (obj instanceof Object) {\n copy = {};\n for (var attr in obj) {\n if (obj.hasOwnProperty(attr)) copy[attr] = clone(obj[attr]);\n }\n return copy;\n }\n\n throw new Error(\"Unable to copy obj! Its type isn't supported.\");\n}\n</code></pre>\n\n<p>The above function will work adequately for the 6 simple types I mentioned, as long as the data in the objects and arrays form a tree structure. That is, there isn't more than one reference to the same data in the object. For example:</p>\n\n<pre><code>// This would be cloneable:\nvar tree = {\n \"left\" : { \"left\" : null, \"right\" : null, \"data\" : 3 },\n \"right\" : null,\n \"data\" : 8\n};\n\n// This would kind-of work, but you would get 2 copies of the \n// inner node instead of 2 references to the same copy\nvar directedAcylicGraph = {\n \"left\" : { \"left\" : null, \"right\" : null, \"data\" : 3 },\n \"data\" : 8\n};\ndirectedAcyclicGraph[\"right\"] = directedAcyclicGraph[\"left\"];\n\n// Cloning this would cause a stack overflow due to infinite recursion:\nvar cyclicGraph = {\n \"left\" : { \"left\" : null, \"right\" : null, \"data\" : 3 },\n \"data\" : 8\n};\ncyclicGraph[\"right\"] = cyclicGraph;\n</code></pre>\n\n<p>It will not be able to handle any JavaScript object, but it may be sufficient for many purposes as long as you don't assume that it will just work for anything you throw at it.</p>\n",
"source": "so",
"questionId": 728360
},
{
"title": "Is there an &amp;quot;exists&amp;quot; function for jQuery?",
"body": "<p>In JavaScript, everything is 'truthy' or 'falsy', and for numbers <code>0</code> (and NaN) means <code>false</code>, everything else <code>true</code>. So you could write:</p>\n\n<pre><code>if ($(selector).length)\n</code></pre>\n\n<p>You don't need that <code>&gt;0</code> part.</p>\n",
"source": "so",
"questionId": 31044
},
{
"title": "How can I know which radio button is selected via jQuery?",
"body": "<p>To get the value of the <strong>selected</strong> <code>radioName</code> item of a form with id <code>myForm</code>:</p>\n\n<pre><code>$('input[name=radioName]:checked', '#myForm').val()\n</code></pre>\n\n<p>Here's an example:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"false\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>$('#myForm input').on('change', function() {\r\n alert($('input[name=radioName]:checked', '#myForm').val()); \r\n});</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;script src=\"https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js\"&gt;&lt;/script&gt;\r\n&lt;form id=\"myForm\"&gt;\r\n&lt;input type=\"radio\" name=\"radioName\" value=\"1\" /&gt; 1 &lt;br /&gt;\r\n&lt;input type=\"radio\" name=\"radioName\" value=\"2\" /&gt; 2 &lt;br /&gt;\r\n&lt;input type=\"radio\" name=\"radioName\" value=\"3\" /&gt; 3 &lt;br /&gt;\r\n&lt;/form&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"source": "so",
"questionId": 596351
},
{
"title": "JavaScript closure inside loops – simple practical example",
"body": "<p>Well, the problem is that the variable <code>i</code>, within each of your anonymous functions, is bound to the same variable outside of the function.</p>\n\n<p>What you want to do is bind the variable within each function to a separate, unchanging value outside of the function:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>var funcs = [];\r\n\r\nfunction createfunc(i) {\r\n return function() { console.log(\"My value: \" + i); };\r\n}\r\n\r\nfor (var i = 0; i &lt; 3; i++) {\r\n funcs[i] = createfunc(i);\r\n}\r\n\r\nfor (var j = 0; j &lt; 3; j++) {\r\n funcs[j](); // and now let's run each one to see\r\n}</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>Since there is no block scope in JavaScript - only function scope - by wrapping the function creation in a new function, you ensure that the value of \"i\" remains as you intended.</p>\n\n<hr>\n\n<p><strong>Update:</strong> with the relatively widespread availability of the <code>Array.prototype.forEach</code> function (in 2015), it's worth noting that in those situations involving iteration primarily over an array of values, <code>.forEach()</code> provides a clean, natural way to get a distinct closure for every iteration. That is, assuming you've got some sort of array containing values (DOM references, objects, whatever), and the problem arises of setting up callbacks specific to each element, you can do this:</p>\n\n<pre><code>var someArray = [ /* whatever */ ];\n// ...\nsomeArray.forEach(function(arrayElement) {\n // ... code code code for this one element\n someAsynchronousFunction(arrayElement, function() {\n arrayElement.doSomething();\n });\n});\n</code></pre>\n\n<p>The idea is that each invocation of the callback function used with the <code>.forEach</code> loop will be its own closure. The parameter passed in to that handler is the array element specific to that particular step of the iteration. If it's used in an asynchronous callback, it won't collide with any of the other callbacks established at other steps of the iteration.</p>\n\n<p>If you happen to be working in jQuery, the <code>$.each()</code> function gives you a similar capability.</p>\n\n<p><strong>Update 2:</strong>\nECMAScript 6 (ES6), the newest version of JavaScript, is now starting to be implemented in many evergreen browsers and backend systems. There are also transpilers like <a href=\"http://babeljs.io/\" rel=\"noreferrer\">Babel</a> that will convert ES6 to ES5 to allow usage of new features on older systems.</p>\n\n<p>ES6 introduces new <code>let</code> and <code>const</code> keywords that are scoped differently than <code>var</code>-based variables. For example, in a loop with a <code>let</code>-based index, each iteration through the loop will have a new value of <code>i</code> where each value is scoped inside the loop, so your code would work as you expect. There are many resources, but I'd recommend <a href=\"http://www.2ality.com/2015/02/es6-scoping.html\" rel=\"noreferrer\">2ality's block-scoping post</a> as a great source of information.</p>\n\n<pre><code>for (let i = 0; i &lt; 3; i++) {\n funcs[i] = function() {\n console.log(\"My value: \" + i);\n };\n}\n</code></pre>\n\n<p>Beware, though, that IE9-IE11 and Edge prior to Edge 14 support <code>let</code> but get the above wrong (they don't create a new <code>i</code> each time, so all the functions above would log 3 like they would if we used <code>var</code>). Edge 14 finally gets it right.</p>\n",
"source": "so",
"questionId": 750486
},
{
"title": "Change an element&#39;s class with JavaScript",
"body": "<h2>Modern HTML5 Techniques for changing classes</h2>\n\n<p>Modern browsers have added <a href=\"https://developer.mozilla.org/en-US/docs/DOM/element.classList\" rel=\"noreferrer\"><strong>classList</strong></a> which provides methods to make it easier to manipulate classes without needing a library:</p>\n\n<pre><code>document.getElementById(\"MyElement\").classList.add('MyClass');\n\ndocument.getElementById(\"MyElement\").classList.remove('MyClass');\n\nif ( document.getElementById(\"MyElement\").classList.contains('MyClass') )\n\ndocument.getElementById(\"MyElement\").classList.toggle('MyClass');\n</code></pre>\n\n<p>Unfortunately, these do not work in Internet Explorer prior to v10, though there is a <a href=\"http://en.wikipedia.org/wiki/Shim_(computing)\" rel=\"noreferrer\">shim</a> to add support for it to IE8 and IE9, available from <a href=\"https://developer.mozilla.org/en-US/docs/DOM/element.classList\" rel=\"noreferrer\">this page</a>. It is, though, getting more and more <a href=\"http://caniuse.com/#feat=classlist\" rel=\"noreferrer\">supported</a>.</p>\n\n<h2>Simple cross-browser solution</h2>\n\n<p>The standard JavaScript way to select an element is using <a href=\"https://developer.mozilla.org/en-US/docs/DOM/document.getElementById\" rel=\"noreferrer\"><code>document.getElementById(\"Id\")</code></a>, which is what the following examples use - you can of course obtain elements in other ways, and in the right situation may simply use <code>this</code> instead - however, going into detail on this is beyond the scope of the answer.</p>\n\n<h3>To change all classes for an element:</h3>\n\n<p>To replace all existing classes with one or more new classes, set the className attribute:</p>\n\n<pre><code>document.getElementById(\"MyElement\").className = \"MyClass\";\n</code></pre>\n\n<p>(You can use a space-delimited list to apply multiple classes.)</p>\n\n<h3>To add an additional class to an element:</h3>\n\n<p>To add a class to an element, without removing/affecting existing values, append a space and the new classname, like so:</p>\n\n<pre><code>document.getElementById(\"MyElement\").className += \" MyClass\";\n</code></pre>\n\n<h3>To remove a class from an element:</h3>\n\n<p>To remove a single class to an element, without affecting other potential classes, a simple regex replace is required:</p>\n\n<pre><code>document.getElementById(\"MyElement\").className =\n document.getElementById(\"MyElement\").className.replace\n ( /(?:^|\\s)MyClass(?!\\S)/g , '' )\n/* Code wrapped for readability - above is all one statement */\n</code></pre>\n\n<p>An explanation of this regex is as follows:</p>\n\n<pre><code>(?:^|\\s) # Match the start of the string, or any single whitespace character\n\nMyClass # The literal text for the classname to remove\n\n(?!\\S) # Negative lookahead to verify the above is the whole classname\n # Ensures there is no non-space character following\n # (i.e. must be end of string or a space)\n</code></pre>\n\n<p>The <code>g</code> flag tells the replace to repeat as required, in case the class name has been added multiple times.</p>\n\n<h3>To check if a class is already applied to an element:</h3>\n\n<p>The same regex used above for removing a class can also be used as a check as to whether a particular class exists:</p>\n\n<pre><code>if ( document.getElementById(\"MyElement\").className.match(/(?:^|\\s)MyClass(?!\\S)/) )\n</code></pre>\n\n<p><br/></p>\n\n<h3>Assigning these actions to onclick events:</h3>\n\n<p>Whilst it is possible to write JavaScript directly inside the HTML event attributes (such as <code>onclick=\"this.className+=' MyClass'\"</code>) this is not recommended behaviour. Especially on larger applications, more maintainable code is achieved by separating HTML markup from JavaScript interaction logic.</p>\n\n<p>The first step to achieving this is by creating a function, and calling the function in the onclick attribute, for example:</p>\n\n<pre><code>&lt;script type=\"text/javascript\"&gt;\n function changeClass(){\n // Code examples from above\n }\n&lt;/script&gt;\n...\n&lt;button onclick=\"changeClass()\"&gt;My Button&lt;/button&gt;\n</code></pre>\n\n<p><sub><em>(It is not required to have this code in script tags, this is simply for brevity of example, and including the JavaScript in a distinct file may be more appropriate.)</em></sub></p>\n\n<p>The second step is to move the onclick event out of the HTML and into JavaScript, for example using <a href=\"https://developer.mozilla.org/en-US/docs/DOM/element.addEventListener\" rel=\"noreferrer\">addEventListener</a></p>\n\n<pre><code>&lt;script type=\"text/javascript\"&gt;\n function changeClass(){\n // Code examples from above\n }\n\n window.onload = function(){\n document.getElementById(\"MyElement\").addEventListener( 'click', changeClass);\n }\n&lt;/script&gt;\n...\n&lt;button id=\"MyElement\"&gt;My Button&lt;/button&gt;\n</code></pre>\n\n<p>(Note that the window.onload part is required so that the contents of that function are executed <em>after</em> the HTML has finished loading - without this, the MyElement might not exist when the JavaScript code is called, so that line would fail.)</p>\n\n<p><br/></p>\n\n<h2>JavaScript Frameworks and Libraries</h2>\n\n<p>The above code is all in standard JavaScript, however it is common practise to use either a framework or a library to simplify common tasks, as well as benefit from fixed bugs and edge cases that you might not think of when writing your code.</p>\n\n<p>Whilst some people consider it overkill to add a ~50&nbsp;KB framework for simply changing a class, if you are doing any substantial amount of JavaScript work, or anything that might have unusual cross-browser behaviour, it is well worth considering.</p>\n\n<p><em>(Very roughly, a library is a set of tools designed for a specific task, whilst a framework generally contains multiple libraries and performs a complete set of duties.)</em></p>\n\n<p>The examples above have been reproduced below using <a href=\"http://jquery.com\" rel=\"noreferrer\">jQuery</a>, probably the most commonly used JavaScript library (though there are others worth investigating too).</p>\n\n<p>(Note that <code>$</code> here is the jQuery object.)</p>\n\n<h3>Changing Classes with jQuery:</h3>\n\n<pre><code>$('#MyElement').addClass('MyClass');\n\n$('#MyElement').removeClass('MyClass');\n\nif ( $('#MyElement').hasClass('MyClass') )\n</code></pre>\n\n<p>In addition, jQuery provides a shortcut for adding a class if it doesn't apply, or removing a class that does:</p>\n\n<pre><code>$('#MyElement').toggleClass('MyClass');\n</code></pre>\n\n<p><br/></p>\n\n<h3>Assigning a function to a click event with jQuery:</h3>\n\n<pre><code>$('#MyElement').click(changeClass);\n</code></pre>\n\n<p>or, without needing an id:</p>\n\n<pre><code>$(':button:contains(My Button)').click(changeClass);\n</code></pre>\n\n<p><br/></p>\n",
"source": "so",
"questionId": 195951
},
{
"title": "How do I empty an array in JavaScript?",
"body": "<p>Ways to clear an existing array <code>A</code>:</p>\n\n<p><strong>Method 1</strong></p>\n\n<p>(this was my original answer to the question)</p>\n\n<pre><code>A = [];\n</code></pre>\n\n<p>This code will set the variable <code>A</code> to a new empty array. This is perfect if you don't have <strong>references to the original array <code>A</code></strong> anywhere else because this actually creates a brand new (empty) array. You should be careful with this method because if you have referenced this array from another variable or property, the original array will remain unchanged. Only use this if you only reference the array by its original variable <code>A</code>.</p>\n\n<p>This is also the fastest solution.</p>\n\n<p>This code sample shows the issue you can encounter when using this method:</p>\n\n<pre><code>var arr1 = ['a','b','c','d','e','f'];\nvar arr2 = arr1; // Reference arr1 by another variable \narr1 = [];\nconsole.log(arr2); // Output ['a','b','c','d','e','f']\n</code></pre>\n\n<p><strong>Method 2</strong> (as <a href=\"https://stackoverflow.com/a/1234337/113570\">suggested</a> by <a href=\"https://stackoverflow.com/users/2214/matthew-crumley\">Matthew Crumley</a>)</p>\n\n<pre><code>A.length = 0\n</code></pre>\n\n<p>This will clear the existing array by setting its length to 0. Some have argued that this may not work in all implementations of JavaScript, but it turns out that this is not the case. It also works when using \"strict mode\" in ECMAScript 5 because the length property of an array is a read/write property.</p>\n\n<p><strong>Method 3</strong> (as <a href=\"https://stackoverflow.com/a/8134354/113570\">suggested</a> by <a href=\"https://stackoverflow.com/users/1047275/anthony\">Anthony</a>)</p>\n\n<pre><code>A.splice(0,A.length)\n</code></pre>\n\n<p>Using <code>.splice()</code> will work perfectly, but since the <code>.splice()</code> function will return an array with all the removed items, it will actually return a copy of the original array. Benchmarks suggest that this has no effect on performance whatsoever.</p>\n\n<p><strong>Method 4</strong> (as <a href=\"https://stackoverflow.com/a/17306971/113570\">suggested</a> by <a href=\"https://stackoverflow.com/users/990356/tanguy-k\">tanguy_k</a>)</p>\n\n<pre><code>while(A.length &gt; 0) {\n A.pop();\n}\n</code></pre>\n\n<p>This solution is not very succinct, and it is also the slowest solution, contrary to earlier benchmarks referenced in the original answer.</p>\n\n<p><strong>Performance</strong></p>\n\n<p>Of all the methods of clearing an <strong><em>existing array</em></strong>, methods 2 and 3 are very similar in performance and are a lot faster than method 4. See this <a href=\"http://jsben.ch/#/hyj65\" rel=\"noreferrer\">benchmark</a>.</p>\n\n<p>As pointed out by <a href=\"https://stackoverflow.com/users/47401/diadistis\">Diadistis</a> in their <a href=\"https://stackoverflow.com/a/28548360/113570\">answer</a> below, the original benchmarks that were used to determine the performance of the four methods described above were flawed. The original benchmark reused the cleared array so the second iteration was clearing an array that was already empty.</p>\n\n<p>The following benchmark fixes this flaw: <a href=\"http://jsben.ch/#/hyj65\" rel=\"noreferrer\">http://jsben.ch/#/hyj65</a>. It clearly shows that methods #2 (length property) and #3 (splice) are the fastest (not counting method #1 which doesn't change the original array).</p>\n\n<hr/>\n\n<p>This has been a hot topic and the cause of a lot of controversy. There are actually many correct answers and because this answer has been marked as the accepted answer for a very long time, I will include all of the methods here. If you vote for this answer, please upvote the other answers that I have referenced as well.</p>\n",
"source": "so",
"questionId": 1232040
},
{
"title": "Can (a== 1 &amp;&amp; a ==2 &amp;&amp; a==3) ever evaluate to true?",
"body": "<p>If you take advantage of <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Equality_comparisons_and_sameness#Loose_equality_using\" rel=\"noreferrer\">how <code>==</code> works</a>, you could simply create an object with a custom <code>toString</code> (or <code>valueOf</code>) function that changes what it returns each time it is used such that it satisfies all three conditions.</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const a = {\r\n i: 1,\r\n toString: function () {\r\n return a.i++;\r\n }\r\n}\r\n\r\nif(a == 1 &amp;&amp; a == 2 &amp;&amp; a == 3) {\r\n console.log('Hello World!');\r\n}</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<hr>\n\n<p>The reason this works is due to the use of the loose equality operator. When using loose equality, if one of the operands is of a different type than the other, the engine will attempt to convert one to the other. In the case of an object on the left and a number on the right, it will attempt to convert the object to a number by first calling <code>valueOf</code> if it is callable, and failing that, it will call <code>toString</code>. I used <code>toString</code> in this case simply because it's what came to mind, <code>valueOf</code> would make more sense. If I instead returned a string from <code>toString</code>, the engine would have then attempted to convert the string to a number giving us the same end result, though with a slightly longer path.</p>\n",
"source": "so",
"questionId": 48270127
},
{
"title": "What is the !! (not not) operator in JavaScript?",
"body": "<p>Coerces <code>oObject</code> to boolean. If it was falsey (e.g. 0, <code>null</code>, <code>undefined</code>, etc.), it will be <code>false</code>, otherwise, <code>true</code>.</p>\n\n<pre><code>!oObject //Inverted boolean\n!!oObject //Non inverted boolean so true boolean representation\n</code></pre>\n\n<p>So <code>!!</code> is not an operator, it's just the <code>!</code> operator twice.</p>\n\n<p>Real World Example \"Test IE version\": </p>\n\n<pre><code>let isIE8 = false; \nisIE8 = !! navigator.userAgent.match(/MSIE 8.0/); \nconsole.log(isIE8); // returns true or false \n</code></pre>\n\n<p>If you ⇒</p>\n\n<pre><code>console.log(navigator.userAgent.match(/MSIE 8.0/)); \n// returns null \n</code></pre>\n\n<p>but if you ⇒</p>\n\n<pre><code>console.log(!!navigator.userAgent.match(/MSIE 8.0/)); \n// returns true or false\n</code></pre>\n",
"source": "so",
"questionId": 784929
},
{
"title": "Checking if a key exists in a JavaScript object?",
"body": "<p>Checking for undefined-ness is not an accurate way of testing whether a key exists. What if the key exists but the value is actually <code>undefined</code>?</p>\n\n<pre><code>var obj = { key: undefined };\nobj[\"key\"] != undefined // false, but the key exists!\n</code></pre>\n\n<p>You should instead use the <code>in</code> operator:</p>\n\n<pre><code>\"key\" in obj // true, regardless of the actual value\n</code></pre>\n\n<p>If you want to check if a key doesn't exist, remember to use parenthesis:</p>\n\n<pre><code>!(\"key\" in obj) // true if \"key\" doesn't exist in object\n!\"key\" in obj // ERROR! Equivalent to \"false in obj\"\n</code></pre>\n\n<p>Or, if you want to particularly test for properties of the object instance (and not inherited properties), use <code>hasOwnProperty</code>:</p>\n\n<pre><code>obj.hasOwnProperty(\"key\") // true\n</code></pre>\n\n<p>For performance comparison between the methods that are <code>in</code>, <code>hasOwnProperty</code> and key is <code>undefined</code>, see this <a href=\"http://jsben.ch/#/WqlIl\" rel=\"noreferrer\"><strong>benchmark</strong></a></p>\n",
"source": "so",
"questionId": 1098040
},
{
"title": "Validate decimal numbers in JavaScript - IsNumeric()",
"body": "<p><a href=\"https://stackoverflow.com/questions/18082/validate-numbers-in-javascript-isnumeric/174921#174921\">@Joel's answer</a> is pretty close, but it will fail in the following cases:</p>\n\n<pre><code>// Whitespace strings:\nIsNumeric(' ') == true;\nIsNumeric('\\t\\t') == true;\nIsNumeric('\\n\\r') == true;\n\n// Number literals:\nIsNumeric(-1) == false;\nIsNumeric(0) == false;\nIsNumeric(1.1) == false;\nIsNumeric(8e5) == false;\n</code></pre>\n\n<p>Some time ago I had to implement an <code>IsNumeric</code> function, to find out if a variable contained a numeric value, <strong>regardless of its type</strong>, it could be a <code>String</code> containing a numeric value (I had to consider also exponential notation, etc.), a <code>Number</code> object, virtually anything could be passed to that function, I couldn't make any type assumptions, taking care of type coercion (eg. <code>+true == 1;</code> but <code>true</code> shouldn't be considered as <code>\"numeric\"</code>).</p>\n\n<p>I think is worth sharing this set of <a href=\"http://run.plnkr.co/plunks/93FPpacuIcXqqKMecLdk/\" rel=\"noreferrer\"><strong>+30 unit tests</strong></a> (<a href=\"http://dl.getdropbox.com/u/35146/js/tests/isNumber.html\" rel=\"noreferrer\">old link</a>) made to numerous function implementations, and also share the one that passes all my tests:</p>\n\n<pre><code>function isNumeric(n) {\n return !isNaN(parseFloat(n)) &amp;&amp; isFinite(n);\n}\n</code></pre>\n\n<p><strong>P.S.</strong> <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/isNaN\" rel=\"noreferrer\">isNaN</a> &amp; <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/isFinite\" rel=\"noreferrer\">isFinite</a> have a confusing behavior due to forced conversion to number. In ES6, <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN\" rel=\"noreferrer\">Number.isNaN</a> &amp; <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isFinite\" rel=\"noreferrer\">Number.isFinite</a> would fix these issues. Keep that in mind when using them. </p>\n\n<hr>\n\n<p><strong>Update</strong> : \n<a href=\"https://github.com/jquery/jquery/blob/2.2-stable/src/core.js#L215\" rel=\"noreferrer\">Here's how jQuery does it now (2.2-stable)</a> : </p>\n\n<pre><code>isNumeric: function( obj ) {\n var realStringObj = obj &amp;&amp; obj.toString();\n return !jQuery.isArray( obj ) &amp;&amp; ( realStringObj - parseFloat( realStringObj ) + 1 ) &gt;= 0;\n}\n</code></pre>\n\n<p><strong>Update</strong> :\n<a href=\"https://github.com/angular/angular/blob/4.3.x/packages/common/src/pipes/number_pipe.ts#L172\" rel=\"noreferrer\">Angular 4.3</a> :</p>\n\n<pre><code>export function isNumeric(value: any): boolean {\n return !isNaN(value - parseFloat(value));\n}\n</code></pre>\n",
"source": "so",
"questionId": 18082
},
{
"title": "Encode URL in JavaScript?",
"body": "<p>Check out the built-in function <code>encodeURIComponent(str)</code> and <code>encodeURI(str)</code>.<br>\nIn your case, this should work:</p>\n\n<pre><code>var myOtherUrl = \n \"http://example.com/index.html?url=\" + encodeURIComponent(myUrl);\n</code></pre>\n",
"source": "so",
"questionId": 332872
},
{
"title": "How do you check for an empty string in JavaScript?",
"body": "<p>If you just want to check whether there's any value, you can do </p>\n\n<pre><code>if (strValue) {\n //do something\n}\n</code></pre>\n\n<p>If you need to check specifically for an empty string over null, I would think checking against <code>\"\"</code> is your best bet, using <a href=\"http://www.webreference.com/js/column26/stricteq.html\" rel=\"noreferrer\">the <code>===</code> operator</a> (so that you know that it is, in fact, a string you're comparing against).</p>\n",
"source": "so",
"questionId": 154059
},
{
"title": "Check if object is array?",
"body": "<p>I would first check if your implementation supports <code>isArray</code>:</p>\n\n<pre><code>if (Array.isArray)\n return Array.isArray(v);\n</code></pre>\n\n<p>You could also try using the <code>instanceof</code> operator</p>\n\n<pre><code>v instanceof Array\n</code></pre>\n",
"source": "so",
"questionId": 4775722
},
{
"title": "How to get the children of the $(this) selector?",
"body": "<p>The jQuery constructor accepts a 2nd parameter called <a href=\"http://api.jquery.com/jQuery/#jQuery-selector-context\" rel=\"noreferrer\"><code>context</code></a> which can be used to override the context of the selection. </p>\n\n<pre><code>jQuery(\"img\", this);\n</code></pre>\n\n<p>Which is the same as using <a href=\"http://api.jquery.com/find\" rel=\"noreferrer\"><code>.find()</code></a> like this:</p>\n\n<pre><code>jQuery(this).find(\"img\");\n</code></pre>\n\n<p>If the imgs you desire are <strong>only</strong> direct descendants of the clicked element, you can also use <a href=\"http://api.jquery.com/children\" rel=\"noreferrer\"><code>.children()</code></a>:</p>\n\n<pre><code>jQuery(this).children(\"img\");\n</code></pre>\n",
"source": "so",
"questionId": 306583
},
{
"title": ".prop() vs .attr()",
"body": "<p><strong>Update 1 November 2012</strong></p>\n\n<p>My original answer applies specifically to jQuery 1.6. My advice remains the same but jQuery 1.6.1 changed things slightly: in the face of the predicted pile of broken websites, the jQuery team <a href=\"http://blog.jquery.com/2011/05/12/jquery-1-6-1-released/\" rel=\"noreferrer\">reverted <code>attr()</code> to something close to (but not exactly the same as) its old behaviour for Boolean attributes</a>. John Resig also <a href=\"http://ejohn.org/blog/jquery-16-and-attr/\" rel=\"noreferrer\">blogged about it</a>. I can see the difficulty they were in but still disagree with the recommendation to prefer <code>attr()</code>.</p>\n\n<p><strong>Original answer</strong></p>\n\n<p>If you've only ever used jQuery and not the DOM directly, this could be a confusing change, although it is definitely an improvement conceptually. Not so good for the bazillions of sites using jQuery that will break as a result of this change though.</p>\n\n<p>I'll summarize the main issues:</p>\n\n<ul>\n<li>You usually want <code>prop()</code> rather than <code>attr()</code>.</li>\n<li>In the majority of cases, <code>prop()</code> does what <code>attr()</code> used to do. Replacing calls to <code>attr()</code> with <code>prop()</code> in your code will generally work.</li>\n<li>Properties are generally simpler to deal with than attributes. An attribute value may only be a string whereas a property can be of any type. For example, the <code>checked</code> property is a Boolean, the <code>style</code> property is an object with individual properties for each style, the <code>size</code> property is a number.</li>\n<li>Where both a property and an attribute with the same name exists, usually updating one will update the other, but this is not the case for certain attributes of inputs, such as <code>value</code> and <code>checked</code>: for these attributes, the property always represents the current state while the attribute (except in old versions of IE) corresponds to the default value/checkedness of the input (reflected in the <code>defaultValue</code> / <code>defaultChecked</code> property).</li>\n<li>This change removes some of the layer of magic jQuery stuck in front of attributes and properties, meaning jQuery developers will have to learn a bit about the difference between properties and attributes. This is a good thing.</li>\n</ul>\n\n<p>If you're a jQuery developer and are confused by this whole business about properties and attributes, you need to take a step back and learn a little about it, since jQuery is no longer trying so hard to shield you from this stuff. For the authoritative but somewhat dry word on the subject, there's the specs: <a href=\"http://www.w3.org/TR/dom/\" rel=\"noreferrer\">DOM4</a>, <a href=\"http://www.w3.org/TR/DOM-Level-2-HTML/\" rel=\"noreferrer\">HTML DOM</a>, <a href=\"http://www.w3.org/TR/DOM-Level-2-Core\" rel=\"noreferrer\">DOM Level 2</a>, <a href=\"http://www.w3.org/TR/DOM-Level-3-Core/\" rel=\"noreferrer\">DOM Level 3</a>. Mozilla's DOM documentation is valid for most modern browsers and is easier to read than the specs, so you may find their <a href=\"https://developer.mozilla.org/en/gecko_dom_reference\" rel=\"noreferrer\">DOM reference</a> helpful. There's a <a href=\"https://developer.mozilla.org/en/DOM/element#Properties\" rel=\"noreferrer\">section on element properties</a>.</p>\n\n<p>As an example of how properties are simpler to deal with than attributes, consider a checkbox that is initially checked. Here are two possible pieces of valid HTML to do this:</p>\n\n<pre><code>&lt;input id=\"cb\" type=\"checkbox\" checked&gt;\n&lt;input id=\"cb\" type=\"checkbox\" checked=\"checked\"&gt;\n</code></pre>\n\n<p>So, how do you find out if the checkbox is checked with jQuery? Look on Stack Overflow and you'll commonly find the following suggestions:</p>\n\n<ul>\n<li><code>if ( $(\"#cb\").attr(\"checked\") === true ) {...}</code></li>\n<li><code>if ( $(\"#cb\").attr(\"checked\") == \"checked\" ) {...}</code></li>\n<li><code>if ( $(\"#cb\").is(\":checked\") ) {...}</code></li>\n</ul>\n\n<p>This is actually the simplest thing in the world to do with the <code>checked</code> Boolean property, which has existed and worked flawlessly in every major scriptable browser since 1995:</p>\n\n<p><code>if (document.getElementById(\"cb\").checked) {...}</code></p>\n\n<p>The property also makes checking or unchecking the checkbox trivial:</p>\n\n<p><code>document.getElementById(\"cb\").checked = false</code></p>\n\n<p>In jQuery 1.6, this unambiguously becomes</p>\n\n<p><code>$(\"#cb\").prop(\"checked\", false)</code></p>\n\n<p>The idea of using the <code>checked</code> attribute for scripting a checkbox is unhelpful and unnecessary. The property is what you need.</p>\n\n<ul>\n<li>It's not obvious what the correct way to check or uncheck the checkbox is using the <code>checked</code> attribute</li>\n<li>The attribute value reflects the default rather than the current visible state (except in some older versions of IE, thus making things still harder). The attribute tells you nothing about the whether the checkbox on the page is checked. See <a href=\"http://jsfiddle.net/VktA6/49/\" rel=\"noreferrer\">http://jsfiddle.net/VktA6/49/</a>.</li>\n</ul>\n",
"source": "so",
"questionId": 5874652
},
{
"title": "How do I loop through or enumerate a JavaScript object?",
"body": "<p>You can use the <code>for-in</code> loop as shown by others. However, you also have to make sure that the key you get is an actual property of an object, and doesn't come from the prototype.</p>\n\n<p><strong>Here is the snippet:</strong>\n<div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>var p = {\r\n \"p1\": \"value1\",\r\n \"p2\": \"value2\",\r\n \"p3\": \"value3\"\r\n};\r\n\r\nfor (var key in p) {\r\n if (p.hasOwnProperty(key)) {\r\n console.log(key + \" -&gt; \" + p[key]);\r\n }\r\n}</code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"source": "so",
"questionId": 684672
},
{
"title": "Add table row in jQuery",
"body": "<p>The approach you suggest is not guaranteed to give you the result you're looking for - what if you had a <code>tbody</code> for example:</p>\n\n<pre><code>&lt;table id=\"myTable\"&gt;\n &lt;tbody&gt;\n &lt;tr&gt;...&lt;/tr&gt;\n &lt;tr&gt;...&lt;/tr&gt;\n &lt;/tbody&gt;\n&lt;/table&gt;\n</code></pre>\n\n<p>You would end up with the following:</p>\n\n<pre><code>&lt;table id=\"myTable\"&gt;\n &lt;tbody&gt;\n &lt;tr&gt;...&lt;/tr&gt;\n &lt;tr&gt;...&lt;/tr&gt;\n &lt;/tbody&gt;\n &lt;tr&gt;...&lt;/tr&gt;\n&lt;/table&gt;\n</code></pre>\n\n<p>I would therefore recommend this approach instead:</p>\n\n<pre><code>$('#myTable tr:last').after('&lt;tr&gt;...&lt;/tr&gt;&lt;tr&gt;...&lt;/tr&gt;');\n</code></pre>\n\n<p>You can include anything within the <code>after()</code> method as long as it's valid HTML, including multiple rows as per the example above.</p>\n\n<p><strong>Update:</strong> Revisiting this answer following recent activity with this question. eyelidlessness makes a good comment that there will always be a <code>tbody</code> in the DOM; this is true, but only if there is at least one row. If you have no rows, there will be no <code>tbody</code> unless you have specified one yourself.</p>\n\n<p>DaRKoN_ <a href=\"https://stackoverflow.com/questions/171027/jquery-add-table-row/468240#468240\">suggests</a> appending to the <code>tbody</code> rather than adding content after the last <code>tr</code>. This gets around the issue of having no rows, but still isn't bulletproof as you could theoretically have multiple <code>tbody</code> elements and the row would get added to each of them.</p>\n\n<p>Weighing everything up, I'm not sure there is a single one-line solution that accounts for every single possible scenario. You will need to make sure the jQuery code tallies with your markup.</p>\n\n<p>I think the safest solution is probably to ensure your <code>table</code> always includes at least one <code>tbody</code> in your markup, even if it has no rows. On this basis, you can use the following which will work however many rows you have (and also account for multiple <code>tbody</code> elements):</p>\n\n<pre><code>$('#myTable &gt; tbody:last-child').append('&lt;tr&gt;...&lt;/tr&gt;&lt;tr&gt;...&lt;/tr&gt;');\n</code></pre>\n",
"source": "so",
"questionId": 171027
},
{
"title": "Storing Objects in HTML5 localStorage",
"body": "<p>Looking at the <a href=\"http://developer.apple.com/safari/library/documentation/iPhone/Conceptual/SafariJSDatabaseGuide/Name-ValueStorage/Name-ValueStorage.html#//apple_ref/doc/uid/TP40007256-CH6-SW1\" rel=\"noreferrer\">Apple</a>, <a href=\"https://developer.mozilla.org/en/DOM/Storage\" rel=\"noreferrer\">Mozilla</a> and <a href=\"http://msdn.microsoft.com/en-us/library/cc197050(VS.85).aspx\" rel=\"noreferrer\">Microsoft</a> documentation, the functionality seems to be limited to handle only string key/value pairs.</p>\n\n<p>A workaround can be to <a href=\"http://www.json.org/js.html\" rel=\"noreferrer\"><em>stringify</em></a> your object before storing it, and later parse it when you retrieve it:</p>\n\n<pre><code>var testObject = { 'one': 1, 'two': 2, 'three': 3 };\n\n// Put the object into storage\nlocalStorage.setItem('testObject', JSON.stringify(testObject));\n\n// Retrieve the object from storage\nvar retrievedObject = localStorage.getItem('testObject');\n\nconsole.log('retrievedObject: ', JSON.parse(retrievedObject));\n</code></pre>\n",
"source": "so",
"questionId": 2010892
},
{
"title": "How can I refresh a page with jQuery?",
"body": "<p>Use <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Location/reload\" rel=\"noreferrer\"><code>location.reload()</code></a>:</p>\n\n<pre><code>$('#something').click(function() {\n location.reload();\n});\n</code></pre>\n\n<p>The <code>reload()</code> function takes an optional parameter that can be set to <code>true</code> to force a reload from the server rather than the cache. The parameter defaults to <code>false</code>, so by default the page may reload from the browser's cache.</p>\n",
"source": "so",
"questionId": 5404839
},
{
"title": "How to insert an item into an array at a specific index?",
"body": "<p>What you want is the <strong><a href=\"https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/splice\" rel=\"noreferrer\"><code>splice</code></a></strong> function on the native array object.</p>\n\n<p><code>arr.splice(index, 0, item);</code> will insert <code>item</code> into <code>arr</code> at the specified index (deleting <code>0</code> items first, that is, it's just an insert).</p>\n\n<p>In this example we will create an array and add an element to it into index 2:</p>\n\n<pre><code>var arr = [];\narr[0] = \"Jani\";\narr[1] = \"Hege\";\narr[2] = \"Stale\";\narr[3] = \"Kai Jim\";\narr[4] = \"Borge\";\n\nconsole.log(arr.join());\narr.splice(2, 0, \"Lene\");\nconsole.log(arr.join());\n</code></pre>\n\n<p>The output of the code above will be:</p>\n\n<pre><code>Jani,Hege,Stale,Kai Jim,Borge\nJani,Hege,Lene,Stale,Kai Jim,Borge\n</code></pre>\n",
"source": "so",
"questionId": 586182
},
{
"title": "How do I detect a click outside an element?",
"body": "<blockquote>\n <p>NOTE: Using <code>stopEventPropagation()</code> is something that should be avoided as it breaks normal event flow in the DOM. See <a href=\"https://css-tricks.com/dangers-stopping-event-propagation/\" rel=\"noreferrer\">this article</a> for more information. Consider using <a href=\"https://stackoverflow.com/a/3028037/561309\">this method</a> instead.</p>\n</blockquote>\n\n<p>Attach a click event to the document body which closes the window. Attach a separate click event to the window which stops propagation to the document body.</p>\n\n<pre><code>$(window).click(function() {\n//Hide the menus if visible\n});\n\n$('#menucontainer').click(function(event){\n event.stopPropagation();\n});\n</code></pre>\n",
"source": "so",
"questionId": 152975
},
{
"title": "Set a default parameter value for a JavaScript function",
"body": "<p>From ES6/ES2015, default parameters is in the language specification.</p>\n\n<pre><code>function read_file(file, delete_after = false) {\n // Code\n}\n</code></pre>\n\n<p>just works.</p>\n\n<p>Reference: <a href=\"https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions/default_parameters\" rel=\"noreferrer\">Default Parameters - MDN</a></p>\n\n<blockquote>\n <p>Default function parameters allow formal parameters to be initialized with default values if <strong>no value</strong> or <strong>undefined</strong> is passed.</p>\n</blockquote>\n\n<p>You can also <a href=\"http://exploringjs.com/es6/ch_parameter-handling.html#sec_named-parameters\" rel=\"noreferrer\">simulate default <em>named</em> parameters via destructuring</a>:</p>\n\n<pre><code>// the `= {}` below lets you call the function without any parameters\nfunction myFor({ start = 5, end = 1, step = -1 } = {}) { // (A)\n // Use the variables `start`, `end` and `step` here\n ···\n}\n</code></pre>\n\n<p><strong>Pre ES2015</strong>,</p>\n\n<p>There are a lot of ways, but this is my preferred method - it lets you pass in anything you want, including false or null. (<code>typeof null == \"object\"</code>)</p>\n\n<pre><code>function foo(a, b) {\n a = typeof a !== 'undefined' ? a : 42;\n b = typeof b !== 'undefined' ? b : 'default_b';\n ...\n}\n</code></pre>\n",
"source": "so",
"questionId": 894860
},
{
"title": "Get selected text from a drop-down list (select box) using jQuery",
"body": "<pre><code>$(\"#yourdropdownid option:selected\").text();\n</code></pre>\n",
"source": "so",
"questionId": 1643227
},
{
"title": "Disable/enable an input with jQuery?",
"body": "<h2>jQuery 1.6+</h2>\n\n<p>To change the <code>disabled</code> property you should use the <a href=\"http://api.jquery.com/prop\" rel=\"noreferrer\"><code>.prop()</code></a> function.</p>\n\n<pre><code>$(\"input\").prop('disabled', true);\n$(\"input\").prop('disabled', false);\n</code></pre>\n\n<h2>jQuery 1.5 and below</h2>\n\n<p>The <code>.prop()</code> function doesn't exist, but <a href=\"http://api.jquery.com/attr\" rel=\"noreferrer\"><code>.attr()</code></a> does similar:</p>\n\n<p>Set the disabled attribute.</p>\n\n<pre><code>$(\"input\").attr('disabled','disabled');\n</code></pre>\n\n<p>To enable again, the proper method is to use <a href=\"//api.jquery.com/removeAttr\" rel=\"noreferrer\"><code>.removeAttr()</code></a></p>\n\n<pre><code>$(\"input\").removeAttr('disabled');\n</code></pre>\n\n<h2>In any version of jQuery</h2>\n\n<p>You can always rely on the actual DOM object and is probably a little faster than the other two options if you are only dealing with one element:</p>\n\n<pre><code>// assuming an event handler thus 'this'\nthis.disabled = true;\n</code></pre>\n\n<p>The advantage to using the <code>.prop()</code> or <code>.attr()</code> methods is that you can set the property for a bunch of selected items.</p>\n\n<hr>\n\n<p><strong>Note:</strong> In 1.6 there is a <a href=\"//api.jquery.com/removeProp\" rel=\"noreferrer\"><code>.removeProp()</code></a> method that sounds a lot like <code>removeAttr()</code>, but it <strong>SHOULD NOT BE USED</strong> on native properties like <code>'disabled'</code> Excerpt from the documentation:</p>\n\n<blockquote>\n <p>Note: Do not use this method to remove native properties such as checked, disabled, or selected. This will remove the property completely and, once removed, cannot be added again to element. Use .prop() to set these properties to false instead.</p>\n</blockquote>\n\n<p>In fact, I doubt there are many legitimate uses for this method, boolean props are done in such a way that you should set them to false instead of \"removing\" them like their \"attribute\" counterparts in 1.5</p>\n",
"source": "so",
"questionId": 1414365
},
{
"title": "Creating multiline strings in JavaScript",
"body": "<h3>Update:</h3>\n\n<p>ECMAScript 6 (ES6) introduces a new type of literal, namely <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/template_strings\" rel=\"noreferrer\"><strong>template literals</strong></a>. They have many features, variable interpolation among others, but most importantly for this question, they can be multiline.</p>\n\n<p>A template literal is delimited by <em>backticks</em>:</p>\n\n<pre><code>var html = `\n &lt;div&gt;\n &lt;span&gt;Some HTML here&lt;/span&gt;\n &lt;/div&gt;\n`;\n</code></pre>\n\n<p>(Note: I'm not advocating to use HTML in strings)</p>\n\n<p><a href=\"https://kangax.github.io/compat-table/es6/#test-template_literals\" rel=\"noreferrer\">Browser support is OK</a>, but you can use <a href=\"https://babeljs.io/\" rel=\"noreferrer\">transpilers</a> to be more compatible.</p>\n\n<hr>\n\n<h3>Original ES5 answer:</h3>\n\n<p>Javascript doesn't have a here-document syntax. You can escape the literal newline, however, which comes close:</p>\n\n<pre><code>\"foo \\\nbar\"\n</code></pre>\n",
"source": "so",
"questionId": 805107
},
{
"title": "How does JavaScript .prototype work?",
"body": "<p>Every JavaScript object has an internal property called <em>[[Prototype]]</em>. If you look up a property via <code>obj.propName</code> or <code>obj['propName']</code> and the object does not have such a property - which can be checked via <code>obj.hasOwnProperty('propName')</code> - the runtime looks up the property in the object referenced by [[Prototype]] instead. If the prototype-object also doesn't have such a property, its prototype is checked in turn, thus walking the original object's <em>prototype-chain</em> until a match is found or its end is reached.</p>\n\n<p>Some JavaScript implementations allow direct access to the [[Prototype]] property, eg via a non-standard property named <code>__proto__</code>. In general, it's only possible to set an object's prototype during object creation: If you create a new object via <code>new Func()</code>, the object's [[Prototype]] property will be set to the object referenced by <code>Func.prototype</code>.</p>\n\n<p>This allows to simulate classes in JavaScript, although JavaScript's inheritance system is - as we have seen - prototypical, and not class-based:</p>\n\n<p>Just think of constructor functions as classes and the properties of the prototype (ie of the object referenced by the constructor function's <code>prototype</code> property) as shared members, ie members which are the same for each instance. In class-based systems, methods are implemented the same way for each instance, so methods are normally added to the prototype, whereas an object's fields are instance-specific and therefore added to the object itself during construction.</p>\n",
"source": "so",
"questionId": 572897
},
{
"title": "How to check for &quot;undefined&quot; in JavaScript?",
"body": "<p>If you are interested in finding out whether a variable has been declared regardless of its value, then using the <code>in</code> operator is the safest way to go. Consider this example.</p>\n\n<pre><code>// global scope\nvar theFu; // theFu has been declared, but its value is undefined\ntypeof theFu; // \"undefined\"\n</code></pre>\n\n<p>But this may not be the intended result for some cases, since the variable or property was declared but just not initialized. Use the <code>in</code> operator for a more robust check.</p>\n\n<pre><code>\"theFu\" in window; // true\n\"theFoo\" in window; // false\n</code></pre>\n\n<p>If you are interested in knowing whether the variable hasn't been declared or has the value <code>undefined</code>, then use the <code>typeof</code> operator.</p>\n\n<pre><code>if (typeof myVar != 'undefined')\n</code></pre>\n\n<p>The <code>typeof</code> operator is guaranteed to return a string. Direct comparisons against <code>undefined</code> are troublesome as <code>undefined</code> can be overwritten. </p>\n\n<pre><code>window.undefined = \"omg\";\n\"omg\" == undefined // true\n</code></pre>\n\n<p>As @CMS pointed out, this has been patched in ECMAScript 5th ed., and <code>undefined</code> is non-writable.</p>\n\n<p><code>if (window.myVar)</code> will also include these falsy values, so it's not very robust:</p>\n\n<pre>\nfalse\n0\n\"\"\nNaN\nnull\nundefined\n</pre>\n\n<p>Thanks to @CMS for pointing out that your third case - <code>if (myVariable)</code> can also throw an error in two cases. The first is when the variable hasn't been defined which throws a <code>ReferenceError</code>. </p>\n\n<pre><code>// abc was never declared.\nif (abc) {\n // ReferenceError: abc is not defined\n} \n</code></pre>\n\n<p>The other case is when the variable has been defined, but has a getter function which throws an error when invoked. For example,</p>\n\n<pre><code>// or it's a property that can throw an error\nObject.defineProperty(window, \"myVariable\", { \n get: function() { throw new Error(\"W00t?\"); }, \n set: undefined \n});\nif (myVariable) {\n // Error: W00t?\n}\n</code></pre>\n",
"source": "so",
"questionId": 3390396
},
{
"title": "What is JSONP all about?",
"body": "<p>It's actually not too complicated...</p>\n\n<p>Say you're on domain example.com, and you want to make a request to domain example.net. To do so, you need to cross domain boundaries, a no-no in most of browserland. </p>\n\n<p>The one item that bypasses this limitation is &lt;script&gt; tags. When you use a script tag, the domain limitation is ignored, but under normal circumstances, you can't really <strong>do</strong> anything with the results, the script just gets evaluated.</p>\n\n<p>Enter JSONP. When you make your request to a server that is JSONP enabled, you pass a special parameter that tells the server a little bit about your page. That way, the server is able to nicely wrap up its response in a way that your page can handle. </p>\n\n<p>For example, say the server expects a parameter called \"callback\" to enable its JSONP capabilities. Then your request would look like:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>http://www.example.net/sample.aspx?callback=mycallback\n</code></pre>\n\n<p>Without JSONP, this might return some basic JavaScript object, like so:</p>\n\n<pre><code>{ foo: 'bar' }\n</code></pre>\n\n<p>However, with JSONP, when the server receives the \"callback\" parameter, it wraps up the result a little differently, returning something like this:</p>\n\n<pre><code>mycallback({ foo: 'bar' });\n</code></pre>\n\n<p>As you can see, it will now invoke the method you specified. So, in your page, you define the callback function:</p>\n\n<pre><code>mycallback = function(data){\n alert(data.foo);\n};\n</code></pre>\n\n<p>And now, when the script is loaded, it'll be evaluated, and your function will be executed. Voila, cross-domain requests!</p>\n\n<p>It's also worth noting the one major issue with JSONP: you lose a lot of control of the request. For example, there is no \"nice\" way to get proper failure codes back. As a result, you end up using timers to monitor the request, etc, which is always a bit suspect. The proposition for <a href=\"http://www.json.org/JSONRequest.html\" rel=\"noreferrer\">JSONRequest</a> is a great solution to allowing cross domain scripting, maintaining security, and allowing proper control of the request.</p>\n\n<p>These days (2015), <a href=\"http://en.wikipedia.org/wiki/Cross-origin_resource_sharing\" rel=\"noreferrer\">CORS</a> is the recommended approach vs. JSONRequest. JSONP is still useful for older browser support, but given the security implications, unless you have no choice CORS is the better choice.</p>\n",
"source": "so",
"questionId": 2067472
},
{
"title": "jQuery scroll to element",
"body": "<p>Assuming you have a button with the id <code>button</code>, try this example:</p>\n\n<pre><code>$(\"#button\").click(function() {\n $('html, body').animate({\n scrollTop: $(\"#elementtoScrollToID\").offset().top\n }, 2000);\n});\n</code></pre>\n\n<p>I got the code from the article <em><a href=\"http://www.abeautifulsite.net/smoothly-scroll-to-an-element-without-a-jquery-plugin-2/\" rel=\"noreferrer\">Smoothly scroll to an element without a jQuery plugin</a></em>. And I have tested it on the example below.</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"false\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;html&gt;\r\n &lt;script src=\"https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js\"&gt;&lt;/script&gt;\r\n &lt;script&gt;\r\n $(document).ready(function (){\r\n $(\"#click\").click(function (){\r\n $('html, body').animate({\r\n scrollTop: $(\"#div1\").offset().top\r\n }, 2000);\r\n });\r\n });\r\n &lt;/script&gt;\r\n &lt;div id=\"div1\" style=\"height: 1000px; width 100px\"&gt;\r\n Test\r\n &lt;/div&gt;\r\n &lt;br/&gt;\r\n &lt;div id=\"div2\" style=\"height: 1000px; width 100px\"&gt;\r\n Test 2\r\n &lt;/div&gt;\r\n &lt;button id=\"click\"&gt;Click me&lt;/button&gt;\r\n&lt;/html&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"source": "so",
"questionId": 6677035
},
{
"title": "How does data binding work in AngularJS?",
"body": "<p>AngularJS remembers the value and compares it to a previous value. This is basic dirty-checking. If there is a change in value, then it fires the change event.</p>\n\n<p>The <code>$apply()</code> method, which is what you call when you are transitioning from a non-AngularJS world into an AngularJS world, calls <code>$digest()</code>. A digest is just plain old dirty-checking. It works on all browsers and is totally predictable.</p>\n\n<p>To contrast dirty-checking (AngularJS) vs change listeners (<a href=\"http://en.wikipedia.org/wiki/KnockoutJS\">KnockoutJS</a> and <a href=\"https://en.wikipedia.org/wiki/Backbone.js\">Backbone.js</a>): While dirty-checking may seem simple, and even inefficient (I will address that later), it turns out that it is semantically correct all the time, while change listeners have lots of weird corner cases and need things like dependency tracking to make it more semantically correct. KnockoutJS dependency tracking is a clever feature for a problem which AngularJS does not have.</p>\n\n<h1>Issues with change listeners:</h1>\n\n<ul>\n<li>The syntax is atrocious, since browsers do not support it natively. Yes, there are proxies, but they are not semantically correct in all cases, and of course there are no proxies on old browsers. The bottom line is that dirty-checking allows you to do <a href=\"http://en.wikipedia.org/wiki/Plain_Old_Java_Object\">POJO</a>, whereas KnockoutJS and Backbone.js force you to inherit from their classes, and access your data through accessors.</li>\n<li>Change coalescence. Suppose you have an array of items. Say you want to add items into an array, as you are looping to add, each time you add you are firing events on change, which is rendering the UI. This is very bad for performance. What you want is to update the UI only once, at the end. The change events are too fine-grained.</li>\n<li>Change listeners fire immediately on a setter, which is a problem, since the change listener can further change data, which fires more change events. This is bad since on your stack you may have several change events happening at once. Suppose you have two arrays which need to be kept in sync for whatever reason. You can only add to one or the other, but each time you add you fire a change event, which now has an inconsistent view of the world. This is a very similar problem to thread locking, which JavaScript avoids since each callback executes exclusively and to completion. Change events break this since setters can have far-reaching consequences which are not intended and non obvious, which creates the thread problem all over again. It turns out that what you want to do is to delay the listener execution, and guarantee, that only one listener runs at a time, hence any code is free to change data, and it knows that no other code runs while it is doing so.</li>\n</ul>\n\n<h1>What about performance?</h1>\n\n<p>So it may seem that we are slow, since dirty-checking is inefficient. This is where we need to look at real numbers rather than just have theoretical arguments, but first let's define some constraints.</p>\n\n<p>Humans are:</p>\n\n<ul>\n<li><p><em>Slow</em> — Anything faster than 50&nbsp;ms is imperceptible to humans and thus can be considered as \"instant\".</p></li>\n<li><p><em>Limited</em> — You can't really show more than about 2000 pieces of information to a human on a single page. Anything more than that is really bad UI, and humans can't process this anyway.</p></li>\n</ul>\n\n<p>So the real question is this: How many comparisons can you do on a browser in 50&nbsp;ms? This is a hard question to answer as many factors come into play, but here is a test case: <a href=\"http://jsperf.com/angularjs-digest/6\">http://jsperf.com/angularjs-digest/6</a> which creates 10,000 watchers. On a modern browser this takes just under 6&nbsp;ms. On <a href=\"http://en.wikipedia.org/wiki/Internet_Explorer_8\">Internet&nbsp;Explorer&nbsp;8</a> it takes about 40&nbsp;ms. As you can see, this is not an issue even on slow browsers these days. There is a caveat: The comparisons need to be simple to fit into the time limit... Unfortunately it is way too easy to add a slow comparison into AngularJS, so it is easy to build slow applications when you don't know what you are doing. But we hope to have an answer by providing an instrumentation module, which would show you which are the slow comparisons.</p>\n\n<p>It turns out that video games and GPUs use the dirty-checking approach, specifically because it is consistent. As long as they get over the monitor refresh rate (typically 50-60 Hz, or every 16.6-20 ms), any performance over that is a waste, so you're better off drawing more stuff, than getting FPS higher.</p>\n",
"source": "so",
"questionId": 9682092
},
{
"title": "Length of a JavaScript object",
"body": "<p>The most robust answer (i.e. that captures the intent of what you're trying to do while causing the fewest bugs) would be:</p>\n\n<pre><code>Object.size = function(obj) {\n var size = 0, key;\n for (key in obj) {\n if (obj.hasOwnProperty(key)) size++;\n }\n return size;\n};\n\n// Get the size of an object\nvar size = Object.size(myArray);\n</code></pre>\n\n<p>There's a sort of convention in JavaScript that you <a href=\"https://stackoverflow.com/questions/10757455/object-prototype-is-verboten\">don't add things to Object.prototype</a>, because it can break enumerations in various libraries. Adding methods to Object is usually safe, though.</p>\n\n<hr>\n\n<p><strong>Here's an update as of 2016 and <a href=\"http://kangax.github.io/compat-table/es5/\" rel=\"noreferrer\">widespread deployment of ES5</a> and beyond.</strong> For IE9+ and all other modern ES5+ capable browsers, you can use <code>Object.keys()</code> so the above code just becomes:</p>\n\n<pre><code>var size = Object.keys(myObj).length;\n</code></pre>\n\n<p>This doesn't have to modify any existing prototype since <code>Object.keys()</code> is now built in.</p>\n",
"source": "so",
"questionId": 5223
},
{
"title": "Modify the URL without reloading the page",
"body": "<p>This can now be done in Chrome, Safari, FF4+, and IE10pp4+!</p>\n\n<p>See this question's answer for more info:\n<a href=\"https://stackoverflow.com/questions/3338642/updating-address-bar-with-new-url-without-hash-or-reloading-the-page\">Updating address bar with new URL without hash or reloading the page</a></p>\n\n<p>Example:</p>\n\n<pre><code> function processAjaxData(response, urlPath){\n document.getElementById(\"content\").innerHTML = response.html;\n document.title = response.pageTitle;\n window.history.pushState({\"html\":response.html,\"pageTitle\":response.pageTitle},\"\", urlPath);\n }\n</code></pre>\n\n<p>You can then use <code>window.onpopstate</code> to detect the back/forward button navigation:</p>\n\n<pre><code>window.onpopstate = function(e){\n if(e.state){\n document.getElementById(\"content\").innerHTML = e.state.html;\n document.title = e.state.pageTitle;\n }\n};\n</code></pre>\n\n<hr>\n\n<p>For a more in-depth look at manipulating browser history see <a href=\"https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Manipulating_the_browser_history\" rel=\"noreferrer\">this MDN article</a>.</p>\n",
"source": "so",
"questionId": 824349
},
{
"title": "How can I merge properties of two JavaScript objects dynamically?",
"body": "<p><strong>ECMAScript 2015 (ES6) Standard Method</strong></p>\n\n<pre><code>/* For the case in question, you would do: */\nObject.assign(obj1, obj2);\n\n/** There's no limit to the number of objects you can merge.\n * All objects get merged into the first object. \n * Only the object in the first argument is mutated and returned.\n * Later properties overwrite earlier properties with the same name. */\nconst allRules = Object.assign({}, obj1, obj2, obj3, etc);\n</code></pre>\n\n<p>(see <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign#Browser_compatibility\" rel=\"noreferrer\">MDN JavaScript Reference</a>)</p>\n\n<hr>\n\n<p><strong>Method for ES5 and Earlier</strong></p>\n\n<pre><code>for (var attrname in obj2) { obj1[attrname] = obj2[attrname]; }\n</code></pre>\n\n<p>Note that this will simply add all attributes of <code>obj2</code> to <code>obj1</code> which might not be what you want if you still want to use the unmodified <code>obj1</code>.</p>\n\n<p>If you're using a framework that craps all over your prototypes then you have to get fancier with checks like <code>hasOwnProperty</code>, but that code will work for 99% of cases.</p>\n\n<p>Example function:</p>\n\n<pre><code>/**\n * Overwrites obj1's values with obj2's and adds obj2's if non existent in obj1\n * @param obj1\n * @param obj2\n * @returns obj3 a new object based on obj1 and obj2\n */\nfunction merge_options(obj1,obj2){\n var obj3 = {};\n for (var attrname in obj1) { obj3[attrname] = obj1[attrname]; }\n for (var attrname in obj2) { obj3[attrname] = obj2[attrname]; }\n return obj3;\n}\n</code></pre>\n",
"source": "so",
"questionId": 171251
},
{
"title": "Round to at most 2 decimal places (only if necessary)",
"body": "<p>Use <code>Math.round(num * 100) / 100</code></p>\n",
"source": "so",
"questionId": 11832914
},
{
"title": "How can I convert a string to boolean in JavaScript?",
"body": "<h1>Do:</h1>\n\n<pre><code>var isTrueSet = (myValue == 'true');\n</code></pre>\n\n<hr>\n\n<h2>Unnecessary:</h2>\n\n<p>You could make it stricter by using the identity operator (<code>===</code>), which doesn't make any implicit type conversions when the compared variables have different types, instead of the equality operator (<code>==</code>), which does:</p>\n\n<pre><code>var isTrueSet = (myValue === 'true');\n</code></pre>\n\n<hr>\n\n<h2>Don't:</h2>\n\n<p>You should probably <strong>be cautious about using these two methods</strong> for your specific needs:</p>\n\n<pre><code>var myBool = Boolean(\"false\"); // == true\n\nvar myBool = !!\"false\"; // == true\n</code></pre>\n\n<p>Any string which isn't the empty string will evaluate to <code>true</code> by using them. Although they're the cleanest methods I can think of concerning to boolean conversion, I think they're not what you're looking for.</p>\n",
"source": "so",
"questionId": 263965
},
{
"title": "How do I test for an empty JavaScript object?",
"body": "<p><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys#Browser_compatibility\" rel=\"noreferrer\">ECMA 5+</a>:</p>\n\n<pre><code>// because Object.keys(new Date()).length === 0;\n// we have to do some additional check\nObject.keys(obj).length === 0 &amp;&amp; obj.constructor === Object\n</code></pre>\n\n<p>Pre-ECMA 5:</p>\n\n<pre><code>function isEmpty(obj) {\n for(var prop in obj) {\n if(obj.hasOwnProperty(prop))\n return false;\n }\n\n return JSON.stringify(obj) === JSON.stringify({});\n}\n</code></pre>\n\n<p><a href=\"http://api.jquery.com/jQuery.isEmptyObject/\" rel=\"noreferrer\">jQuery</a>:</p>\n\n<pre><code>jQuery.isEmptyObject({}); // true\n</code></pre>\n\n<p><a href=\"https://lodash.com/docs#isEmpty\" rel=\"noreferrer\">lodash</a>:</p>\n\n<pre><code>_.isEmpty({}); // true\n</code></pre>\n\n<p><a href=\"http://underscorejs.org/#isEmpty\" rel=\"noreferrer\">Underscore</a>:</p>\n\n<pre><code>_.isEmpty({}); // true\n</code></pre>\n\n<p><a href=\"https://github.com/hapijs/hoek\" rel=\"noreferrer\">Hoek</a></p>\n\n<pre><code>Hoek.deepEqual({}, {}); // true\n</code></pre>\n\n<p><a href=\"http://docs.sencha.com/extjs/6.0.2/modern/Ext.html#method-isEmpty\" rel=\"noreferrer\">ExtJS</a></p>\n\n<pre><code>Ext.Object.isEmpty({}); // true\n</code></pre>\n\n<p><a href=\"https://docs.angularjs.org/api/ng/function/angular.equals\" rel=\"noreferrer\">AngularJS (version 1)</a></p>\n\n<pre><code>angular.equals({}, {}); // true\n</code></pre>\n\n<p><a href=\"http://ramdajs.com/docs/#isEmpty\" rel=\"noreferrer\">Ramda</a></p>\n\n<pre><code>R.isEmpty({}); // true\n</code></pre>\n",
"source": "so",
"questionId": 679915
},
{
"title": "Sort array of objects by string property value in JavaScript",
"body": "<p>It's easy enough to write your own comparison function:</p>\n\n<pre><code>function compare(a,b) {\n if (a.last_nom &lt; b.last_nom)\n return -1;\n if (a.last_nom &gt; b.last_nom)\n return 1;\n return 0;\n}\n\nobjs.sort(compare);\n</code></pre>\n\n<p>Or inline (c/o Marco Demaio): </p>\n\n<pre><code>objs.sort(function(a,b) {return (a.last_nom &gt; b.last_nom) ? 1 : ((b.last_nom &gt; a.last_nom) ? -1 : 0);} ); \n</code></pre>\n",
"source": "so",
"questionId": 1129216
},
{
"title": "How do I pass command line arguments?",
"body": "<h1>Standard Method (no library)</h1>\n\n<p>The arguments are stored in <code>process.argv</code></p>\n\n<p>Here are <a href=\"http://nodejs.org/docs/latest/api/process.html#process_process_argv\">the node docs on handling command line args:</a></p>\n\n<blockquote>\n <p><code>process.argv</code> is an array containing the command line arguments. The first element will be 'node', the second element will be the name of the JavaScript file. The next elements will be any additional command line arguments.</p>\n</blockquote>\n\n<pre><code>// print process.argv\nprocess.argv.forEach(function (val, index, array) {\n console.log(index + ': ' + val);\n});\n</code></pre>\n\n<p>This will generate:</p>\n\n<pre><code>$ node process-2.js one two=three four\n0: node\n1: /Users/mjr/work/node/process-2.js\n2: one\n3: two=three\n4: four\n</code></pre>\n",
"source": "so",
"questionId": 4351521
},
{
"title": "What is the scope of variables in JavaScript?",
"body": "<p>I think about the best I can do is give you a bunch of examples to study.\nJavascript programmers are practically ranked by how well they understand scope.\nIt can at times be quite counter-intuitive.</p>\n\n<ol>\n<li><p><strong>A globally-scoped variable</strong></p>\n\n<pre><code>// global scope\nvar a = 1;\n\nfunction one() {\n alert(a); // alerts '1'\n}\n</code></pre></li>\n<li><p><strong>Local scope</strong></p>\n\n<pre><code>// global scope\nvar a = 1;\n\nfunction two(a) {\n // local scope\n alert(a); // alerts the given argument, not the global value of '1'\n}\n\n// local scope again\nfunction three() {\n var a = 3;\n alert(a); // alerts '3'\n}\n</code></pre></li>\n<li><p><strong>Intermediate</strong>: <em>No such thing as block scope in JavaScript</em> (ES5; ES6 introduces <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let\" rel=\"noreferrer\"><code>let</code></a>)</p>\n\n<p>a.</p>\n\n<pre><code>var a = 1;\n\nfunction four() {\n if (true) {\n var a = 4;\n }\n\n alert(a); // alerts '4', not the global value of '1'\n}\n</code></pre>\n\n<p>b.</p>\n\n<pre><code>var a = 1;\n\nfunction one() {\n if (true) {\n let a = 4;\n }\n\n alert(a); // alerts '1' because the 'let' keyword uses block scoping\n}\n</code></pre></li>\n<li><p><strong>Intermediate</strong>: <em>Object properties</em></p>\n\n<pre><code>var a = 1;\n\nfunction Five() {\n this.a = 5;\n}\n\nalert(new Five().a); // alerts '5'\n</code></pre></li>\n<li><p><strong>Advanced</strong>: <em>Closure</em></p>\n\n<pre><code>var a = 1;\n\nvar six = (function() {\n var a = 6;\n\n return function() {\n // JavaScript \"closure\" means I have access to 'a' in here,\n // because it is defined in the function in which I was defined.\n alert(a); // alerts '6'\n };\n})();\n</code></pre></li>\n<li><p><strong>Advanced</strong>: <em>Prototype-based scope resolution</em></p>\n\n<pre><code>var a = 1;\n\nfunction seven() {\n this.a = 7;\n}\n\n// [object].prototype.property loses to\n// [object].property in the lookup chain. For example...\n\n// Won't get reached, because 'a' is set in the constructor above.\nseven.prototype.a = -1;\n\n// Will get reached, even though 'b' is NOT set in the constructor.\nseven.prototype.b = 8;\n\nalert(new seven().a); // alerts '7'\nalert(new seven().b); // alerts '8'\n</code></pre>\n\n<hr></li>\n<li><p><strong>Global+Local</strong>: <em>An extra complex Case</em></p>\n\n<pre><code>var x = 5;\n\n(function () {\n console.log(x);\n var x = 10;\n console.log(x); \n})();\n</code></pre>\n\n<p>This will print out <code>undefined</code> and <code>10</code> rather than <code>5</code> and <code>10</code> since JavaScript always moves variable declarations (not initializations) to the top of the scope, making the code equivalent to:</p>\n\n<pre><code>var x = 5;\n\n(function () {\n var x;\n console.log(x);\n x = 10;\n console.log(x); \n})();\n</code></pre></li>\n<li><p><strong>Catch clause-scoped variable</strong></p>\n\n<pre><code>var e = 5;\nconsole.log(e);\ntry {\n throw 6;\n} catch (e) {\n console.log(e);\n}\nconsole.log(e);\n</code></pre>\n\n<p>This will print out <code>5</code>, <code>6</code>, <code>5</code>. Inside the catch clause <code>e</code> shadows global and local variables. But this special scope is only for the caught variable. If you write <code>var f;</code> inside the catch clause, then it's exactly the same as if you had defined it before or after the try-catch block.</p></li>\n</ol>\n",
"source": "so",
"questionId": 500431
},
{
"title": "When to use double or single quotes in JavaScript?",
"body": "<p>The most likely reason for use of single vs double in different libraries is programmer preference and/or API consistency.</p>\n\n<p>Other than being consistent, use whichever best suits the string:.</p>\n\n<p>Using the other type of quote as a literal:</p>\n\n<pre><code>alert('Say \"Hello\"');\nalert(\"Say 'Hello'\");\n</code></pre>\n\n<p>…but this can get complicated…</p>\n\n<pre><code>alert(\"It's \\\"game\\\" time.\");\nalert('It\\'s \"game\" time.');\n</code></pre>\n\n<p>Another option, new in ES6, are <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals\" rel=\"noreferrer\">Template literals</a> which use the <code>back-tick</code> character:</p>\n\n<pre><code>alert(`Use \"double\" and 'single' quotes in the same string`);\nalert(`The escape the \\` back-tick character in a string`);\n</code></pre>\n\n<p>Template literals offer a clean syntax for: variable interpolation, multi-line strings, and more.</p>\n",
"source": "so",
"questionId": 242813
},
{
"title": "Event binding on dynamically created elements?",
"body": "<p><strong>As of jQuery 1.7</strong> you should use <a href=\"https://api.jquery.com/on/#on-events-selector-data-handler\" rel=\"noreferrer\"><code>jQuery.fn.on</code></a>:</p>\n\n<pre><code>$(staticAncestors).on(eventName, dynamicChild, function() {});\n</code></pre>\n\n<hr>\n\n<p><strong>Prior to this</strong>, the recommended approach was to use <a href=\"http://api.jquery.com/live\" rel=\"noreferrer\"><code>live()</code></a>: </p>\n\n<pre><code>$(selector).live( eventName, function(){} );\n</code></pre>\n\n<p>However, <code>live()</code> was deprecated in 1.7 in favour of <code>on()</code>, and completely removed in 1.9. The <code>live()</code> signature:</p>\n\n<pre><code>$(selector).live( eventName, function(){} );\n</code></pre>\n\n<p>... can be replaced with the following <a href=\"http://api.jquery.com/on/\" rel=\"noreferrer\"><code>on()</code></a> signature:</p>\n\n<pre><code>$(document).on( eventName, selector, function(){} );\n</code></pre>\n\n<hr>\n\n<p>For example, if your page was dynamically creating elements with the class name <code>dosomething</code> you would bind the event to <strong>a parent which already exists</strong> (this is the nub of the problem here, you need something that exists to bind to, don't bind to the dynamic content), this can be (and the easiest option) is <code>document</code>. Though bear in mind <a href=\"https://stackoverflow.com/questions/12824549/should-all-jquery-events-be-bound-to-document\"><code>document</code> may not be the most efficient option</a>.</p>\n\n<pre><code>$(document).on('mouseover mouseout', '.dosomething', function(){\n // what you want to happen when mouseover and mouseout \n // occurs on elements that match '.dosomething'\n});\n</code></pre>\n\n<p>Any parent that exists at the time the event is bound is fine. For example</p>\n\n<pre><code>$('.buttons').on('click', 'button', function(){\n // do something here\n});\n</code></pre>\n\n<p>would apply to </p>\n\n<pre><code>&lt;div class=\"buttons\"&gt;\n &lt;!-- &lt;button&gt;s that are generated dynamically and added here --&gt;\n&lt;/div&gt;\n</code></pre>\n",
"source": "so",
"questionId": 203198
},
{
"title": "Abort Ajax requests using jQuery",
"body": "<p>Most of the jQuery Ajax methods return an XMLHttpRequest (or the equivalent) object, so you can just use <code>abort()</code>.</p>\n\n<p>See the documentation:</p>\n\n<ul>\n<li><a href=\"http://msdn.microsoft.com/en-us/library/ms535920%28VS.85%29.aspx\" rel=\"noreferrer\">abort Method</a> (<a href=\"http://en.wikipedia.org/wiki/Microsoft_Developer_Network\" rel=\"noreferrer\">MSDN</a>). Cancels the current HTTP request.</li>\n<li><a href=\"https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/abort\" rel=\"noreferrer\">abort()</a> (<a href=\"http://en.wikipedia.org/wiki/Mozilla_Developer_Network\" rel=\"noreferrer\">MDN</a>). If the request has been sent already, this method will abort the request.</li>\n</ul>\n\n\n\n<pre><code>var xhr = $.ajax({\n type: \"POST\",\n url: \"some.php\",\n data: \"name=John&amp;location=Boston\",\n success: function(msg){\n alert( \"Data Saved: \" + msg );\n }\n});\n\n//kill the request\nxhr.abort()\n</code></pre>\n\n<p><strong>UPDATE:</strong>\nAs of jQuery 1.5 the returned object is a wrapper for the native XMLHttpRequest object called jqXHR. This object appears to expose all of the native properties and methods so the above example still works. See <em><a href=\"http://api.jquery.com/jQuery.ajax/#jqXHR\" rel=\"noreferrer\">The jqXHR Object</a></em> (jQuery API documentation).</p>\n\n<p><strong>UPDATE 2:</strong>\nAs of jQuery 3, the ajax method returns a promise without extra methods (like abort), so this will no longer work. See the <a href=\"http://blog.jquery.com/2016/01/14/jquery-3-0-beta-released/\" rel=\"noreferrer\">3.0 blog here</a>. One way around this is to control the xhr object through the <code>xhr</code> property. Here is a crude example:</p>\n\n<pre><code>var xhr = new window.XMLHttpRequest();\nvar request = $.ajax({\n url : url,\n xhr : function(){\n return xhr;\n }\n});\nxhr.abort();\n</code></pre>\n",
"source": "so",
"questionId": 446594
},
{
"title": "How do I get the current date in JavaScript?",
"body": "<p>Use <code>new Date()</code> to generate a new <code>Date</code> object containing the current date and time.</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"false\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>var today = new Date();\r\nvar dd = today.getDate();\r\nvar mm = today.getMonth()+1; //January is 0!\r\nvar yyyy = today.getFullYear();\r\n\r\nif(dd&lt;10) {\r\n dd = '0'+dd\r\n} \r\n\r\nif(mm&lt;10) {\r\n mm = '0'+mm\r\n} \r\n\r\ntoday = mm + '/' + dd + '/' + yyyy;\r\ndocument.write(today);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>This will give you today's date in the format of mm/dd/yyyy.</p>\n\n<p>Simply change <code>today = mm +'/'+ dd +'/'+ yyyy;</code> to whatever format you wish.</p>\n",
"source": "so",
"questionId": 1531093
},
{
"title": "What is the difference between Bower and npm?",
"body": "<p><a href=\"https://www.npmjs.org\" rel=\"noreferrer\">npm</a> is most commonly used for managing Node.js modules, but it works for the front-end too when combined with <a href=\"http://browserify.org/\" rel=\"noreferrer\">Browserify</a> and/or <code>$ npm dedupe</code>.</p>\n\n<p><a href=\"http://bower.io\" rel=\"noreferrer\">Bower</a> is created solely for the front-end and is optimized with that in mind. The biggest difference is that npm does nested dependency tree <em>(size heavy)</em> while Bower requires a flat dependency tree <em>(puts the burden of dependency resolution on the user)</em>.</p>\n\n<p>A nested dependency tree means that your dependencies can have their own dependencies which can have their own, and so on. This is really great on the server where you don't have to care much about space and latency. It lets you not have to care about dependency conflicts as all your dependencies use e.g. their own version of Underscore. This obviously doesn't work that well on the front-end. Imagine a site having to download three copies of jQuery.</p>\n\n<p>The reason many projects use both is that they use Bower for front-end packages and npm for developer tools like Yeoman, Grunt, Gulp, JSHint, CoffeeScript, etc.</p>\n\n<p>All package managers have many downsides. You just have to pick which you can live with.</p>\n\n<hr>\n\n<h2>Resources</h2>\n\n<ul>\n<li><a href=\"http://maxogden.com/nested-dependencies.html\" rel=\"noreferrer\">Nested Dependencies</a> - Insight into why node_modules works the way it does</li>\n</ul>\n",
"source": "so",
"questionId": 18641899
},
{
"title": "What is the preferred syntax for defining enums in JavaScript?",
"body": "<p>I can't post comment to THE answer, so I guess I'd bump the thread since it shows up high in Google.</p>\n\n<p>Since 1.8.5 it's possible to seal and freeze the object, so define the above as:</p>\n\n<pre><code>var DaysEnum = Object.freeze({\"monday\":1, \"tuesday\":2, \"wednesday\":3, ...})\n</code></pre>\n\n<p>or</p>\n\n<pre><code>var DaysEnum = {\"monday\":1, \"tuesday\":2, \"wednesday\":3, ...}\nObject.freeze(DaysEnum)\n</code></pre>\n\n<p>and voila! JS enums ;)</p>\n\n<p>source: <a href=\"https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object/freeze\">https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object/freeze</a></p>\n\n<p>IMHO quotes aren't needed but I kept them for consistency.</p>\n",
"source": "so",
"questionId": 287903
},
{
"title": "$(document).ready equivalent without jQuery",
"body": "<p>There is a standards based replacement,<code>DOMContentLoaded</code> that is supported by over <a href=\"http://caniuse.com/#search=DOMContentLoaded\" rel=\"noreferrer\">98% of browsers</a>, though not IE8:</p>\n\n<pre><code>document.addEventListener(\"DOMContentLoaded\", function(event) { \n //do work\n});\n</code></pre>\n\n<p>jQuery's native function is much more complicated than just window.onload, as depicted below. </p>\n\n<pre><code>function bindReady(){\n if ( readyBound ) return;\n readyBound = true;\n\n // Mozilla, Opera and webkit nightlies currently support this event\n if ( document.addEventListener ) {\n // Use the handy event callback\n document.addEventListener( \"DOMContentLoaded\", function(){\n document.removeEventListener( \"DOMContentLoaded\", arguments.callee, false );\n jQuery.ready();\n }, false );\n\n // If IE event model is used\n } else if ( document.attachEvent ) {\n // ensure firing before onload,\n // maybe late but safe also for iframes\n document.attachEvent(\"onreadystatechange\", function(){\n if ( document.readyState === \"complete\" ) {\n document.detachEvent( \"onreadystatechange\", arguments.callee );\n jQuery.ready();\n }\n });\n\n // If IE and not an iframe\n // continually check to see if the document is ready\n if ( document.documentElement.doScroll &amp;&amp; window == window.top ) (function(){\n if ( jQuery.isReady ) return;\n\n try {\n // If IE is used, use the trick by Diego Perini\n // http://javascript.nwbox.com/IEContentLoaded/\n document.documentElement.doScroll(\"left\");\n } catch( error ) {\n setTimeout( arguments.callee, 0 );\n return;\n }\n\n // and execute any waiting functions\n jQuery.ready();\n })();\n }\n\n // A fallback to window.onload, that will always work\n jQuery.event.add( window, \"load\", jQuery.ready );\n}\n</code></pre>\n",
"source": "so",
"questionId": 799981
},
{
"title": "JavaScript equivalent to printf/string.format",
"body": "<p>Try <a href=\"https://github.com/alexei/sprintf.js\" rel=\"noreferrer\">sprintf() for JavaScript</a>.</p>\n\n<hr>\n\n<p><strong>Update</strong>    Ok, if you really want to do a simple format method on your own, don’t do the replacements successively but do them simultaneously.</p>\n\n<p>Because most of the other proposals that are mentioned fail when a replace string of previous replacement does also contain a format sequence like this:</p>\n\n<pre><code>\"{0}{1}\".format(\"{1}\", \"{0}\")\n</code></pre>\n\n<p>Normally you would expect the output to be <code>{1}{0}</code> but the actual output is <code>{1}{1}</code>. So do a simultaneously replacement instead like in <a href=\"https://stackoverflow.com/questions/610406/javascript-printf-string-format/4673436#4673436\">fearphage’s suggestion</a>.</p>\n",
"source": "so",
"questionId": 610406
},
{
"title": "How can I pretty-print JSON using JavaScript?",
"body": "<p><strong><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify\" rel=\"noreferrer\">Pretty-printing is implemented natively in <code>JSON.stringify()</code></a></strong>. The third argument enables pretty printing and sets the spacing to use:</p>\n\n<pre><code>var str = JSON.stringify(obj, null, 2); // spacing level = 2\n</code></pre>\n\n<p>If you need syntax highlighting, you might use some regex magic like so:</p>\n\n<pre><code>function syntaxHighlight(json) {\n if (typeof json != 'string') {\n json = JSON.stringify(json, undefined, 2);\n }\n json = json.replace(/&amp;/g, '&amp;amp;').replace(/&lt;/g, '&amp;lt;').replace(/&gt;/g, '&amp;gt;');\n return json.replace(/(\"(\\\\u[a-zA-Z0-9]{4}|\\\\[^u]|[^\\\\\"])*\"(\\s*:)?|\\b(true|false|null)\\b|-?\\d+(?:\\.\\d*)?(?:[eE][+\\-]?\\d+)?)/g, function (match) {\n var cls = 'number';\n if (/^\"/.test(match)) {\n if (/:$/.test(match)) {\n cls = 'key';\n } else {\n cls = 'string';\n }\n } else if (/true|false/.test(match)) {\n cls = 'boolean';\n } else if (/null/.test(match)) {\n cls = 'null';\n }\n return '&lt;span class=\"' + cls + '\"&gt;' + match + '&lt;/span&gt;';\n });\n}\n</code></pre>\n\n<p>See in action here: <a href=\"http://jsfiddle.net/KJQ9K/554/\" rel=\"noreferrer\">jsfiddle</a></p>\n\n<p><strong>Or a full snippet provided below:</strong></p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"false\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function output(inp) {\r\n document.body.appendChild(document.createElement('pre')).innerHTML = inp;\r\n}\r\n\r\nfunction syntaxHighlight(json) {\r\n json = json.replace(/&amp;/g, '&amp;amp;').replace(/&lt;/g, '&amp;lt;').replace(/&gt;/g, '&amp;gt;');\r\n return json.replace(/(\"(\\\\u[a-zA-Z0-9]{4}|\\\\[^u]|[^\\\\\"])*\"(\\s*:)?|\\b(true|false|null)\\b|-?\\d+(?:\\.\\d*)?(?:[eE][+\\-]?\\d+)?)/g, function (match) {\r\n var cls = 'number';\r\n if (/^\"/.test(match)) {\r\n if (/:$/.test(match)) {\r\n cls = 'key';\r\n } else {\r\n cls = 'string';\r\n }\r\n } else if (/true|false/.test(match)) {\r\n cls = 'boolean';\r\n } else if (/null/.test(match)) {\r\n cls = 'null';\r\n }\r\n return '&lt;span class=\"' + cls + '\"&gt;' + match + '&lt;/span&gt;';\r\n });\r\n}\r\n\r\nvar obj = {a:1, 'b':'foo', c:[false,'false',null, 'null', {d:{e:1.3e5,f:'1.3e5'}}]};\r\nvar str = JSON.stringify(obj, undefined, 4);\r\n\r\noutput(str);\r\noutput(syntaxHighlight(str));</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>pre {outline: 1px solid #ccc; padding: 5px; margin: 5px; }\r\n.string { color: green; }\r\n.number { color: darkorange; }\r\n.boolean { color: blue; }\r\n.null { color: magenta; }\r\n.key { color: red; }</code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"source": "so",
"questionId": 4810841
},
{
"title": "Get current URL in JavaScript?",
"body": "<p>To get the path, you can use:</p>\n\n<pre><code>var pathname = window.location.pathname; // Returns path only\nvar url = window.location.href; // Returns full URL\n</code></pre>\n",
"source": "so",
"questionId": 406192
},
{
"title": "What is the &#39;new&#39; keyword in JavaScript?",
"body": "<p>It does 5 things:</p>\n\n<ol>\n<li>It creates a new object. The type of this object is simply <em>object</em>.</li>\n<li>It sets this new object's internal, inaccessible, <em>[[prototype]]</em> (i.e. <strong>__proto__</strong>) property to be the constructor function's external, accessible, <em>prototype</em> object (every function object automatically has a <em>prototype</em> property).</li>\n<li>It makes the <code>this</code> variable point to the newly created object.</li>\n<li>It executes the constructor function, using the newly created object whenever <code>this</code> is mentioned.</li>\n<li>It returns the newly created object, unless the constructor function returns a non-<code>null</code> object reference. In this case, that object reference is returned instead.</li>\n</ol>\n\n<p>Note: <em>constructor function</em> refers the function after the <code>new</code> keyword, as in </p>\n\n<pre><code>new ConstructorFunction(arg1, arg2)\n</code></pre>\n\n<p>Once this is done, if an undefined property of the new object is requested, the script will check the object's <em>[[prototype]]</em> object for the property instead. This is how you can get something similar to traditional class inheritance in JavaScript. </p>\n\n<p>The most difficult part about this is point number 2. Every object (including functions) has this internal property called <em>[[prototype]]</em>. It can <em>only</em> be set at object creation time, either with <em>new</em>, with <em>Object.create</em>, or based on the literal (functions default to Function.prototype, numbers to Number.prototype, etc.). It can only be read with <em>Object.getPrototypeOf(someObject)</em>. There is <em>no</em> other way to set or read this value.</p>\n\n<p>Functions, in addition to the hidden <em>[[prototype]]</em> property, also have a property called <em>prototype</em>, and it is this that you can access, and modify, to provide inherited properties and methods for the objects you make.</p>\n\n<hr>\n\n<p>Here is an example:</p>\n\n<pre><code>ObjMaker = function() {this.a = 'first';};\n// ObjMaker is just a function, there's nothing special about it that makes \n// it a constructor.\n\nObjMaker.prototype.b = 'second';\n// like all functions, ObjMaker has an accessible prototype property that \n// we can alter. I just added a property called 'b' to it. Like \n// all objects, ObjMaker also has an inaccessible [[prototype]] property\n// that we can't do anything with\n\nobj1 = new ObjMaker();\n// 3 things just happened.\n// A new, empty object was created called obj1. At first obj1 was the same\n// as {}. The [[prototype]] property of obj1 was then set to the current\n// object value of the ObjMaker.prototype (if ObjMaker.prototype is later\n// assigned a new object value, obj1's [[prototype]] will not change, but you\n// can alter the properties of ObjMaker.prototype to add to both the\n// prototype and [[prototype]]). The ObjMaker function was executed, with\n// obj1 in place of this... so obj1.a was set to 'first'.\n\nobj1.a;\n// returns 'first'\nobj1.b;\n// obj1 doesn't have a property called 'b', so JavaScript checks \n// its [[prototype]]. Its [[prototype]] is the same as ObjMaker.prototype\n// ObjMaker.prototype has a property called 'b' with value 'second'\n// returns 'second'\n</code></pre>\n\n<p>It's like class inheritance because now, any objects you make using <code>new ObjMaker()</code> will also appear to have inherited the 'b' property.</p>\n\n<p>If you want something like a subclass, then you do this:</p>\n\n<pre><code>SubObjMaker = function () {};\nSubObjMaker.prototype = new ObjMaker(); // note: this pattern is deprecated!\n// Because we used 'new', the [[prototype]] property of SubObjMaker.prototype\n// is now set to the object value of ObjMaker.prototype.\n// The modern way to do this is with Object.create(), which was added in ECMAScript 5:\n// SubObjMaker.prototype = Object.create(ObjMaker.prototype);\n\nSubObjMaker.prototype.c = 'third'; \nobj2 = new SubObjMaker();\n// [[prototype]] property of obj2 is now set to SubObjMaker.prototype\n// Remember that the [[prototype]] property of SubObjMaker.prototype\n// is ObjMaker.prototype. So now obj2 has a prototype chain!\n// obj2 ---&gt; SubObjMaker.prototype ---&gt; ObjMaker.prototype\n\nobj2.c;\n// returns 'third', from SubObjMaker.prototype\n\nobj2.b;\n// returns 'second', from ObjMaker.prototype\n\nobj2.a;\n// returns 'first', from SubObjMaker.prototype, because SubObjMaker.prototype \n// was created with the ObjMaker function, which assigned a for us\n</code></pre>\n\n<hr>\n\n<p>I read a ton of rubbish on this subject before finally finding <a href=\"http://joost.zeekat.nl/constructors-considered-mildly-confusing.html\" rel=\"noreferrer\">this page</a>, where this is explained very well with nice diagrams.</p>\n",
"source": "so",
"questionId": 1646698
},
{
"title": "How to determine if variable is &#39;undefined&#39; or &#39;null&#39;?",
"body": "<p>You can use the qualities of the <a href=\"http://www.ecma-international.org/ecma-262/6.0/#sec-abstract-equality-comparison\" rel=\"noreferrer\">abstract equality operator</a> to do this:</p>\n\n<pre><code>if (variable == null){\n // your code here.\n}\n</code></pre>\n\n<p>Because <code>null == undefined</code> is true, the above code will catch both <code>null</code> and <code>undefined</code>.</p>\n",
"source": "so",
"questionId": 2647867
},
{
"title": "How to check if a string &quot;StartsWith&quot; another string?",
"body": "<p>You can use ECMAScript 6's <a href=\"https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith\" rel=\"noreferrer\"><code>String.prototype.startsWith()</code></a> method, but it's <a href=\"http://kangax.github.io/compat-table/es6/#test-String.prototype_methods_String.prototype.startsWith\" rel=\"noreferrer\">not yet supported in all browsers</a>. You'll want to use a shim/polyfill to add it on browsers that don't support it. Creating an implementation that complies with <a href=\"http://www.ecma-international.org/ecma-262/6.0/#sec-string.prototype.startswith\" rel=\"noreferrer\">all the details laid out in the spec</a> is a little complicated, and the version defined in this answer won't do; if you want a faithful shim, use either:</p>\n\n<ul>\n<li><a href=\"https://github.com/mathiasbynens/String.prototype.startsWith\" rel=\"noreferrer\">Matthias Bynens's <code>String.prototype.startsWith</code> shim</a>, or</li>\n<li>The <a href=\"https://github.com/paulmillr/es6-shim\" rel=\"noreferrer\">es6-shim</a>, which shims as much of the ES6 spec as possible, including <code>String.prototype.startsWith</code>.</li>\n</ul>\n\n<p>Once you've shimmed the method (or if you're only supporting browsers and JavaScript engines that already have it), you can use it like this:</p>\n\n<pre><code>\"Hello World!\".startsWith(\"He\"); // true\n\nvar haystack = \"Hello world\";\nvar prefix = 'orl';\nhaystack.startsWith(prefix); // false\n</code></pre>\n",
"source": "so",
"questionId": 646628
},
{
"title": "Is there a standard function to check for null, undefined, or blank variables in JavaScript?",
"body": "<p>You can just check if the <em>variable</em> has a <code>truthy</code> value or not. That means</p>\n\n<pre><code>if( value ) {\n}\n</code></pre>\n\n<p>will evaluate to <code>true</code> if <code>value</code> is <strong>not</strong>:</p>\n\n<ul>\n<li>null</li>\n<li>undefined</li>\n<li>NaN</li>\n<li>empty string (\"\")</li>\n<li>0</li>\n<li>false</li>\n</ul>\n\n<p>The above list represents all possible <code>falsy</code> values in ECMA-/Javascript. Find it in the <a href=\"http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-262.pdf\" rel=\"noreferrer\">specification</a> at the <code>ToBoolean</code> section.</p>\n\n<p>Furthermore, if you do not <strong>know</strong> whether a variable exists (that means, if it was <em>declared</em>) you should check with the <code>typeof</code> operator. For instance</p>\n\n<pre><code>if( typeof foo !== 'undefined' ) {\n // foo could get resolved and it's defined\n}\n</code></pre>\n\n<p>If you can be sure that a <em>variable</em> is declared at least, you should directly check if it has a <code>truthy</code> value like shown above.</p>\n\n<p>Further read: <a href=\"http://typeofnan.blogspot.com/2011/01/typeof-is-fast.html\" rel=\"noreferrer\">http://typeofnan.blogspot.com/2011/01/typeof-is-fast.html</a></p>\n",
"source": "so",
"questionId": 5515310
},
{
"title": "Open a URL in a new tab (and not a new window) using JavaScript",
"body": "<p>Nothing an author can do can choose to open in a new tab instead of a new window. It is a <em>user preference</em>.</p>\n\n<p>CSS3 proposed <a href=\"http://www.w3.org/TR/2004/WD-css3-hyperlinks-20040224/#target-new\" rel=\"noreferrer\">target-new</a>, but <a href=\"http://www.w3.org/TR/2014/NOTE-css3-hyperlinks-20141014/\" rel=\"noreferrer\">the specification was abandoned</a>.</p>\n\n<p>The <strong>reverse</strong> is not true; by specifying dimensions for the window in the third argument of <code>window.open</code>, you can trigger a new window when the preference is for tabs.</p>\n",
"source": "so",
"questionId": 4907843
},
{
"title": "Why is using &quot;for...in&quot; with array iteration a bad idea?",
"body": "<p>The reason is that one construct:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>var a = []; // Create a new empty array.\r\na[5] = 5; // Perfectly legal JavaScript that resizes the array.\r\n\r\nfor (var i = 0; i &lt; a.length; i++) {\r\n // Iterate over numeric indexes from 0 to 5, as everyone expects.\r\n console.log(a[i]);\r\n}\r\n\r\n/* Will display:\r\n undefined\r\n undefined\r\n undefined\r\n undefined\r\n undefined\r\n 5\r\n*/</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>can sometimes be totally different from the other:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>var a = [];\r\na[5] = 5;\r\nfor (var x in a) {\r\n // Shows only the explicitly set index of \"5\", and ignores 0-4\r\n console.log(x);\r\n}\r\n\r\n/* Will display:\r\n 5\r\n*/</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>Also consider that <a href=\"http://en.wikipedia.org/wiki/JavaScript\" rel=\"noreferrer\">JavaScript</a> libraries might do things like this, which will affect any array you create:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>// Somewhere deep in your JavaScript library...\r\nArray.prototype.foo = 1;\r\n\r\n// Now you have no idea what the below code will do.\r\nvar a = [1, 2, 3, 4, 5];\r\nfor (var x in a){\r\n // Now foo is a part of EVERY array and \r\n // will show up here as a value of 'x'.\r\n console.log(x);\r\n}\r\n\r\n/* Will display:\r\n 0\r\n 1\r\n 2\r\n 3\r\n 4\r\n foo\r\n*/</code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"source": "so",
"questionId": 500504
},
{
"title": "Get the size of the screen, current web page and browser window",
"body": "<p>If you are using jQuery, you can get the size of the window or the document using jQuery methods:</p>\n\n<pre><code>$(window).height(); // returns height of browser viewport\n$(document).height(); // returns height of HTML document (same as pageHeight in screenshot)\n$(window).width(); // returns width of browser viewport\n$(document).width(); // returns width of HTML document (same as pageWidth in screenshot)\n</code></pre>\n\n<p>For screen size you can use the <code>screen</code> object in the following way:</p>\n\n<pre><code>screen.height;\nscreen.width;\n</code></pre>\n",
"source": "so",
"questionId": 3437786
},
{
"title": "Parse JSON in JavaScript?",
"body": "<p>Most browsers support <a href=\"http://msdn.microsoft.com/en-us/library/cc836466(v=vs.85).aspx\" rel=\"noreferrer\"><code>JSON.parse()</code></a>, which is defined in ECMA-262 5th Edition (the specification that JavaScript is based on). Its usage is simple:</p>\n\n<pre><code>var json = '{\"result\":true,\"count\":1}',\n obj = JSON.parse(json);\n\nalert(obj.count);\n</code></pre>\n\n<p>For the browsers that don't you can implement it using <a href=\"https://github.com/douglascrockford/JSON-js/blob/master/json2.js\" rel=\"noreferrer\">json2.js</a>.</p>\n\n<p>As noted in the comments, if you're already using jQuery, there is a <code>$.parseJSON</code> function that maps to <code>JSON.parse</code> if available or a form of <code>eval</code> in older browsers. However, this performs additional, unnecessary checks that are also performed by <code>JSON.parse</code>, so for the best all round performance I'd recommend using it like so:</p>\n\n<pre><code>var json = '{\"result\":true,\"count\":1}',\n obj = JSON &amp;&amp; JSON.parse(json) || $.parseJSON(json);\n</code></pre>\n\n<p>This will ensure you use native <code>JSON.parse</code> immediately, rather than having jQuery perform sanity checks on the string before passing it to the native parsing function.</p>\n",
"source": "so",
"questionId": 4935632
},
{
"title": "Iterate through object properties",
"body": "<p>Iterating over properties requires this additional <code>hasOwnProperty</code> check: </p>\n\n<pre><code>for (var property in object) {\n if (object.hasOwnProperty(property)) {\n // do stuff\n }\n}\n</code></pre>\n\n<p>It's necessary because an object's prototype contains additional properties for the object which are technically part of the object. These additional properties are inherited from the base object class, but are still properties of <code>object</code>.</p>\n\n<p><a href=\"https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty\" rel=\"noreferrer\"><code>hasOwnProperty</code></a> simply checks to see if this is a property specific to this class, and not one inherited from the base class.</p>\n",
"source": "so",
"questionId": 8312459
},
{
"title": "How do you check if a variable is an array in JavaScript?",
"body": "<p>There are several ways of checking if an variable is an array or not. The best solution is the one you have chosen.</p>\n\n<pre><code>variable.constructor === Array\n</code></pre>\n\n<p>This is the fastest method on Chrome, and most likely all other browsers. All arrays are objects, so checking the constructor property is a fast process for JavaScript engines.</p>\n\n<p>If you are having issues with finding out if an objects property is an array, you must first check if the property is there.</p>\n\n<pre><code>variable.prop &amp;&amp; variable.prop.constructor === Array\n</code></pre>\n\n<p>Some other ways are:</p>\n\n<pre><code>variable instanceof Array\n</code></pre>\n\n<p>This method runs about <s>1/3 the speed</s> as the first example. Still pretty solid, looks cleaner, if you're all about pretty code and not so much on performance. Note that checking for numbers does not work as <code>variable instanceof Number</code> always returns <code>false</code>. <strong>Update: <code>instanceof</code> now goes 2/3 the speed!</strong></p>\n\n<pre><code>Array.isArray(variable)\n</code></pre>\n\n<p>This last one is, in my opinion the ugliest, and it is one of the slowest. Running about 1/5 the speed as the first example. Array.prototype, is actually an array. you can read more about it here <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray\" rel=\"noreferrer\">https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray</a></p>\n\n<p><strong>So yet another update</strong></p>\n\n<pre><code>Object.prototype.toString.call(variable) === '[object Array]';\n</code></pre>\n\n<p>This guy is the slowest for trying to check for an Array. However, this is a one stop shop for any type you're looking for. However, since you're looking for an array, just use the fastest method above.</p>\n\n<p>Also, I ran some test: <a href=\"http://jsperf.com/instanceof-array-vs-array-isarray/33\" rel=\"noreferrer\">http://jsperf.com/instanceof-array-vs-array-isarray/33</a> So have some fun and check it out.</p>\n\n<p>Note: @EscapeNetscape has created another test as jsperf.com is down. <a href=\"http://jsben.ch/#/QgYAV\" rel=\"noreferrer\">http://jsben.ch/#/QgYAV</a> I wanted to make sure the original link stay for whenever jsperf comes back online.</p>\n",
"source": "so",
"questionId": 767486
},
{
"title": "What is the JavaScript version of sleep()?",
"body": "<h2>2017 update</h2>\n\n<p>Since 2009 when this question was asked, JavaScript has evolved significantly. All other answers are now obsolete or overly complicated. Here is the current best practice:</p>\n\n<pre><code>function sleep(ms) {\n return new Promise(resolve =&gt; setTimeout(resolve, ms));\n}\n\nasync function demo() {\n console.log('Taking a break...');\n await sleep(2000);\n console.log('Two second later');\n}\n\ndemo();\n</code></pre>\n\n<h3>This is it. <code>await sleep(&lt;duration&gt;)</code>.</h3>\n\n<p>You can try this code live <a href=\"https://runkit.com/dandv/57f770a7aed68d0014e7b660\" rel=\"noreferrer\">on Runkit</a>. Note that,</p>\n\n<ol>\n<li><code>await</code> can only be executed in functions prefixed with the <code>async</code> keyword. Runkit wraps your code in an async function before executing it.</li>\n<li><code>await</code> only pauses the current <code>async</code> function</li>\n</ol>\n\n<p>Two new JavaScript features helped write this actual \"sleep\" function:</p>\n\n<ul>\n<li><a href=\"https://ponyfoo.com/articles/es6-promises-in-depth\" rel=\"noreferrer\">Promises, a native feature of ES2015</a> (aka ES6). We also use <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions\" rel=\"noreferrer\">arrow functions</a> in the definition of the sleep function.</li>\n<li>The <a href=\"https://github.com/tc39/ecmascript-asyncawait\" rel=\"noreferrer\">upcoming</a> <a href=\"https://ponyfoo.com/articles/understanding-javascript-async-await\" rel=\"noreferrer\"><code>async/await</code></a> feature lets the code explicitly wait for a promise to settle.</li>\n</ul>\n\n<h2>Compatibility</h2>\n\n<ul>\n<li>promises are supported <a href=\"http://node.green/#Promise\" rel=\"noreferrer\">in Node v0.12+</a> and <a href=\"http://caniuse.com/#feat=promises\" rel=\"noreferrer\">widely supported in browsers</a>, except IE</li>\n<li><code>async</code>/<code>await</code> landed in V8 and has been <a href=\"https://developers.google.com/web/fundamentals/getting-started/primers/async-functions\" rel=\"noreferrer\">enabled by default since Chrome 55</a>\n\n<ul>\n<li>it landed <a href=\"https://blog.risingstack.com/async-await-node-js-7-nightly/\" rel=\"noreferrer\">in Node 7 in October 2016</a></li>\n<li>has also <a href=\"https://blog.nightly.mozilla.org/2016/11/01/async-await-support-in-firefox/\" rel=\"noreferrer\">landed in Firefox nightly in Nov 2016-Nov</a></li>\n</ul></li>\n</ul>\n\n<p>If for some reason you're using Node older than 7, or are targeting old browsers, <code>async</code>/<code>await</code> can still be used via <a href=\"https://babeljs.io/\" rel=\"noreferrer\">Babel</a> (a tool that will <a href=\"https://www.stevefenton.co.uk/2012/11/compiling-vs-transpiling/\" rel=\"noreferrer\">transpile</a> JavaScript + new features into plain old JavaScript), with the <a href=\"https://babeljs.io/docs/plugins/transform-async-to-generator/\" rel=\"noreferrer\"><code>transform-async-to-generator</code> plugin</a>. Run</p>\n\n<pre><code>npm install babel-cli --save\n</code></pre>\n\n<p>Create <code>.babelrc</code> with:</p>\n\n<pre><code>{\n \"plugins\": [\n \"transform-async-to-generator\",\n ]\n}\n</code></pre>\n\n<p>Then run your code with</p>\n\n<pre><code>node_modules/babel-cli/bin/babel-node.js sleep.js\n</code></pre>\n\n<p>But again, you don't need this if you're using Node 7 or later, or if you're targeting modern browsers.</p>\n",
"source": "so",
"questionId": 951021
},
{
"title": "Generating random whole numbers in JavaScript in a specific range?",
"body": "<p>There are some examples on the <a href=\"https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Math/random\" rel=\"noreferrer\">Mozilla Developer Network</a> page:</p>\n\n<pre><code>/**\n * Returns a random number between min (inclusive) and max (exclusive)\n */\nfunction getRandomArbitrary(min, max) {\n return Math.random() * (max - min) + min;\n}\n\n/**\n * Returns a random integer between min (inclusive) and max (inclusive)\n * Using Math.round() will give you a non-uniform distribution!\n */\nfunction getRandomInt(min, max) {\n return Math.floor(Math.random() * (max - min + 1)) + min;\n}\n</code></pre>\n\n<hr>\n\n<p>Here's the logic behind it. It's a simple rule of three:</p>\n\n<p><code>Math.random()</code> returns a <code>Number</code> between 0 (inclusive) and 1 (exclusive). So we have an interval like this:</p>\n\n<pre><code>[0 .................................... 1)\n</code></pre>\n\n<p>Now, we'd like a number between <code>min</code> (inclusive) and <code>max</code> (exclusive):</p>\n\n<pre><code>[0 .................................... 1)\n[min .................................. max)\n</code></pre>\n\n<p>We can use the <code>Math.random</code> to get the correspondent in the [min, max) interval. But, first we should factor a little bit the problem by subtracting <code>min</code> from the second interval:</p>\n\n<pre><code>[0 .................................... 1)\n[min - min ............................ max - min)\n</code></pre>\n\n<p>This gives:</p>\n\n<pre><code>[0 .................................... 1)\n[0 .................................... max - min)\n</code></pre>\n\n<p>We may now apply <code>Math.random</code> and then calculate the correspondent. Let's choose a random number:</p>\n\n<pre><code> Math.random()\n |\n[0 .................................... 1)\n[0 .................................... max - min)\n |\n x (what we need)\n</code></pre>\n\n<p>So, in order to find <code>x</code>, we would do:</p>\n\n<pre><code>x = Math.random() * (max - min);\n</code></pre>\n\n<p>Don't forget to add <code>min</code> back, so that we get a number in the [min, max) interval:</p>\n\n<pre><code>x = Math.random() * (max - min) + min;\n</code></pre>\n\n<p>That was the first function from MDN. The second one, returns an integer between <code>min</code> and <code>max</code>, both inclusive.</p>\n\n<p>Now for getting integers, you could use <code>round</code>, <code>ceil</code> or <code>floor</code>.</p>\n\n<p>You could use <code>Math.round(Math.random() * (max - min)) + min</code>, this however gives a non-even distribution. Both, <code>min</code> and <code>max</code> only have approximately half the chance to roll:</p>\n\n<pre><code>min...min+0.5...min+1...min+1.5 ... max-0.5....max\n└───┬───┘└────────┬───────┘└───── ... ─────┘└───┬──┘ ← Math.round()\n min min+1 max\n</code></pre>\n\n<p>With <code>max</code> excluded from the interval, it has an even less chance to roll than <code>min</code>.</p>\n\n<p>With <code>Math.floor(Math.random() * (max - min +1)) + min</code> you have a perfectly even distribution.</p>\n\n<pre><code>min.... min+1... min+2 ... max-1... max.... max+1 (is excluded from interval)\n| | | | | |\n└───┬───┘└───┬───┘└─── ... ┘└───┬───┘└───┬───┘ ← Math.floor()\n min min+1 max-1 max\n</code></pre>\n\n<p>You can't use <code>ceil()</code> and <code>-1</code> in that equation because <code>max</code> now had a slightly less chance to roll, but you can roll the (unwanted) <code>min-1</code> result too.</p>\n",
"source": "so",
"questionId": 1527803
},
{
"title": "JavaScript chop/slice/trim off last character in string",
"body": "<p>You can use the <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/substring\" rel=\"noreferrer\">substring</a> function:</p>\n\n<pre><code>var str = \"12345.00\";\nstr = str.substring(0, str.length - 1); // \"12345.0\"\n</code></pre>\n\n<p>This is the accepted answer, but as per the conversations below, the <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/slice\" rel=\"noreferrer\">slice</a> syntax is much clearer:</p>\n\n<pre><code>var str = \"12345.00\";\nstr = str.slice(0, -1); // \"12345.0\"\n</code></pre>\n",
"source": "so",
"questionId": 952924
},
{
"title": "Why does ++[[]][+[]]+[+[]] return the string &quot;10&quot;?",
"body": "<p>If we split it up, the mess is equal to:</p>\n\n<pre><code>++[[]][+[]]\n+\n[+[]]\n</code></pre>\n\n<p>In JavaScript, it is true that <code>+[] === 0</code>. <code>+</code> converts something into a number, and in this case it will come down to <code>+\"\"</code> or <code>0</code> (see specification details below).</p>\n\n<p>Therefore, we can simplify it (<code>++</code> has precendence over <code>+</code>):</p>\n\n<pre><code>++[[]][0]\n+\n[0]\n</code></pre>\n\n<p>Because <code>[[]][0]</code> means: get the first element from <code>[[]]</code>, it is true that:</p>\n\n<ul>\n<li><code>[[]][0]</code> returns the inner array (<code>[]</code>). Due to references it's wrong to say <code>[[]][0] === []</code>, but let's call the inner array <code>A</code> to avoid the wrong notation.</li>\n<li><code>++[[]][0] == A + 1</code>, since <code>++</code> means 'increment by one'.</li>\n<li><code>++[[]][0] === +(A + 1)</code>; in other words, it will always be a number (<code>+1</code> does not necessarily return a number, whereas <code>++</code> always does - thanks to Tim Down for pointing this out).</li>\n</ul>\n\n<p>Again, we can simplify the mess into something more legible. Let's substitute <code>[]</code> back for <code>A</code>:</p>\n\n<pre><code>+([] + 1)\n+\n[0]\n</code></pre>\n\n<p>In JavaScript, this is true as well: <code>[] + 1 === \"1\"</code>, because <code>[] == \"\"</code> (joining an empty array), so:</p>\n\n<ul>\n<li><code>+([] + 1) === +(\"\" + 1)</code>, and</li>\n<li><code>+(\"\" + 1) === +(\"1\")</code>, and</li>\n<li><code>+(\"1\") === 1</code></li>\n</ul>\n\n<p>Let's simplify it even more:</p>\n\n<pre><code>1\n+\n[0]\n</code></pre>\n\n<p>Also, this is true in JavaScript: <code>[0] == \"0\"</code>, because it's joining an array with one element. Joining will concatenate the elements separated by <code>,</code>. With one element, you can deduce that this logic will result in the first element itself.</p>\n\n<p>So, in the end we obtain (number + string = string):</p>\n\n<pre><code>1\n+\n\"0\"\n\n=== \"10\" // Yay!\n</code></pre>\n\n<hr>\n\n<p>Specification details for <code>+[]</code>:</p>\n\n<p>This is quite a maze, but to do <code>+[]</code>, first it is being converted to a string because that's what <code>+</code> says:</p>\n\n<blockquote>\n <p>11.4.6 Unary + Operator</p>\n \n <p>The unary + operator converts its operand to Number type.</p>\n \n <p>The production UnaryExpression : + UnaryExpression is evaluated as follows:</p>\n \n <ol>\n <li><p>Let expr be the result of evaluating UnaryExpression.</p></li>\n <li><p>Return ToNumber(GetValue(expr)).</p></li>\n </ol>\n</blockquote>\n\n<p><code>ToNumber()</code> says:</p>\n\n<blockquote>\n <p>Object</p>\n \n <p>Apply the following steps:</p>\n \n <ol>\n <li><p>Let primValue be ToPrimitive(input argument, hint String).</p></li>\n <li><p>Return ToString(primValue).</p></li>\n </ol>\n</blockquote>\n\n<p><code>ToPrimitive()</code> says:</p>\n\n<blockquote>\n <p>Object</p>\n \n <p>Return a default value for the Object. The default value of an object is retrieved by calling the [[DefaultValue]] internal method of the object, passing the optional hint PreferredType. The behaviour of the [[DefaultValue]] internal method is defined by this specification for all native ECMAScript objects in 8.12.8.</p>\n</blockquote>\n\n<p><code>[[DefaultValue]]</code> says:</p>\n\n<blockquote>\n <p>8.12.8 [[DefaultValue]] (hint)</p>\n \n <p>When the [[DefaultValue]] internal method of O is called with hint String, the following steps are taken:</p>\n \n <ol>\n <li><p>Let toString be the result of calling the [[Get]] internal method of object O with argument \"toString\".</p></li>\n <li><p>If IsCallable(toString) is true then,</p></li>\n </ol>\n \n <p>a. Let str be the result of calling the [[Call]] internal method of toString, with O as the this value and an empty argument list.</p>\n \n <p>b. If str is a primitive value, return str.</p>\n</blockquote>\n\n<p>The <code>.toString</code> of an array says:</p>\n\n<blockquote>\n <p>15.4.4.2 Array.prototype.toString ( )</p>\n \n <p>When the toString method is called, the following steps are taken:</p>\n \n <ol>\n <li><p>Let array be the result of calling ToObject on the this value.</p></li>\n <li><p>Let func be the result of calling the [[Get]] internal method of array with argument \"join\".</p></li>\n <li><p>If IsCallable(func) is false, then let func be the standard built-in method Object.prototype.toString (15.2.4.2).</p></li>\n <li><p>Return the result of calling the [[Call]] internal method of func providing array as the this value and an empty arguments list.</p></li>\n </ol>\n</blockquote>\n\n<p>So <code>+[]</code> comes down to <code>+\"\"</code>, because <code>[].join() === \"\"</code>.</p>\n\n<p>Again, the <code>+</code> is defined as:</p>\n\n<blockquote>\n <p>11.4.6 Unary + Operator</p>\n \n <p>The unary + operator converts its operand to Number type.</p>\n \n <p>The production UnaryExpression : + UnaryExpression is evaluated as follows:</p>\n \n <ol>\n <li><p>Let expr be the result of evaluating UnaryExpression.</p></li>\n <li><p>Return ToNumber(GetValue(expr)).</p></li>\n </ol>\n</blockquote>\n\n<p><code>ToNumber</code> is defined for <code>\"\"</code> as:</p>\n\n<blockquote>\n <p>The MV of StringNumericLiteral ::: [empty] is 0.</p>\n</blockquote>\n\n<p>So <code>+\"\" === 0</code>, and thus <code>+[] === 0</code>.</p>\n",
"source": "so",
"questionId": 7202157
},
{
"title": "How to move an element into another element?",
"body": "<p>You may want to use the <a href=\"http://api.jquery.com/appendTo/\" rel=\"noreferrer\"><code>appendTo</code></a> function (which adds to the end of the element):</p>\n\n<pre><code>$(\"#source\").appendTo(\"#destination\");\n</code></pre>\n\n<p>Alternatively you could use the <a href=\"http://api.jquery.com/prependTo/\" rel=\"noreferrer\"><code>prependTo</code></a> function (which adds to the beginning of the element):</p>\n\n<pre><code>$(\"#source\").prependTo(\"#destination\");\n</code></pre>\n\n<hr>\n\n<p>Example:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>$(\"#appendTo\").click(function() {\r\n $(\"#moveMeIntoMain\").appendTo($(\"#main\"));\r\n});\r\n$(\"#prependTo\").click(function() {\r\n $(\"#moveMeIntoMain\").prependTo($(\"#main\"));\r\n});</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>#main {\r\n border: 2px solid blue;\r\n min-height: 100px;\r\n}\r\n\r\n.moveMeIntoMain {\r\n border: 1px solid red;\r\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;script src=\"https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js\"&gt;&lt;/script&gt;\r\n&lt;div id=\"main\"&gt;main&lt;/div&gt;\r\n&lt;div id=\"moveMeIntoMain\" class=\"moveMeIntoMain\"&gt;move me to main&lt;/div&gt;\r\n\r\n&lt;button id=\"appendTo\"&gt;appendTo main&lt;/button&gt;\r\n&lt;button id=\"prependTo\"&gt;prependTo main&lt;/button&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"source": "so",
"questionId": 1279957
},
{
"title": "What is the purpose of the var keyword and when should I use it (or omit it)?",
"body": "<p>If you're in the global scope then there's no difference.</p>\n\n<p>If you're in a function then <strong><code>var</code></strong> will create a local variable, \"no var\" will look up the scope chain until it finds the variable or hits the global scope (at which point it will create it):</p>\n\n<pre><code>// These are both globals\nvar foo = 1;\nbar = 2;\n\nfunction()\n{\n var foo = 1; // Local\n bar = 2; // Global\n\n // Execute an anonymous function\n (function()\n {\n var wibble = 1; // Local\n foo = 2; // Inherits from scope above (creating a closure)\n moo = 3; // Global\n }())\n}\n</code></pre>\n\n<p>If you're not doing an assignment then you need to use <code>var</code>:</p>\n\n<pre><code>var x; // Declare x\n</code></pre>\n",
"source": "so",
"questionId": 1470488
},
{
"title": "Difference between == and === in JavaScript",
"body": "<p><code>===</code> and <code>!==</code> are strict comparison operators:</p>\n\n<blockquote>\n <p>JavaScript has both strict and\n type-converting equality comparison.\n For strict equality the objects being\n compared must have the same type and:</p>\n \n <ul>\n <li>Two strings are strictly equal when they have the same sequence of\n characters, same length, and same\n characters in corresponding positions.</li>\n <li>Two numbers are strictly equal when they are numerically equal (have\n the same number value). NaN is not\n equal to anything, including NaN.\n Positive and negative zeros are equal\n to one another.</li>\n <li>Two Boolean operands are strictly equal if both are true or\n both are false.</li>\n <li>Two objects are strictly equal if they refer to the same Object.</li>\n <li>Null and Undefined types are == (but not ===). [I.e. (Null==Undefined) is true but (Null===Undefined) is false]</li>\n </ul>\n</blockquote>\n\n<p><a href=\"https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Operators/Comparison_Operators\" rel=\"noreferrer\">Comparison Operators - MDC</a></p>\n",
"source": "so",
"questionId": 523643
},
{
"title": "How do I debug Node.js applications?",
"body": "<p>The <a href=\"http://en.wikipedia.org/wiki/V8_%28JavaScript_engine%29\" rel=\"noreferrer\">V8</a> debugger released as part of the Google <a href=\"http://code.google.com/p/chromedevtools/\" rel=\"noreferrer\">Chrome Developer Tools</a> can be used to debug Node.js scripts. A detailed explanation of how this works can be found in the <a href=\"https://github.com/nodejs/node/wiki/Using-Eclipse-as-Node-Applications-Debugger\" rel=\"noreferrer\">Node.js GitHub wiki</a>.</p>\n\n<p><strike>There is also <a href=\"http://github.com/smtlaissezfaire/ndb\" rel=\"noreferrer\">ndb</a>, a command line debugger written in Node.js itself.</strike></p>\n",
"source": "so",
"questionId": 1911015
},
{
"title": "Differences between lodash and underscore",
"body": "<p>I created Lo-Dash to provide more consistent cross-environment iteration support for arrays, strings, objects, and <code>arguments</code> objects<sup>1</sup>. It has since become a superset of Underscore, providing more consistent API behavior, more <a href=\"http://lodash.com\">features</a> (like AMD support, deep clone, and deep merge), more thorough <a href=\"http://lodash.com/docs\">documentation</a> and unit tests (tests which run in Node, Ringo, Rhino, Narwhal, PhantomJS, and browsers), better overall performance and optimizations for large arrays/object iteration, and more flexibility with <a href=\"http://lodash.com/\">custom builds</a> and template pre-compilation utilities.</p>\n\n<p>Because Lo-Dash is updated more frequently than Underscore, a <code>lodash underscore</code> build <a href=\"http://lodash.com/\">is provided</a> to ensure compatibility with the latest stable version of Underscore.</p>\n\n<p>At one point I was even given <a href=\"https://s3.amazonaws.com/f.cl.ly/items/2e0O0S010f2A3s1W283U/push_access.png?v=ba693725\">push access</a> to Underscore, in part because Lo-Dash is responsible for raising more than 30 issues; landing bug fixes, new features, &amp; perf gains in Underscore v1.4.x+.</p>\n\n<p>In addition there are at least 3 Backbone boilerplates that include Lo-Dash by default and Lo-Dash is now mentioned in Backbone’s official <a href=\"http://backbonejs.org/#downloads\">documentation</a>.</p>\n\n<p>Check out Kit Cambridge's post, <a href=\"http://kitcambridge.be/blog/say-hello-to-lo-dash/\">Say \"Hello\" to Lo-Dash</a>, for a deeper breakdown on the differences between Lo-Dash and Underscore.</p>\n\n<p>Footnotes:</p>\n\n<ol>\n<li>Underscore has inconsistent support for arrays, strings, objects, and <code>arguments</code> objects. In newer browsers, Underscore methods ignore <a href=\"http://www.2ality.com/2012/06/dense-arrays.html\">holes in arrays</a>, \"Objects\" methods iterate <code>arguments</code> objects, strings are treated as array-like, and methods correctly iterate functions (ignoring their \"prototype\" property) and objects (iterating shadowed properties like \"toString\" and \"valueOf\"), while in older browsers they will not. Also, Underscore methods like <code>_.clone</code> preserve holes in arrays, while others like <code>_.flatten</code> don't.</li>\n</ol>\n",
"source": "so",
"questionId": 13789618
},
{
"title": "How do I update each dependency in package.json to the latest version?",
"body": "<p>Looks like <a href=\"https://www.npmjs.org/package/npm-check-updates\" rel=\"noreferrer\">npm-check-updates</a> is the only way to make this happen now.</p>\n\n<pre><code>npm i -g npm-check-updates\nncu -u\nnpm install\n</code></pre>\n\n<hr>\n\n<p>On npm &lt;3.11:</p>\n\n<p>Simply change every dependency's version to <code>*</code>, then run <code>npm update --save</code>. (<strong>Note:</strong> <a href=\"https://github.com/npm/npm/issues/13555\" rel=\"noreferrer\">broken in recent (3.11) versions of npm</a>).</p>\n\n<p>Before:</p>\n\n<pre><code> \"dependencies\": {\n \"express\": \"*\",\n \"mongodb\": \"*\",\n \"underscore\": \"*\",\n \"rjs\": \"*\",\n \"jade\": \"*\",\n \"async\": \"*\"\n }\n</code></pre>\n\n<p>After:</p>\n\n<pre><code> \"dependencies\": {\n \"express\": \"~3.2.0\",\n \"mongodb\": \"~1.2.14\",\n \"underscore\": \"~1.4.4\",\n \"rjs\": \"~2.10.0\",\n \"jade\": \"~0.29.0\",\n \"async\": \"~0.2.7\"\n }\n</code></pre>\n\n<hr>\n\n<p>Of course, this is the blunt hammer of updating dependencies. It's fine if&mdash;as you said&mdash;the project is empty and nothing can break.</p>\n\n<p>On the other hand, if you're working in a more mature project, you probably want to verify that there are no breaking changes in your dependencies before upgrading.</p>\n\n<p>To see which modules are outdated, just run <a href=\"https://docs.npmjs.com/cli/outdated\" rel=\"noreferrer\"><code>npm outdated</code></a>. It will list any installed dependencies that have newer versions available.</p>\n",
"source": "so",
"questionId": 16073603
},
{
"title": "How can I format numbers as dollars currency string in JavaScript?",
"body": "<p>Ok, based on what you said, i'm using this:</p>\n\n<pre><code>var DecimalSeparator = Number(\"1.2\").toLocaleString().substr(1,1);\n\nvar AmountWithCommas = Amount.toLocaleString();\nvar arParts = String(AmountWithCommas).split(DecimalSeparator);\nvar intPart = arParts[0];\nvar decPart = (arParts.length &gt; 1 ? arParts[1] : '');\ndecPart = (decPart + '00').substr(0,2);\n\nreturn '£ ' + intPart + DecimalSeparator + decPart;\n</code></pre>\n\n<p>I'm open to improvement suggestions (i'd prefer not to include YUI just to do this :-) )\nI already know I should be detecting the \".\" instead of just using it as the decimal separator...</p>\n",
"source": "so",
"questionId": 149055
},
{
"title": "Creating a div element in jQuery",
"body": "<p>You can use <code>append</code> (to add at last position of parent) or <code>prepend</code> (to add at fist position of parent):</p>\n\n<pre><code>$('#parent').append('&lt;div&gt;hello&lt;/div&gt;'); \n// or\n$('&lt;div&gt;hello&lt;/div&gt;').appendTo('#parent');\n</code></pre>\n\n<p>Alternatively, you can use the <code>.html()</code> or <code>.add()</code> as mentioned in a <a href=\"https://stackoverflow.com/a/867941/59087\">different answer</a>.</p>\n\n\n",
"source": "so",
"questionId": 867916
},
{
"title": "What is the best way to detect a mobile device in jQuery?",
"body": "<p>Instead of using jQuery you can use simple JavaScript to detect it:</p>\n\n<pre><code>if( /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ) {\n // some code..\n}\n</code></pre>\n\n<p>Or you can combine them both to make it more accessible through jQuery...</p>\n\n<pre><code>$.browser.device = (/android|webos|iphone|ipad|ipod|blackberry|iemobile|opera mini/i.test(navigator.userAgent.toLowerCase()));\n</code></pre>\n\n<p>Now <code>$.browser</code> will return <code>\"device\"</code> for all above devices</p>\n\n<p>Note: <code>$.browser</code> removed on <a href=\"http://jquery.com/upgrade-guide/1.9/#jquery-browser-removed\" rel=\"noreferrer\"><strong>jQuery v1.9.1</strong></a>. But you can use this by using jQuery migration plugin <a href=\"https://stackoverflow.com/a/15072522/2724173\"><strong>Code</strong></a></p>\n\n<hr>\n\n<p>A more thorough version:</p>\n\n<pre><code>var isMobile = false; //initiate as false\n// device detection\nif(/(android|bb\\d+|meego).+mobile|avantgo|bada\\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|ipad|iris|kindle|Android|Silk|lge |maemo|midp|mmp|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i.test(navigator.userAgent) \n || /1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\\-(n|u)|c55\\/|capi|ccwa|cdm\\-|cell|chtm|cldc|cmd\\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\\-s|devi|dica|dmob|do(c|p)o|ds(12|\\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\\-|_)|g1 u|g560|gene|gf\\-5|g\\-mo|go(\\.w|od)|gr(ad|un)|haie|hcit|hd\\-(m|p|t)|hei\\-|hi(pt|ta)|hp( i|ip)|hs\\-c|ht(c(\\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\\-(20|go|ma)|i230|iac( |\\-|\\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\\/)|klon|kpt |kwc\\-|kyo(c|k)|le(no|xi)|lg( g|\\/(k|l|u)|50|54|\\-[a-w])|libw|lynx|m1\\-w|m3ga|m50\\/|ma(te|ui|xo)|mc(01|21|ca)|m\\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\\-2|po(ck|rt|se)|prox|psio|pt\\-g|qa\\-a|qc(07|12|21|32|60|\\-[2-7]|i\\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\\-|oo|p\\-)|sdk\\/|se(c(\\-|0|1)|47|mc|nd|ri)|sgh\\-|shar|sie(\\-|m)|sk\\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\\-|v\\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\\-|tdg\\-|tel(i|m)|tim\\-|t\\-mo|to(pl|sh)|ts(70|m\\-|m3|m5)|tx\\-9|up(\\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\\-|your|zeto|zte\\-/i.test(navigator.userAgent.substr(0,4))) { \n isMobile = true;\n}\n</code></pre>\n",
"source": "so",
"questionId": 3514784
},
{
"title": "How do I convert a string into an integer in JavaScript?",
"body": "<p>The simplest way would be to use the native <code>Number</code> function:</p>\n\n<pre><code>var x = Number(\"1000\")\n</code></pre>\n\n<p>If that doesn't work for you, then there are the <strong>parseInt</strong>, <strong>unary plus</strong>, <strong>parseFloat with floor</strong>, and <strong>Math.round</strong> methods.</p>\n\n<p>parseInt:</p>\n\n<pre><code>var x = parseInt(\"1000\", 10); // you want to use radix 10\n // so you get a decimal number even with a leading 0 and an old browser ([IE8, Firefox 20, Chrome 22 and older][1])\n</code></pre>\n\n<p>unary plus\nif your string is already in the form of an integer:</p>\n\n<pre><code>var x = +\"1000\";\n</code></pre>\n\n<p>if your string is or might be a float and you want an integer:</p>\n\n<pre><code>var x = Math.floor(\"1000.01\"); //floor automatically converts string to number\n</code></pre>\n\n<p>or, if you're going to be using Math.floor several times:</p>\n\n<pre><code>var floor = Math.floor;\nvar x = floor(\"1000.01\");\n</code></pre>\n\n<p>If you're the type who forgets to put the radix in when you call parseInt, you can use parseFloat and round it however you like. Here I use floor.</p>\n\n<pre><code>var floor = Math.floor;\nvar x = floor(parseFloat(\"1000.01\"));\n</code></pre>\n\n<p>Interestingly, Math.round (like Math.floor) will do a string to number conversion, so if you want the number rounded (or if you have an integer in the string), this is a great way, maybe my favorite:</p>\n\n<pre><code>var round = Math.round;\nvar x = round(\"1000\"); //equivalent to round(\"1000\",0)\n</code></pre>\n",
"source": "so",
"questionId": 1133770
},
{
"title": "Get selected value in dropdown list using JavaScript?",
"body": "<p>If you have a select element that looks like this:</p>\n\n<pre class=\"lang-html prettyprint-override\"><code>&lt;select id=\"ddlViewBy\"&gt;\n &lt;option value=\"1\"&gt;test1&lt;/option&gt;\n &lt;option value=\"2\" selected=\"selected\"&gt;test2&lt;/option&gt;\n &lt;option value=\"3\"&gt;test3&lt;/option&gt;\n&lt;/select&gt;\n</code></pre>\n\n<p>Running this code:</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>var e = document.getElementById(\"ddlViewBy\");\nvar strUser = e.options[e.selectedIndex].value;\n</code></pre>\n\n<p>Would make <code>strUser</code> be <code>2</code>. If what you actually want is <code>test2</code>, then do this:</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>var e = document.getElementById(\"ddlViewBy\");\nvar strUser = e.options[e.selectedIndex].text;\n</code></pre>\n\n<p>Which would make <code>strUser</code> be <code>test2</code></p>\n",
"source": "so",
"questionId": 1085801
},
{
"title": "Compare two dates with JavaScript",
"body": "<p>The <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date\" rel=\"noreferrer\">Date object</a> will do what you want - construct one for each date, then compare them using the <code>&gt;</code>, <code>&lt;</code>, <code>&lt;=</code> or <code>&gt;=</code>. </p>\n\n<p>The <code>==</code>, <code>!=</code>, <code>===</code>, and <code>!==</code> operators require you to use <code>date.getTime()</code> as in </p>\n\n<pre><code>var d1 = new Date();\nvar d2 = new Date(d1);\nvar same = d1.getTime() === d2.getTime();\nvar notSame = d1.getTime() !== d2.getTime();\n</code></pre>\n\n<p>to be clear just checking for equality directly with the data objects won't work</p>\n\n<pre><code>var d1 = new Date();\nvar d2 = new Date(d1);\n\nconsole.log(d1 == d2); // prints false (wrong!) \nconsole.log(d1 === d2); // prints false (wrong!)\nconsole.log(d1 != d2); // prints true (wrong!)\nconsole.log(d1 !== d2); // prints true (wrong!)\nconsole.log(d1.getTime() === d2.getTime()); // prints true (correct)\n</code></pre>\n\n<p>I suggest you use drop-downs or some similar constrained form of date entry rather than text boxes, though, lest you find yourself in input validation hell.</p>\n",
"source": "so",
"questionId": 492994
},
{
"title": "Where can I find documentation on formatting a date in JavaScript?",
"body": "<p>I love <em><a href=\"http://www.webdevelopersnotes.com/tips/html/10_ways_to_format_time_and_date_using_javascript.php3\" rel=\"noreferrer\">10 ways to format time and date using JavaScript</a></em> and <em><a href=\"http://www.elated.com/articles/working-with-dates/\" rel=\"noreferrer\">Working with Dates</a></em>.</p>\n\n<p>Basically, you have three methods and you have to combine the strings for yourself:</p>\n\n<pre><code>getDate() // Returns the date\ngetMonth() // Returns the month\ngetFullYear() // Returns the year\n</code></pre>\n\n<p>Example:</p>\n\n<pre><code>&lt;script type=\"text/javascript\"&gt;\n var d = new Date();\n var curr_date = d.getDate();\n var curr_month = d.getMonth() + 1; //Months are zero based\n var curr_year = d.getFullYear();\n console.log(curr_date + \"-\" + curr_month + \"-\" + curr_year);\n&lt;/script&gt;\n</code></pre>\n",
"source": "so",
"questionId": 1056728
},
{
"title": "When are you supposed to use escape instead of encodeURI / encodeURIComponent?",
"body": "<h1>escape()</h1>\n\n<p>Special characters are encoded with the exception of: @*_+-./</p>\n\n<p>The hexadecimal form for characters, whose code unit value is 0xFF or less, is a two-digit escape sequence: %xx. For characters with a greater code unit, the four-digit format %uxxxx is used.</p>\n\n<p><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/escape\" rel=\"noreferrer\">https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/escape</a></p>\n\n<h1>encodeURI()</h1>\n\n<p>Use encodeURI when you want a working URL. Make this call:</p>\n\n<pre><code>encodeURI(\"http://www.example.org/a file with spaces.html\")\n</code></pre>\n\n<p>to get:</p>\n\n<pre><code>http://www.example.org/a%20file%20with%20spaces.html\n</code></pre>\n\n<p>Don't call encodeURIComponent since it would destroy the URL and return</p>\n\n<pre><code>http%3A%2F%2Fwww.example.org%2Fa%20file%20with%20spaces.html\n</code></pre>\n\n<h1>encodeURIComponent()</h1>\n\n<p>Use encodeURIComponent when you want to encode the value of a URL parameter.</p>\n\n<pre><code>var p1 = encodeURIComponent(\"http://example.org/?a=12&amp;b=55\")\n</code></pre>\n\n<p>Then you may create the URL you need:</p>\n\n<pre><code>var url = \"http://example.net/?param1=\" + p1 + \"&amp;param2=99\";\n</code></pre>\n\n<p>And you will get this complete URL:</p>\n\n<p><code>http://example.net/?param1=http%3A%2F%2Fexample.org%2F%Ffa%3D12%26b%3D55&amp;param2=99</code></p>\n\n<p>Note that encodeURIComponent does not escape the <code>'</code> character. A common bug is to use it to create html attributes such as <code>href='MyUrl'</code>, which could suffer an injection bug. If you are constructing html from strings, either use <code>\"</code> instead of <code>'</code> for attribute quotes, or add an extra layer of encoding (<code>'</code> can be encoded as %27).</p>\n\n<p>For more information on this type of encoding you can check: <a href=\"http://en.wikipedia.org/wiki/Percent-encoding\" rel=\"noreferrer\">http://en.wikipedia.org/wiki/Percent-encoding</a></p>\n",
"source": "so",
"questionId": 75980
},
{
"title": "Copying array by value in JavaScript",
"body": "<p>Use this:</p>\n\n<pre><code>var newArray = oldArray.slice();\n</code></pre>\n\n<p>Basically, the <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice\" rel=\"noreferrer\">slice()</a> operation clones the array and returns the reference to the new array. Also note that:</p>\n\n<p>For references, strings and numbers (and not the actual object), slice copies object references into the new array. Both the original and new array refer to the same object. If a referenced object changes, the changes are visible to both the new and original arrays.</p>\n\n<p>Primitives such as strings and numbers are immutable so changes to the string or number are impossible. </p>\n",
"source": "so",
"questionId": 7486085
},
{
"title": "JavaScript post request like a form submit",
"body": "<pre><code>function post(path, params, method) {\n method = method || \"post\"; // Set method to post by default if not specified.\n\n // The rest of this code assumes you are not using a library.\n // It can be made less wordy if you use one.\n var form = document.createElement(\"form\");\n form.setAttribute(\"method\", method);\n form.setAttribute(\"action\", path);\n\n for(var key in params) {\n if(params.hasOwnProperty(key)) {\n var hiddenField = document.createElement(\"input\");\n hiddenField.setAttribute(\"type\", \"hidden\");\n hiddenField.setAttribute(\"name\", key);\n hiddenField.setAttribute(\"value\", params[key]);\n\n form.appendChild(hiddenField);\n }\n }\n\n document.body.appendChild(form);\n form.submit();\n}\n</code></pre>\n\n<p>Example:</p>\n\n<pre><code>post('/contact/', {name: 'Johnny Bravo'});\n</code></pre>\n\n<p><strong>EDIT</strong>: Since this has gotten upvoted so much, I'm guessing people will be copy-pasting this a lot. So I added the <code>hasOwnProperty</code> check to fix any inadvertent bugs.</p>\n",
"source": "so",
"questionId": 133925
},
{
"title": "Scroll to the top of the page using JavaScript/jQuery?",
"body": "<p>If you don't need the change to animate then you don't need to use any special plugins - I'd just use the native JavaScript window.scrollTo method -- passing in 0,0 will scroll the page to the top left instantly.</p>\n\n<pre><code>window.scrollTo(x-coord, y-coord);\n</code></pre>\n\n<p>Parameters </p>\n\n<ul>\n<li>x-coord is the pixel along the horizontal axis. </li>\n<li>y-coord is the pixel along the vertical axis. </li>\n</ul>\n",
"source": "so",
"questionId": 1144805
},
{
"title": "JavaScript check if variable exists (is defined/initialized)",
"body": "<p>The <code>typeof</code> operator will check if the variable is really undefined.</p>\n\n<pre><code>if (typeof variable === 'undefined') {\n // variable is undefined\n}\n</code></pre>\n\n<p>The <code>typeof</code> operator, unlike the other operators, doesn't throw a <em>ReferenceError</em> exception when used with an undeclared variable.</p>\n\n<p>However, do note that <code>typeof null</code> will return <code>\"object\"</code>. We have to be careful to avoid the mistake of initializing a variable to <code>null</code>. To be safe, this is what we could use instead:</p>\n\n<pre><code>if (typeof variable === 'undefined' || variable === null) {\n // variable is undefined or null\n}\n</code></pre>\n\n<hr>\n\n<p>For more info on using strict comparison <code>===</code> instead of simple equality <code>==</code>, see:<br><a href=\"https://stackoverflow.com/q/359494/584192\">Which equals operator (== vs ===) should be used in JavaScript comparisons?</a></p>\n",
"source": "so",
"questionId": 5113374
},
{
"title": "Trim string in JavaScript?",
"body": "<p>All browsers since IE9+ have <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/trim\" rel=\"noreferrer\"><code>trim()</code></a>.</p>\n\n<p>For those browsers who does not support <code>trim()</code>, you can use this polyfill from <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/Trim\" rel=\"noreferrer\">MDN</a>:</p>\n\n<pre><code>if (!String.prototype.trim) {\n (function() {\n // Make sure we trim BOM and NBSP\n var rtrim = /^[\\s\\uFEFF\\xA0]+|[\\s\\uFEFF\\xA0]+$/g;\n String.prototype.trim = function() {\n return this.replace(rtrim, '');\n };\n })();\n}\n</code></pre>\n\n<hr>\n\n<p>See this:</p>\n\n<pre><code>String.prototype.trim=function(){return this.replace(/^\\s+|\\s+$/g, '');};\n\nString.prototype.ltrim=function(){return this.replace(/^\\s+/,'');};\n\nString.prototype.rtrim=function(){return this.replace(/\\s+$/,'');};\n\nString.prototype.fulltrim=function(){return this.replace(/(?:(?:^|\\n)\\s+|\\s+(?:$|\\n))/g,'').replace(/\\s+/g,' ');};\n</code></pre>\n",
"source": "so",
"questionId": 498970
},
{
"title": "What is the purpose of Node.js module.exports and how do you use it?",
"body": "<p><a href=\"http://nodejs.org/api/modules.html#modules_module_exports\" rel=\"noreferrer\"><code>module.exports</code></a> is the object that's actually returned as the result of a <code>require</code> call.</p>\n\n<p>The <code>exports</code> variable is initially set to that same object (i.e. it's a shorthand \"alias\"), so in the module code you would usually write something like this:</p>\n\n<pre><code>var myFunc1 = function() { ... };\nvar myFunc2 = function() { ... };\nexports.myFunc1 = myFunc1;\nexports.myFunc2 = myFunc2;\n</code></pre>\n\n<p>to export (or \"expose\") the internally scoped functions <code>myFunc1</code> and <code>myFunc2</code>.</p>\n\n<p>And in the calling code you would use:</p>\n\n<pre><code>var m = require('mymodule');\nm.myFunc1();\n</code></pre>\n\n<p>where the last line shows how the result of <code>require</code> is (usually) just a plain object whose properties may be accessed.</p>\n\n<p>NB: if you overwrite <code>exports</code> then it will no longer refer to <code>module.exports</code>. So if you wish to assign a new object (or a function reference) to <code>exports</code> then you should also assign that new object to <code>module.exports</code></p>\n\n<hr>\n\n<p>It's worth noting that the name added to the <code>exports</code> object does not have to be the same as the module's internally scoped name for the value that you're adding, so you could have:</p>\n\n<pre><code>var myVeryLongInternalName = function() { ... };\nexports.shortName = myVeryLongInternalName;\n// add other objects, functions, as required\n</code></pre>\n\n<p>followed by:</p>\n\n<pre><code>var m = require('mymodule');\nm.shortName(); // invokes module.myVeryLongInternalName\n</code></pre>\n",
"source": "so",
"questionId": 5311334
},
{
"title": "How can I display a JavaScript object?",
"body": "<p>If you want to print the object for debugging purposes, I suggest instead installing <a href=\"http://getfirebug.com\" rel=\"noreferrer\">Firebug for Firefox</a> and using the code:</p>\n\n<pre><code>console.log(obj)\n</code></pre>\n",
"source": "so",
"questionId": 957537
},
{
"title": "How to Loop through plain JavaScript object with objects as members?",
"body": "<pre><code>for (var key in validation_messages) {\n // skip loop if the property is from prototype\n if (!validation_messages.hasOwnProperty(key)) continue;\n\n var obj = validation_messages[key];\n for (var prop in obj) {\n // skip loop if the property is from prototype\n if(!obj.hasOwnProperty(prop)) continue;\n\n // your code\n alert(prop + \" = \" + obj[prop]);\n }\n}\n</code></pre>\n",
"source": "so",
"questionId": 921789
},
{
"title": "Generate random number between two numbers in JavaScript",
"body": "<p>If you wanted to get between 1 and 6, you would calculate:</p>\n\n<pre><code>Math.floor(Math.random() * 6) + 1 \n</code></pre>\n\n<p>Where: </p>\n\n<ul>\n<li>1 is the start number </li>\n<li>6 is the number of possible results (1 + start <em>(6)</em> - end <em>(1)</em>)</li>\n</ul>\n",
"source": "so",
"questionId": 4959975
},
{
"title": "What is the best way to add options to a select from as a JS object with jQuery?",
"body": "<p>Same as other answers, in jQuery fashion:</p>\n\n<pre><code>$.each(selectValues, function(key, value) { \n $('#mySelect')\n .append($(\"&lt;option&gt;&lt;/option&gt;\")\n .attr(\"value\",key)\n .text(value)); \n});\n</code></pre>\n",
"source": "so",
"questionId": 170986
},
{
"title": "What is TypeScript and why would I use it in place of JavaScript?",
"body": "<blockquote>\n <p>I originally wrote this answer when Typescript was still\n hot-off-the-presses. Five years later, this is an OK overview, but look \n at <a href=\"https://stackoverflow.com/a/35048303/6521\">Lodewijk's answer</a> below for more depth</p>\n</blockquote>\n\n<h2>1000ft view...</h2>\n\n<p><a href=\"http://www.typescriptlang.org\" rel=\"noreferrer\">TypeScript</a> is a superset of JavaScript which primarily provides optional static typing, classes and interfaces. One of the big benefits is to enable IDEs to provide a richer environment for spotting common errors <em>as you type the code</em>.</p>\n\n<p>To get an idea of what I mean, watch <a href=\"http://channel9.msdn.com/posts/Anders-Hejlsberg-Introducing-TypeScript\" rel=\"noreferrer\">Microsoft's introductory video</a> on the language.</p>\n\n<p>For a large JavaScript project, adopting TypeScript might result in more robust software, while still being deployable where a regular JavaScript application would run.</p>\n\n<p>It is open source, but you only get the clever Intellisense as you type if you use a supported IDE. Initially, this was only Microsoft's Visual Studio (also noted in blog post from <a href=\"http://tirania.org/blog/archive/2012/Oct-01.html\" rel=\"noreferrer\">Miguel de Icaza</a>). These days, <a href=\"https://github.com/Microsoft/TypeScript/wiki/TypeScript-Editor-Support\" rel=\"noreferrer\">other IDEs offer TypeScript support too</a>.</p>\n\n<h2>Are there other technologies like it?</h2>\n\n<p>There's <a href=\"http://coffeescript.org/\" rel=\"noreferrer\">CoffeeScript</a>, but that really serves a different purpose. IMHO, CoffeeScript provides readability for humans, but TypeScript also provides deep readability for <em>tools</em> through its optional static typing (see this <a href=\"http://www.hanselman.com/blog/WhyDoesTypeScriptHaveToBeTheAnswerToAnything.aspx\" rel=\"noreferrer\">recent blog post</a> for a little more critique). There's also <a href=\"http://en.wikipedia.org/wiki/Dart_%28programming_language%29\" rel=\"noreferrer\">Dart</a> but that's a full on replacement for JavaScript (though it <a href=\"http://www.dartlang.org/docs/dart-up-and-running/contents/ch04-tools-dart2js.html\" rel=\"noreferrer\">can produce JavaScript code</a>)</p>\n\n<h2>Example</h2>\n\n<p>As an example, here's some TypeScript (you can play with this in the <a href=\"http://www.typescriptlang.org/Playground/\" rel=\"noreferrer\">TypeScript Playground</a>)</p>\n\n<pre><code>class Greeter {\n greeting: string;\n constructor (message: string) {\n this.greeting = message;\n }\n greet() {\n return \"Hello, \" + this.greeting;\n }\n} \n</code></pre>\n\n<p>And here's the JavaScript it would produce</p>\n\n<pre><code>var Greeter = (function () {\n function Greeter(message) {\n this.greeting = message;\n }\n Greeter.prototype.greet = function () {\n return \"Hello, \" + this.greeting;\n };\n return Greeter;\n})();\n</code></pre>\n\n<p>Notice how the TypeScript defines the type of member variables and class method parameters. This is removed when translating to JavaScript, but used by the IDE and compiler to spot errors, like passing a numeric type to the constructor.</p>\n\n<p>It's also capable of inferring types which aren't explicitly declared, for example, it would determine the <code>greet()</code> method returns a string.</p>\n\n<h2>Debugging Typescript</h2>\n\n<p>Many browsers and IDEs offer direct debugging support through sourcemaps. See this Stack Overflow question for more details: <a href=\"https://stackoverflow.com/questions/12711826/debugging-typescript-code-with-visual-studio\">Debugging TypeScript code with Visual Studio</a></p>\n\n<h2>Want to know more?</h2>\n\n<p>I originally wrote this answer when Typescript was still hot-off-the-presses. Check out <a href=\"https://stackoverflow.com/a/35048303/6521\">Lodewijk's answer</a> to this question for some more current detail.</p>\n",
"source": "so",
"questionId": 12694530
},
{
"title": "Deleting array elements in JavaScript - delete vs splice",
"body": "<p><code>delete</code> will delete the object property, but will not reindex the array or update its length. This makes it appears as if it is undefined:</p>\n\n<pre><code>&gt; myArray = ['a', 'b', 'c', 'd']\n [\"a\", \"b\", \"c\", \"d\"]\n&gt; delete myArray[0]\n true\n&gt; myArray[0]\n undefined\n</code></pre>\n\n<p>Note that it is not in fact set to the value <code>undefined</code>, rather the property is removed from the array, making it <em>appear</em> undefined. The Chrome dev tools make this distinction clear by printing <code>empty</code> when logging the array.</p>\n\n<pre><code>&gt; myArray[0]\n undefined\n&gt; myArray\n [empty, \"b\", \"c\", \"d\"]\n</code></pre>\n\n<p><a href=\"https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/splice\" rel=\"noreferrer\"><code>myArray.splice(start, deleteCount)</code></a> actually removes the element, reindexes the array, and changes its length.</p>\n\n<pre><code>&gt; myArray = ['a', 'b', 'c', 'd']\n [\"a\", \"b\", \"c\", \"d\"]\n&gt; myArray.splice(0, 2)\n [\"a\", \"b\"]\n&gt; myArray\n [\"c\", \"d\"]\n</code></pre>\n",
"source": "so",
"questionId": 500606
},
{
"title": "How to manage a redirect request after a jQuery Ajax call",
"body": "<p>The solution that was eventually implemented was to use a wrapper for the callback function of the Ajax call and in this wrapper check for the existence of a specific element on the returned HTML chunk. If the element was found then the wrapper executed a redirection. If not, the wrapper forwarded the call to the actual callback function. </p>\n\n<p>For example, our wrapper function was something like:</p>\n\n<pre><code>function cbWrapper(data, funct){\n if($(\"#myForm\", data).length &gt; 0)\n top.location.href=\"login.htm\";//redirection\n else\n funct(data);\n}\n</code></pre>\n\n<p>Then, when making the Ajax call we used something like:</p>\n\n<pre><code>$.post(\"myAjaxHandler\", \n {\n param1: foo,\n param2: bar\n },\n function(data){\n cbWrapper(data, myActualCB);\n }, \n \"html\"\n);\n</code></pre>\n\n<p>This worked for us because all Ajax calls always returned HTML inside a DIV element that we use to replace a piece of the page. Also, we only needed to redirect to the login page.</p>\n",
"source": "so",
"questionId": 199099
},
{
"title": "How to efficiently count the number of keys/properties of an object in JavaScript?",
"body": "<p>To do this in any ES5-compatible environment, such as <a href=\"http://nodejs.org\">Node</a>, Chrome, IE 9+, FF 4+, or Safari 5+:</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>Object.keys(obj).length\n</code></pre>\n\n<ul>\n<li><a href=\"http://kangax.github.com/es5-compat-table/\">Browser compatibility</a></li>\n<li><a href=\"https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object/keys\">Object.keys documentation</a> \n<ul>\n<li>(includes a method you can add to non-ECMA5 browsers)</li>\n</ul></li>\n</ul>\n",
"source": "so",
"questionId": 126100
},
{
"title": "How do I check if an object has a property in JavaScript?",
"body": "<p>I'm really confused by the answers that have been given - most of them are just outright incorrect. Of course you can have object properties that have undefined, null, or false values. So simply reducing the property check to <code>typeof this[property]</code> or, even worse, <code>x.key</code> will give you completely misleading results.</p>\n\n<p>It depends on what you're looking for. If you want to know if an object physically contains a property (and it is not coming from somewhere up on the prototype chain) then <code>object.hasOwnProperty</code> is the way to go. All modern browsers support it. (It was missing in older versions of Safari - 2.0.1 and older - but those versions of the browser are rarely used any more.)</p>\n\n<p>If what you're looking for is if an object has a property on it that is iterable (when you iterate over the properties of the object, it will appear) then doing: <code>prop in object</code> will give you your desired effect.</p>\n\n<p>Since using <code>hasOwnProperty</code> is probably what you want, and considering that you may want a fallback method, I present to you the following solution:</p>\n\n<pre><code>var obj = {\n a: undefined,\n b: null,\n c: false\n};\n\n// a, b, c all found\nfor ( var prop in obj ) {\n document.writeln( \"Object1: \" + prop );\n}\n\nfunction Class(){\n this.a = undefined;\n this.b = null;\n this.c = false;\n}\n\nClass.prototype = {\n a: undefined,\n b: true,\n c: true,\n d: true,\n e: true\n};\n\nvar obj2 = new Class();\n\n// a, b, c, d, e found\nfor ( var prop in obj2 ) {\n document.writeln( \"Object2: \" + prop );\n}\n\nfunction hasOwnProperty(obj, prop) {\n var proto = obj.__proto__ || obj.constructor.prototype;\n return (prop in obj) &amp;&amp;\n (!(prop in proto) || proto[prop] !== obj[prop]);\n}\n\nif ( Object.prototype.hasOwnProperty ) {\n var hasOwnProperty = function(obj, prop) {\n return obj.hasOwnProperty(prop);\n }\n}\n\n// a, b, c found in modern browsers\n// b, c found in Safari 2.0.1 and older\nfor ( var prop in obj2 ) {\n if ( hasOwnProperty(obj2, prop) ) {\n document.writeln( \"Object2 w/ hasOwn: \" + prop );\n }\n}\n</code></pre>\n\n<p>The above is a working, cross-browser, solution to <code>hasOwnProperty</code>, with one caveat: It is unable to distinguish between cases where an identical property is on the prototype and on the instance - it just assumes that it's coming from the prototype. You could shift it to be more lenient or strict, based upon your situation, but at the very least this should be more helpful.</p>\n",
"source": "so",
"questionId": 135448
},
{
"title": "How to convert decimal to hex in JavaScript?",
"body": "<p>Convert a number to a hexadecimal string with:</p>\n\n<pre><code>hexString = yourNumber.toString(16);\n</code></pre>\n\n<p>and reverse the process with:</p>\n\n<pre><code>yourNumber = parseInt(hexString, 16);\n</code></pre>\n",
"source": "so",
"questionId": 57803
},
{
"title": "Serializing to JSON in jQuery",
"body": "<p><a href=\"https://github.com/douglascrockford/JSON-js\" rel=\"noreferrer\">JSON-js</a> - JSON in JavaScript.</p>\n\n<p>To convert an object to a string, use <code>JSON.stringify</code>:</p>\n\n<pre><code>var json_text = JSON.stringify(your_object, null, 2);\n</code></pre>\n\n<p>To convert a JSON string to object, use <code>JSON.parse</code>:</p>\n\n<pre><code>var your_object = JSON.parse(json_text);\n</code></pre>\n\n<p>It was recently recommended by <a href=\"http://ejohn.org/blog/ecmascript-5-strict-mode-json-and-more/\" rel=\"noreferrer\">John Resig</a>:</p>\n\n<blockquote>\n <p>...PLEASE start migrating\n your JSON-using applications over to\n Crockford's json2.js. It is fully\n compatible with the ECMAScript 5\n specification and gracefully degrades\n if a native (faster!) implementation\n exists.</p>\n \n <p>In fact, I just landed a change in jQuery yesterday that utilizes the\n JSON.parse method if it exists, now\n that it has been completely specified.</p>\n</blockquote>\n\n<p>I tend to trust what he says on JavaScript matters :)</p>\n\n<p><a href=\"http://caniuse.com/json\" rel=\"noreferrer\">Newer browsers</a> support the <a href=\"http://ecma262-5.com/ELS5_Section_15.htm#Section_15.12\" rel=\"noreferrer\">JSON object</a> natively. The current version of Crockford's JSON library will only define <code>JSON.stringify</code> and <code>JSON.parse</code> if they're not already defined, leaving any browser native implementation intact.</p>\n",
"source": "so",
"questionId": 191881
},
{
"title": "How to format a JavaScript date",
"body": "<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function formatDate(date) {\r\n var monthNames = [\r\n \"January\", \"February\", \"March\",\r\n \"April\", \"May\", \"June\", \"July\",\r\n \"August\", \"September\", \"October\",\r\n \"November\", \"December\"\r\n ];\r\n\r\n var day = date.getDate();\r\n var monthIndex = date.getMonth();\r\n var year = date.getFullYear();\r\n\r\n return day + ' ' + monthNames[monthIndex] + ' ' + year;\r\n}\r\n\r\nconsole.log(formatDate(new Date())); // show current date-time in console</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>You can edit the array <code>monthNames</code> to use Jan, Feb, Mar, etc..</p>\n",
"source": "so",
"questionId": 3552461
},
{
"title": "jQuery get specific option tag text",
"body": "<p>It's looking for an element with id <code>list</code> which has a property <code>value</code> equal to 2. What you want is the <code>option</code> child of the <code>list</code>.</p>\n\n<pre><code>$(\"#list option[value='2']\").text()\n</code></pre>\n",
"source": "so",
"questionId": 196684
},
{
"title": "Convert JavaScript String to be all lower case?",
"body": "<pre><code>var lowerCaseName = \"Your Name\".toLowerCase();\n</code></pre>\n",
"source": "so",
"questionId": 154862
},
{
"title": "Why don&#39;t self-closing script tags work?",
"body": "<p>XHTML 1 specification says:</p>\n\n<p><a href=\"http://www.w3.org/TR/xhtml1/#C_3\" rel=\"noreferrer\">С.3. Element Minimization and Empty Element Content</a></p>\n\n<blockquote>\n <p>Given an empty instance of an element whose content model is not <code>EMPTY</code> (for example, an empty title or paragraph) do not use the minimized form (e.g. use <code>&lt;p&gt; &lt;/p&gt;</code> and not <code>&lt;p /&gt;</code>).</p>\n</blockquote>\n\n<p><a href=\"http://www.w3.org/TR/xhtml1/dtds.html#a_dtd_XHTML-1.0-Strict\" rel=\"noreferrer\">XHTML DTD</a> specifies script tags as:</p>\n\n<pre><code>&lt;!-- script statements, which may include CDATA sections --&gt;\n&lt;!ELEMENT script (#PCDATA)&gt;\n</code></pre>\n",
"source": "so",
"questionId": 69913
},
{
"title": "jQuery document.createElement equivalent?",
"body": "<p>here's your example in \"one\" line.</p>\n\n<pre><code>this.$OuterDiv = $('&lt;div&gt;&lt;/div&gt;')\n .hide()\n .append($('&lt;table&gt;&lt;/table&gt;')\n .attr({ cellSpacing : 0 })\n .addClass(\"text\")\n )\n;\n</code></pre>\n\n<hr>\n\n<p><em>Update</em>: I thought I'd update this post since it still gets quite a bit of traffic. In the comments below there's some discussion about <code>$(\"&lt;div&gt;\")</code> vs <code>$(\"&lt;div&gt;&lt;/div&gt;\")</code> vs <code>$(document.createElement('div'))</code> as a way of creating new elements, and which is \"best\".</p>\n\n<p>I put together <a href=\"http://jsbin.com/elula3\" rel=\"noreferrer\">a small benchmark</a>, and here's roughly the results of repeating the above options 100,000 times:</p>\n\n<p><strong>jQuery 1.4, 1.5, 1.6</strong></p>\n\n<pre><code> Chrome 11 Firefox 4 IE9\n&lt;div&gt; 440ms 640ms 460ms\n&lt;div&gt;&lt;/div&gt; 420ms 650ms 480ms\ncreateElement 100ms 180ms 300ms\n</code></pre>\n\n<p><strong>jQuery 1.3</strong></p>\n\n<pre><code> Chrome 11\n&lt;div&gt; 770ms\n&lt;div&gt;&lt;/div&gt; 3800ms\ncreateElement 100ms\n</code></pre>\n\n<p><strong>jQuery 1.2</strong></p>\n\n<pre><code> Chrome 11\n&lt;div&gt; 3500ms\n&lt;div&gt;&lt;/div&gt; 3500ms\ncreateElement 100ms\n</code></pre>\n\n<p>I think it's no big surprise, but <code>document.createElement</code> is the fastest method. Of course, before you go off and start refactoring your entire codebase, remember that the differences we're talking about here (in all but the archaic versions of jQuery) equate to about an extra 3 milliseconds <em>per thousand elements</em>. </p>\n\n<p><strong>Update 2</strong></p>\n\n<p>Updated for jQuery 1.7.2 and put the benchmark on JSBen.ch which is probably a bit more scientific than my primitive benchmarks, plus it can be crowdsourced now!</p>\n\n<p><a href=\"http://jsben.ch/#/ARUtz\" rel=\"noreferrer\">http://jsben.ch/#/ARUtz</a></p>\n",
"source": "so",
"questionId": 268490
},
{
"title": "Preview an image before it is uploaded",
"body": "<p>Please take a look at the sample code below:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function readURL(input) {\r\n\r\n if (input.files &amp;&amp; input.files[0]) {\r\n var reader = new FileReader();\r\n\r\n reader.onload = function(e) {\r\n $('#blah').attr('src', e.target.result);\r\n }\r\n\r\n reader.readAsDataURL(input.files[0]);\r\n }\r\n}\r\n\r\n$(\"#imgInp\").change(function() {\r\n readURL(this);\r\n});</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;script src=\"https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js\"&gt;&lt;/script&gt;\r\n&lt;form id=\"form1\" runat=\"server\"&gt;\r\n &lt;input type='file' id=\"imgInp\" /&gt;\r\n &lt;img id=\"blah\" src=\"#\" alt=\"your image\" /&gt;\r\n&lt;/form&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>Also, you can <a href=\"http://jsfiddle.net/LvsYc/\" rel=\"noreferrer\">try this sample here</a>.</p>\n",
"source": "so",
"questionId": 4459379
},
{
"title": "Where should I put &lt;script&gt; tags in HTML markup?",
"body": "<p>Here's what happens when a browser loads a website with a <code>&lt;script&gt;</code> tag on it:</p>\n\n<ol>\n<li>Fetch the HTML page (e.g. index.html)</li>\n<li>Begin parsing the HTML</li>\n<li>The parser encounters a <code>&lt;script&gt;</code> tag referencing an external script file.</li>\n<li>The browser requests the script file. Meanwhile, the parser blocks and stops parsing the other HTML on your page.</li>\n<li>After some time the script is downloaded and subsequently executed.</li>\n<li>The parser continues parsing the rest of the HTML document.</li>\n</ol>\n\n<p>Step 4 causes a bad user experience. Your website basically stops loading until you've downloaded all scripts. If there's one thing that users hate it's waiting for a website to load.</p>\n\n<h2>Why does this even happen?</h2>\n\n<p>Any script can insert its own HTML via <code>document.write()</code> or other DOM manipulations. This implies that the parser has to wait until the script has been downloaded &amp; executed before it can safely parse the rest of the document. After all, the script <em>could</em> have inserted its own HTML in the document.</p>\n\n<p>However, most javascript developers no longer manipulate the DOM <em>while</em> the document is loading. Instead, they wait until the document has been loaded before modifying it. For example:</p>\n\n<pre><code>&lt;!-- index.html --&gt;\n&lt;html&gt;\n &lt;head&gt;\n &lt;title&gt;My Page&lt;/title&gt;\n &lt;script type=\"text/javascript\" src=\"my-script.js\"&gt;&lt;/script&gt;\n &lt;/head&gt;\n &lt;body&gt;\n &lt;div id=\"user-greeting\"&gt;Welcome back, user&lt;/div&gt;\n &lt;/body&gt;\n&lt;/html&gt;\n</code></pre>\n\n<p>Javascript:</p>\n\n<pre><code>// my-script.js\ndocument.addEventListener(\"DOMContentLoaded\", function() { \n // this function runs when the DOM is ready, i.e. when the document has been parsed\n document.getElementById(\"user-greeting\").textContent = \"Welcome back, Bart\";\n});\n</code></pre>\n\n<p>Because your browser does not know my-script.js isn't going to modify the document until it has been downloaded &amp; executed, the parser stops parsing.</p>\n\n<h2>Antiquated recommendation</h2>\n\n<p>The old approach to solving this problem was to put <code>&lt;script&gt;</code> tags at the bottom of your <code>&lt;body&gt;</code>, because this ensures the parser isn't blocked until the very end. </p>\n\n<p>This approach has its own problem: the browser cannot start downloading the scripts until the entire document is parsed. For larger websites with large scripts &amp; stylesheets, being able to download the script as soon as possible is very important for performance. If your website doesn't load within 2 seconds, people will go to another website.</p>\n\n<p>In an optimal solution, the browser would start downloading your scripts as soon as possible, while at the same time parsing the rest of your document.</p>\n\n<h2>The modern approach</h2>\n\n<p>Today, browsers support the <code>async</code> and <code>defer</code> attributes on scripts. These attributes tell the browser it's safe to continue parsing while the scripts are being downloaded.</p>\n\n<h3>async</h3>\n\n<pre><code>&lt;script type=\"text/javascript\" src=\"path/to/script1.js\" async&gt;&lt;/script&gt;\n&lt;script type=\"text/javascript\" src=\"path/to/script2.js\" async&gt;&lt;/script&gt;\n</code></pre>\n\n<p>Scripts with the async attribute are executed asynchronously. This means the script is executed as soon as it's downloaded, without blocking the browser in the meantime.<br>\nThis implies that it's possible to script 2 is downloaded &amp; executed before script 1. </p>\n\n<p>According to <a href=\"http://caniuse.com/#feat=script-async\" rel=\"noreferrer\">http://caniuse.com/#feat=script-async</a>, 90% of all browsers support this.</p>\n\n<h3>defer</h3>\n\n<pre><code>&lt;script type=\"text/javascript\" src=\"path/to/script1.js\" defer&gt;&lt;/script&gt;\n&lt;script type=\"text/javascript\" src=\"path/to/script2.js\" defer&gt;&lt;/script&gt;\n</code></pre>\n\n<p>Scripts with the defer attribute are executed in order (i.e. first script 1, then script 2). This also does not block the browser.</p>\n\n<p>Unlike async scripts, defer scripts are only executed after the entire document has been loaded.</p>\n\n<p>According to <a href=\"http://caniuse.com/#feat=script-defer\" rel=\"noreferrer\">http://caniuse.com/#feat=script-defer</a>, 90% of all browsers support this. 92% support it at least partially.</p>\n\n<p>An important note on browser compatibility: in some circumstances IE &lt;= 9 may execute deferred scripts out of order. If you need to support those browsers, please read <a href=\"https://github.com/h5bp/lazyweb-requests/issues/42\" rel=\"noreferrer\">this</a> first!</p>\n\n<h1>Conclusion</h1>\n\n<p>The current state-of-the-art is to put scripts in the <code>&lt;head&gt;</code> tag and use the <code>async</code> or <code>defer</code> attributes. This allows your scripts to be downloaded asap without blocking your browser.</p>\n\n<p>The good thing is that your website should still load correctly on the 20% of browsers that do not support these attributes while speeding up the other 80%.</p>\n",
"source": "so",
"questionId": 436411
},
{
"title": "Determine whether an array contains a value",
"body": "<pre><code>var contains = function(needle) {\n // Per spec, the way to identify NaN is that it is not equal to itself\n var findNaN = needle !== needle;\n var indexOf;\n\n if(!findNaN &amp;&amp; typeof Array.prototype.indexOf === 'function') {\n indexOf = Array.prototype.indexOf;\n } else {\n indexOf = function(needle) {\n var i = -1, index = -1;\n\n for(i = 0; i &lt; this.length; i++) {\n var item = this[i];\n\n if((findNaN &amp;&amp; item !== item) || item === needle) {\n index = i;\n break;\n }\n }\n\n return index;\n };\n }\n\n return indexOf.call(this, needle) &gt; -1;\n};\n</code></pre>\n\n<p>You can use it like this:</p>\n\n<pre><code>var myArray = [0,1,2],\n needle = 1,\n index = contains.call(myArray, needle); // true\n</code></pre>\n\n<p><a href=\"http://codepen.io/anon/pen/mVRNaJ\" rel=\"noreferrer\">CodePen validation/usage</a></p>\n",
"source": "so",
"questionId": 1181575
},
{
"title": "Is JavaScript a pass-by-reference or pass-by-value language?",
"body": "<p>It's interesting in Javascript. Consider this example:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function changeStuff(a, b, c)\r\n{\r\n a = a * 10;\r\n b.item = \"changed\";\r\n c = {item: \"changed\"};\r\n}\r\n\r\nvar num = 10;\r\nvar obj1 = {item: \"unchanged\"};\r\nvar obj2 = {item: \"unchanged\"};\r\n\r\nchangeStuff(num, obj1, obj2);\r\n\r\nconsole.log(num);\r\nconsole.log(obj1.item); \r\nconsole.log(obj2.item);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>This produces the output:</p>\n\n<pre><code>10\nchanged\nunchanged\n</code></pre>\n\n<p>If it was pure pass by value, then changing <code>obj1.item</code> would have no effect on the <code>obj1</code> outside of the function.\nIf it was pure pass by reference, then everything would have changed. <code>num</code> would be <code>100</code>, and <code>obj2.item</code> would read <code>\"changed\"</code>.</p>\n\n<p>Instead, the situation is that the item passed in is passed by value. But the item that is passed by value is <em>itself</em> a reference.\nTechnically, this is called <a href=\"http://en.wikipedia.org/wiki/Evaluation_strategy#Call_by_sharing\" rel=\"noreferrer\">call-by-sharing</a>.</p>\n\n<p>In practical terms, this means that if you change the parameter itself (as with <code>num</code> and <code>obj2</code>), that won't affect the item that was fed into the parameter.\nBut if you change the INTERNALS of the parameter, that will propagate back up (as with <code>obj1</code>).</p>\n",
"source": "so",
"questionId": 518000
},
{
"title": "How to print a number with commas as thousands separators in JavaScript",
"body": "<p>I used the idea from Kerry's answer, but simplified it since I was just looking for something simple for my specific purpose. Here is what I did:</p>\n\n<pre><code>const numberWithCommas = (x) =&gt; {\n return x.toString().replace(/\\B(?=(\\d{3})+(?!\\d))/g, \",\");\n}\n</code></pre>\n\n<p>This is all you really need to know.</p>\n\n<p>@Neils Bom asked how the regex works. My explanation is sort of long. It won't fit in the comments and I don't know where else to put it so I am doing it here. If anyone has any other suggestions for where to put it, please let me know.</p>\n\n<p>The regex uses 2 lookahead assertions: a positive one to look for any point in the string that has a multiple of 3 digits in a row after it, and a negative assertion to make sure that point only has exactly a multiple of 3 digits. The replacement expression puts a comma there.</p>\n\n<p>For example, if you pass it \"123456789.01\", the positive assertion will match every spot to the left of the 7 (since \"789\" is a multiple of 3 digits, \"678\" is a multiple of 3 digits, \"567\", etc.). The negative assertion checks that the multiple of 3 digits does not have any digits after it. \"789\" has a period after it so it is exactly a multiple of 3 digits, so a comma goes there. \"678\" is a multiple of 3 digits but it has a \"9\" after it, so those 3 digits are part of a group of 4, and a comma does not go there. Similarly for \"567\". \"456789\" is 6 digits, which is a multiple of 3, so a comma goes before that. \"345678\" is a multiple of 3, but it has a \"9\" after it, so no comma goes there. And so on. The \"\\B\" keeps the regex from putting a comma at the beginning of the string.</p>\n\n<p>@neu-rah mentioned that this function adds commas in undesirable places if there are more than 3 digits after the decimal point. If this is a problem, you can use this function:</p>\n\n<pre><code>const numberWithCommas = (x) =&gt; {\n var parts = x.toString().split(\".\");\n parts[0] = parts[0].replace(/\\B(?=(\\d{3})+(?!\\d))/g, \",\");\n return parts.join(\".\");\n}\n</code></pre>\n",
"source": "so",
"questionId": 2901102
},
{
"title": "Safely turning a JSON string into an object",
"body": "<p><a href=\"https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse\" rel=\"noreferrer\"><code>JSON.parse(jsonString)</code></a> is a pure JavaScript approach so long as you can guarantee a reasonably modern browser.</p>\n",
"source": "so",
"questionId": 45015
},
{
"title": "Trigger a button click with JavaScript on the Enter key in a text box",
"body": "<p>In jQuery, the following would work:</p>\n\n<pre><code>$(\"#id_of_textbox\").keyup(function(event) {\n if (event.keyCode === 13) {\n $(\"#id_of_button\").click();\n }\n});\n</code></pre>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>$(\"#pw\").keyup(function(event) {\r\n if (event.keyCode === 13) {\r\n $(\"#myButton\").click();\r\n }\r\n});\r\n\r\n$(\"#myButton\").click(function() {\r\n alert(\"Button code executed.\");\r\n});</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;script src=\"https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js\"&gt;&lt;/script&gt;\r\n\r\nUsername:&lt;input id=\"username\" type=\"text\"&gt;&lt;br&gt;\r\nPassword:&amp;nbsp;&lt;input id=\"pw\" type=\"password\"&gt;&lt;br&gt;\r\n&lt;button id=\"myButton\"&gt;Submit&lt;/button&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>Or in plain JavaScript, the following would work:</p>\n\n<pre><code>document.getElementById(\"id_of_textbox\")\n .addEventListener(\"keyup\", function(event) {\n event.preventDefault();\n if (event.keyCode === 13) {\n document.getElementById(\"id_of_button\").click();\n }\n});\n</code></pre>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>document.getElementById(\"pw\")\r\n .addEventListener(\"keyup\", function(event) {\r\n event.preventDefault();\r\n if (event.keyCode === 13) {\r\n document.getElementById(\"myButton\").click();\r\n }\r\n});\r\n\r\nfunction buttonCode()\r\n{\r\n alert(\"Button code executed.\");\r\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;script src=\"https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js\"&gt;&lt;/script&gt;\r\n\r\nUsername:&lt;input id=\"username\" type=\"text\"&gt;&lt;br&gt;\r\nPassword:&amp;nbsp;&lt;input id=\"pw\" type=\"password\"&gt;&lt;br&gt;\r\n&lt;button id=\"myButton\" onclick=\"buttonCode()\"&gt;Submit&lt;/button&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"source": "so",
"questionId": 155188
},
{
"title": "Check if a variable is a string in JavaScript",
"body": "<p>You can use <code>typeof</code> operator:</p>\n\n<pre><code>var booleanValue = true; \nvar numericalValue = 354;\nvar stringValue = \"This is a String\";\nalert(typeof booleanValue) // displays \"boolean\"\nalert(typeof numericalValue) // displays \"number\"\nalert(typeof stringValue) // displays \"string\"\n</code></pre>\n\n<p>Example from <a href=\"http://hubpages.com/hub/javascript-typeof-operator\" rel=\"noreferrer\">this webpage</a>. (Example was slightly modified though).</p>\n\n<p><a href=\"http://www.webreference.com/javascript/reference/core_ref/ops.html\" rel=\"noreferrer\">Here's</a> reference for <code>typeof</code> operator.</p>\n",
"source": "so",
"questionId": 4059147
},
{
"title": "How can I add new array elements at the beginning of an array in JavaScript?",
"body": "<p>Use <a href=\"https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/unshift\" rel=\"noreferrer\"><code>unshift</code></a>. It's like <a href=\"https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/push\" rel=\"noreferrer\"><code>push</code></a>, except it adds elements to the beginning of the array instead of the end.</p>\n\n<ul>\n<li><code>unshift</code>/<code>push</code> - add an element to the beginning/end of an array</li>\n<li><code>shift</code>/<code>pop</code> - remove and return the first/last element of and array</li>\n</ul>\n\n<p>A simple diagram...</p>\n\n<pre class=\"lang-none prettyprint-override\"><code> unshift -&gt; array &lt;- push\n shift &lt;- array -&gt; pop\n</code></pre>\n\n<p>and chart:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code> add remove start end\n push X X\n pop X X\nunshift X X\n shift X X\n</code></pre>\n\n<p>Check out the <a href=\"https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array\" rel=\"noreferrer\">MDN Array documentation</a>. Virtually every language that has the ability to push/pop elements from an array will also have the ability to unshift/shift (sometimes called <code>push_front</code>/<code>pop_front</code>) elements, you should never have to implement these yourself.</p>\n",
"source": "so",
"questionId": 8073673
},
{
"title": "Writing files in Node.js",
"body": "<p>There are a lot of details in the <a href=\"http://nodejs.org/docs/latest/api/fs.html\" rel=\"noreferrer\">filesystem API</a>. The most common way (as far as I know) is:</p>\n\n<pre><code>var fs = require('fs');\nfs.writeFile(\"/tmp/test\", \"Hey there!\", function(err) {\n if(err) {\n return console.log(err);\n }\n\n console.log(\"The file was saved!\");\n}); \n</code></pre>\n",
"source": "so",
"questionId": 2496710
},
{
"title": "window.onload vs $(document).ready()",
"body": "<p>The <code>ready</code> event occurs after the HTML document has been loaded, while the <code>onload</code> event occurs later, when all content (e.g. images) also has been loaded.</p>\n\n<p>The <code>onload</code> event is a standard event in the DOM, while the <code>ready</code> event is specific to jQuery. The purpose of the <code>ready</code> event is that it should occur as early as possible after the document has loaded, so that code that adds functionality to the elements in the page doesn't have to wait for all content to load.</p>\n",
"source": "so",
"questionId": 3698200
},
{
"title": "Generate random string/characters in JavaScript",
"body": "<p>I think this will work for you:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function makeid() {\r\n var text = \"\";\r\n var possible = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789\";\r\n\r\n for (var i = 0; i &lt; 5; i++)\r\n text += possible.charAt(Math.floor(Math.random() * possible.length));\r\n\r\n return text;\r\n}\r\n\r\nconsole.log(makeid());</code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"source": "so",
"questionId": 1349404
},
{
"title": "Stop setInterval call in JavaScript",
"body": "<p><code>setInterval()</code> returns an interval ID, which you can pass to <code>clearInterval()</code>:</p>\n\n<pre><code>var refreshIntervalId = setInterval(fname, 10000);\n\n/* later */\nclearInterval(refreshIntervalId);\n</code></pre>\n\n<p>See the docs for <a href=\"https://developer.mozilla.org/en/DOM/window.setInterval\" rel=\"noreferrer\"><code>setInterval()</code></a> and <a href=\"https://developer.mozilla.org/en/DOM/window.clearInterval\" rel=\"noreferrer\"><code>clearInterval()</code></a>.</p>\n",
"source": "so",
"questionId": 109086
}
]
},
{
"Author": "JSTips",
"url": "https://github.com/loverajoel/jstips",
"format": "html",
"tips": [
{
"title": 'Inserting an item into an existing array',
"body": `<p>Inserting an item into an existing array is a daily common task. You can add elements to the end of an array using push, to the beginning using unshift, or to the middle using splice.</p>
<p>Those are known methods, but it doesn't mean there isn't a more performant way. Here we go:</p>
<h2 id="addinganelementattheend">Adding an element at the end</h2>
<p>Adding an element at the end of the array is easy with push(), but it can be done in different ways.</p>
<pre><code class="javascript language-javascript">
var arr = [1,2,3,4,5];
var arr2 = [];
arr.push(6);
arr[arr.length] = 6;
arr2 = arr.concat([6]);
</code></pre>
<p>Both first methods modify the original array. Don't believe me? Check the <a href="http://jsperf.com/push-item-inside-an-array">jsperf</a></p>
<h3 id="performanceonmobile">Performance on mobile :</h3>
<h4 id="androidv422">Android (v4.2.2)</h4>
<ol>
<li><em>arr.push(6);</em> and <em>arr[arr.length] = 6;</em> have the same performance // 3 319 694 ops/sec</li>
<li><em>arr2 = arr.concat([6]);</em> 50.61 % slower than the other two methods</li>
</ol>
<h4 id="chromemobilev3300">Chrome Mobile (v33.0.0)</h4>
<ol>
<li><em>arr[arr.length] = 6;</em> // 6 125 975 ops/sec</li>
<li><em>arr.push(6);</em> 66.74 % slower</li>
<li><em>arr2 = arr.concat([6]);</em> 87.63 % slower</li>
</ol>
<h4 id="safarimobilev9">Safari Mobile (v9)</h4>
<ol>
<li><em>arr[arr.length] = 6;</em> // 7 452 898 ops/sec</li>
<li><em>arr.push(6);</em> 40.19 % slower</li>
<li><em>arr2 = arr.concat([6]);</em> 49.78 % slower</li>
</ol>
<pre><code class="javascript language-javascript">
Final victor
1. arr[arr.length] = 6; // with an average of 5 632 856 ops/sec
2. arr.push(6); // 35.64 % slower
3. arr2 = arr.concat([6]); // 62.67 % slower
</code></pre>
<h3 id="performanceondesktop">Performance on desktop</h3>
<h4 id="chromev4802564">Chrome (v48.0.2564)</h4>
<ol>
<li><em>arr[arr.length] = 6;</em> // 21 602 722 ops/sec</li>
<li><em>arr.push(6);</em> 61.94 % slower</li>
<li><em>arr2 = arr.concat([6]);</em> 87.45 % slower</li>
</ol>
<h4 id="firefoxv44">Firefox (v44)</h4>
<ol>
<li><em>arr.push(6);</em> // 56 032 805 ops/sec</li>
<li><em>arr[arr.length] = 6;</em> 0.52 % slower</li>
<li><em>arr2 = arr.concat([6]);</em> 87.36 % slower</li>
</ol>
<h4 id="iev11">IE (v11)</h4>
<ol>
<li><em>arr[arr.length] = 6;</em> // 67 197 046 ops/sec</li>
<li><em>arr.push(6);</em> 39.61 % slower</li>
<li><em>arr2 = arr.concat([6]);</em> 93.41 % slower</li>
</ol>
<h4 id="operav350206668">Opera (v35.0.2066.68)</h4>
<ol>
<li><em>arr[arr.length] = 6;</em> // 30 775 071 ops/sec</li>
<li><em>arr.push(6);</em> 71.60 % slower</li>
<li><em>arr2 = arr.concat([6]);</em> 83.70 % slower</li>
</ol>
<h4 id="safariv903">Safari (v9.0.3)</h4>
<ol>
<li><em>arr.push(6);</em> // 42 670 978 ops/sec</li>
<li><em>arr[arr.length] = 6;</em> 0.80 % slower</li>
<li><em>arr2 = arr.concat([6]);</em> 76.07 % slower</li>
</ol>
<pre><code class="javascript language-javascript">
Final victor
1. arr[arr.length] = 6; // with an average of 42 345 449 ops/sec
2. arr.push(6); // 34.66 % slower
3. arr2 = arr.concat([6]); // 85.79 % slower
</code></pre>
<h2 id="addanelementatthebeginning">Add an element at the beginning</h2>
<p>Now if we are trying to add an item to the beginning of the array:</p>
<pre><code class="javascript language-javascript">
var arr = [1,2,3,4,5];
arr.unshift(0);
[0].concat(arr);
</code></pre>
<p>Here is a little more detail: unshift edits the original array; concat returns a new array. <a href="http://jsperf.com/unshift-item-inside-an-array">jsperf</a></p>
<h3 id="performanceonmobile-1">Performance on mobile :</h3>
<h4 id="androidv422-1">Android (v4.2.2)</h4>
<ol>
<li><em>[0].concat(arr);</em> // 1 808 717 ops/sec</li>
<li><em>arr.unshift(0);</em> 97.85 % slower</li>
</ol>
<h4 id="chromemobilev3300-1">Chrome Mobile (v33.0.0)</h4>
<ol>
<li><em>[0].concat(arr);</em> // 1 269 498 ops/sec</li>
<li><em>arr.unshift(0);</em> 99.86 % slower</li>
</ol>
<h4 id="safarimobilev9-1">Safari Mobile (v9)</h4>
<ol>
<li><em>arr.unshift(0);</em> // 3 250 184 ops/sec</li>
<li><em>[0].concat(arr);</em> 33.67 % slower</li>
</ol>
<pre><code class="javascript language-javascript">
Final victor
1. [0].concat(arr); // with an average of 4 972 622 ops/sec
2. arr.unshift(0); // 64.70 % slower
</code></pre>
<h3 id="performanceondesktop-1">Performance on desktop</h3>
<h4 id="chromev4802564-1">Chrome (v48.0.2564)</h4>
<ol>
<li><em>[0].concat(arr);</em> // 2 656 685 ops/sec</li>
<li><em>arr.unshift(0);</em> 96.77 % slower</li>
</ol>
<h4 id="firefoxv44-1">Firefox (v44)</h4>
<ol>
<li><em>[0].concat(arr);</em> // 8 039 759 ops/sec</li>
<li><em>arr.unshift(0);</em> 99.72 % slower</li>
</ol>
<h4 id="iev11-1">IE (v11)</h4>
<ol>
<li><em>[0].concat(arr);</em> // 3 604 226 ops/sec</li>
<li><em>arr.unshift(0);</em> 98.31 % slower</li>
</ol>
<h4 id="operav350206668-1">Opera (v35.0.2066.68)</h4>
<ol>
<li><em>[0].concat(arr);</em> // 4 102 128 ops/sec</li>
<li><em>arr.unshift(0);</em> 97.44 % slower</li>
</ol>
<h4 id="safariv903-1">Safari (v9.0.3)</h4>
<ol>
<li><em>arr.unshift(0);</em> // 12 356 477 ops/sec</li>
<li><em>[0].concat(arr);</em> 15.17 % slower</li>
</ol>
<pre><code class="javascript language-javascript">
Final victor
1. [0].concat(arr); // with an average of 6 032 573 ops/sec
2. arr.unshift(0); // 78.65 % slower
</code></pre>
<h2 id="addanelementinthemiddle">Add an element in the middle</h2>
<p>Adding items in the middle of an array is easy with splice, and it's the most performant way to do it.</p>
<pre><code class="javascript language-javascript">
var items = ['one', 'two', 'three', 'four'];
items.splice(items.length / 2, 0, 'hello');
</code></pre>
<p>I tried to run these tests in various Browsers and OS and the results were similar. I hope these tips will be useful for you and encourage to perform your own tests!</p>`,
},
{
"title": 'Improve Nested Conditionals',
"body": `<p>How can we improve and make a more efficient nested "if" statement in javascript?</p>
<pre><code class="javascript language-javascript">
if (color) {
if (color === 'black') {
printBlackBackground();
} else if (color === 'red') {
printRedBackground();
} else if (color === 'blue') {
printBlueBackground();
} else if (color === 'green') {
printGreenBackground();
} else {
printYellowBackground();
}
}
</code></pre>
<p>One way to improve the nested <code>if</code> statement would be using the <code>switch</code> statement. Although it is less verbose and is more ordered, it's not recommended to use it because it's so difficult to debug errors. Here's <a href="https://toddmotto.com/deprecating-the-switch-statement-for-object-literals">why</a>.</p>
<pre><code class="javascript language-javascript">switch(color) {
case 'black':
printBlackBackground();
break;
case 'red':
printRedBackground();
break;
case 'blue':
printBlueBackground();
break;
case 'green':
printGreenBackground();
break;
default:
printYellowBackground();
}
</code></pre>
<p>But what if we have a conditional with several checks in each statement? In this case, if we want it less verbose and more ordered, we can use the conditional <code>switch</code>.
If we pass <code>true</code> as a parameter to the <code>switch</code> statement, it allows us to put a conditional in each case.</p>
<pre><code class="javascript language-javascript">switch(true) {
case (typeof color === 'string' &amp;&amp; color === 'black'):
printBlackBackground();
break;
case (typeof color === 'string' &amp;&amp; color === 'red'):
printRedBackground();
break;
case (typeof color === 'string' &amp;&amp; color === 'blue'):
printBlueBackground();
break;
case (typeof color === 'string' &amp;&amp; color === 'green'):
printGreenBackground();
break;
case (typeof color === 'string' &amp;&amp; color === 'yellow'):
printYellowBackground();
break;
}
</code></pre>
<p>If refactoring is an option, we can try to simplify the functions themselves. For example instead of having a function for each background color we could have an function that takes the color as an argument.</p>
<pre><code class="javascript language-javascript">function printBackground(color) {
if (!color || typeof color !== 'string') {
return; // Invalid color, return immediately
}
}
</code></pre>
<p>But if refactoring is not an option, we must always avoid having several checks in every condition and avoid using <code>switch</code> as much as possible. We also must take into account that the most efficient way to do this is through an <code>object</code>.</p>
<pre><code class="javascript language-javascript">var colorObj = {
'black': printBlackBackground,
'red': printRedBackground,
'blue': printBlueBackground,
'green': printGreenBackground,
'yellow': printYellowBackground
};
if (color in colorObj) {
colorObj[color]();
}
</code></pre>
<p>Here you can find more information about <a href="http://www.nicoespeon.com/en/2015/01/oop-revisited-switch-in-js/">this</a>.</p>`,
},
{
"title": 'Sorting strings with accented characters',
"body": `<p>Javascript has a native method <strong><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort">sort</a></strong> that allows sorting arrays. Doing a simple <code>array.sort()</code> will treat each array entry as a string and sort it alphabetically. Also you can provide your <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort#Parameters">own custom sorting</a> function.</p>
<pre><code class="javascript language-javascript">
['Shanghai', 'New York', 'Mumbai', 'Buenos Aires'].sort();
// ["Buenos Aires", "Mumbai", "New York", "Shanghai"]
</code></pre>
<p>But when you try order an array of non ASCII characters like this <code>['é', 'a', 'ú', 'c']</code>, you will obtain a strange result <code>['c', 'e', 'á', 'ú']</code>. That happens because sort works only with the English language.</p>
<p>See the next example:</p>
<pre><code class="javascript language-javascript">
// Spanish
['único','árbol', 'cosas', 'fútbol'].sort();
// ["cosas", "fútbol", "árbol", "único"] // bad order
// German
['Woche', 'wöchentlich', 'wäre', 'Wann'].sort();
// ["Wann", "Woche", "wäre", "wöchentlich"] // bad order
</code></pre>
<p>Fortunately, there are two ways to overcome this behavior <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/localeCompare">localeCompare</a> and <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Collator">Intl.Collator</a> provided by ECMAScript Internationalization API.</p>
<blockquote>
<p>Both methods have their own custom parameters in order to configure it to work adequately.</p>
</blockquote>
<h3 id="usinglocalecompare">Using <code>localeCompare()</code></h3>
<pre><code class="javascript language-javascript">
['único','árbol', 'cosas', 'fútbol'].sort(function (a, b) {
return a.localeCompare(b);
});
// ["árbol", "cosas", "fútbol", "único"]
['Woche', 'wöchentlich', 'wäre', 'Wann'].sort(function (a, b) {
return a.localeCompare(b);
});
// ["Wann", "wäre", "Woche", "wöchentlich"]
</code></pre>
<h3 id="usingintlcollator">Using <code>Intl.Collator()</code></h3>
<pre><code class="javascript language-javascript">
['único','árbol', 'cosas', 'fútbol'].sort(Intl.Collator().compare);
// ["árbol", "cosas", "fútbol", "único"]
['Woche', 'wöchentlich', 'wäre', 'Wann'].sort(Intl.Collator().compare);
// ["Wann", "wäre", "Woche", "wöchentlich"]
</code></pre>
<ul>
<li>For each method you can customize the location.</li>
<li>According to <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/localeCompare#Performance">Firefox</a> Intl.Collator is faster when comparing large numbers of strings.</li>
</ul>
<p>So when you are working with arrays of strings in a language other than English, remember to use this method to avoid unexpected sorting.</p>`,
},
{
"title": 'Differences between "undefined" and "null"',
"body": `<ul>
<li><p><code>undefined</code> means a variable has not been declared, or has been declared but has not yet been assigned a value</p></li>
<li><p><code>null</code> is an assignment value that means "no value"</p></li>
<li><p>Javascript sets unassigned variables with a default value of <code>undefined</code></p></li>
<li><p>Javascript never sets a value to <code>null</code>. It is used by programmers to indicate that a <code>var</code> has no value.</p></li>
<li><p><code>undefined</code> is not valid in JSON while <code>null</code> is</p></li>
<li><p><code>undefined</code> typeof is <code>undefined</code></p></li>
<li><p><code>null</code> typeof is an <code>object</code>. <a href="http://www.2ality.com/2013/10/typeof-null.html">Why?</a></p></li>
<li><p>Both are primitives</p></li>
<li><p>Both are <a href="https://developer.mozilla.org/en-US/docs/Glossary/Falsy">falsy</a>
(<code>Boolean(undefined) // false</code>, <code>Boolean(null) // false</code>)</p></li>
<li><p>You can know if a variable is <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/undefined">undefined</a></p>
<pre><code class="javascript language-javascript">typeof variable === "undefined"
</code></pre></li>
<li><p>You can check if a variable is <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/null">null</a></p>
<pre><code class="javascript language-javascript">variable === null
</code></pre></li>
<li><p>The <strong>equality</strong> operator considers them equal, but the <strong>identity</strong> doesn't</p>
<pre><code class="javascript language-javascript">null == undefined // true
null === undefined // false
</code></pre></li>
</ul>`,
},
{
"title": 'Writing a single method for arrays and a single element',
"body": `<p>Rather than writing separate methods to handle an array and a single element parameter, write your functions so they can handle both. This is similar to how some of jQuery’s functions work (<code>css</code> will modify everything matched by the selector).</p>
<p>You just have to concat everything into an array first. <code>Array.concat</code> will accept an array or a single element.</p>
<pre><code class="language-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">printUpperCase</span>(<span class="hljs-params">words</span>) </span>{
<span class="hljs-keyword">var</span> elements = [].concat(words || []);
<span class="hljs-keyword">for</span> (<span class="hljs-keyword">var</span> i = <span class="hljs-number">0</span>; i &lt; elements.length; i++) {
<span class="hljs-built_in">console</span>.log(elements[i].toUpperCase());
}
}
</code></pre>
<p><code>printUpperCase</code> is now ready to accept a single node or an array of nodes as its parameter. It also avoids the potential <code>TypeError</code> that would be thrown if no parameter was passed.</p>
<pre><code class="language-javascript">printUpperCase(<span class="hljs-string">"cactus"</span>);
<span class="hljs-comment">// =&gt; CACTUS</span>
printUpperCase([<span class="hljs-string">"cactus"</span>, <span class="hljs-string">"bear"</span>, <span class="hljs-string">"potato"</span>]);
<span class="hljs-comment">// =&gt; CACTUS</span>
<span class="hljs-comment">// BEAR</span>
<span class="hljs-comment">// POTATO</span>
</code></pre>`,
},
{
"title": 'use strict and get lazy',
"body": `<p>Strict-mode JavaScript makes it easier for the developer to write “secure” JavaScript.</p>
<p>By default, JavaScript allows the programmer to be pretty careless, for example, by not requiring us to declare our variables with “var” when we first introduce them. While this may seem like a convenience to the unseasoned developer, it’s also the source of many errors when a variable name is misspelled or accidentally referred to out of its scope.</p>
<p>Programmers like to make the computer do the boring stuff for us, and automatically check our work for mistakes. That’s what the JavaScript “use strict” directive allows us to do, by turning our mistakes into JavaScript errors.</p>
<p>We add this directive either by adding it at the top of a js file:</p>
<pre><code class="language-javascript"><span class="hljs-comment">// Whole-script strict mode syntax</span>
<span class="hljs-pi">"use strict"</span>;
<span class="hljs-keyword">var</span> v = <span class="hljs-string">"Hi! I'm a strict mode script!"</span>;
</code></pre>
<p>or inside a function:</p>
<pre><code class="language-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">f</span>(<span class="hljs-params"></span>)
</span>{
<span class="hljs-comment">// Function-level strict mode syntax</span>
<span class="hljs-pi"> 'use strict'</span>;
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">nested</span>(<span class="hljs-params"></span>) </span>{ <span class="hljs-keyword">return</span> <span class="hljs-string">"And so am I!"</span>; }
<span class="hljs-keyword">return</span> <span class="hljs-string">"Hi! I'm a strict mode function! "</span> + nested();
}
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">f2</span>(<span class="hljs-params"></span>) </span>{ <span class="hljs-keyword">return</span> <span class="hljs-string">"I'm not strict."</span>; }
</code></pre>
<p>By including this directive in a JavaScript file or function, we will direct the JavaScript engine to execute in strict mode which disables a bunch of behaviors that are usually undesirable in larger JavaScript projects. Among other things, strict mode changes the following behaviors:</p>
<ul>
<li>Variables can only be introduced when they are preceded with “var”</li>
<li>Attempting to write to read-only properties generates a noisy error</li>
<li>You have to call constructors with the “new” keyword</li>
<li>“this” is not implicitly bound to the global object</li>
<li>Very limited use of eval() allowed</li>
<li>Protects you from using reserved words or future reserved words as variable names</li>
</ul>
<p>Strict mode is great for new projects, but can be challenging to introduce into older projects that don’t already use it in most places. It also can be problematic if your build chain concatenates all your js files into one big file, as this may cause all files to execute in strict mode.</p>
<p>It is not a statement, but a literal expression, ignored by earlier versions of JavaScript.<br>
Strict mode is supported in:</p>
<ul>
<li>Internet Explorer from version 10.</li>
<li>Firefox from version 4.</li>
<li>Chrome from version 13.</li>
<li>Safari from version 5.1.</li>
<li>Opera from version 12.</li>
</ul>
<p><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode">See MDN for a fuller description of strict mode</a>.</p>`,
},
{
"title": 'Converting a Node List to an Array',
"body": `<p>The <code>querySelectorAll</code> method returns an array-like object called a node list. These data structures are referred to as “Array-like”, because they appear as an array, but can not be used with array methods like <code>map</code> and <code>forEach</code>. Here’s a quick, safe, and reusable way to convert a node list into an array of DOM elements:</p>
<pre><code class="language-javascript"><span class="hljs-keyword">const</span> nodelist = <span class="hljs-built_in">document</span>.querySelectorAll(<span class="hljs-string">'div'</span>);
<span class="hljs-keyword">const</span> nodelistToArray = <span class="hljs-built_in">Array</span>.apply(<span class="hljs-literal">null</span>, nodelist);
<span class="hljs-comment">//later on ..</span>
nodelistToArray.forEach(...);
nodelistToArray.map(...);
nodelistToArray.slice(...);
<span class="hljs-comment">//etc...</span>
</code></pre>
<p>The <code>apply</code> method is used to pass an array of arguments to a function with a given <code>this</code> value. <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply">MDN</a> states that <code>apply</code> will take an array-like object, which is exactly what <code>querySelectorAll</code> returns. Since we don’t need to specify a value for <code>this</code> in the context of the function, we pass in <code>null</code> or <code>0</code>. The result is an actual array of DOM elements which contains all of the available array methods.</p>
<p>Alternatively you can use <code>Array.prototype.slice</code> combined with <code>Function.prototype.call</code> or <code>Function.prototype.apply</code> passing the array-like object as the value of <code>this</code>:</p>
<pre><code class="language-javascript"><span class="hljs-keyword">const</span> nodelist = <span class="hljs-built_in">document</span>.querySelectorAll(<span class="hljs-string">'div'</span>);
<span class="hljs-keyword">const</span> nodelistToArray = <span class="hljs-built_in">Array</span>.prototype.slice.call(nodelist); <span class="hljs-comment">// or equivalently Array.prototype.slice.apply(nodelist);</span>
<span class="hljs-comment">//later on ..</span>
nodelistToArray.forEach(...);
nodelistToArray.map(...);
nodelistToArray.slice(...);
<span class="hljs-comment">//etc...</span>
</code></pre>
<p>Or if you are using ES2015 you can use the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_operator">spread operator <code>...</code></a></p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> nodelist = [...document.querySelectorAll(<span class="hljs-string">'div'</span>)]; <span class="hljs-comment">// returns a real array</span>
<span class="hljs-comment">//later on ..</span>
nodelist.forEach(...);
nodelist.map(...);
nodelist.slice(...);
<span class="hljs-comment">//etc...</span>
</code></pre>`,
},
{
"title": 'Template Strings',
"body": `<p>As of ES6, JS now has template strings as an alternative to the classic end quotes strings.</p>
<p>Ex:<br>
Normal string</p>
<pre><code class="language-javascript"><span class="hljs-keyword">var</span> firstName = <span class="hljs-string">'Jake'</span>;
<span class="hljs-keyword">var</span> lastName = <span class="hljs-string">'Rawr'</span>;
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">'My name is '</span> + firstName + <span class="hljs-string">' '</span> + lastName);
<span class="hljs-comment">// My name is Jake Rawr</span>
</code></pre>
<p>Template String</p>
<pre><code class="language-javascript"><span class="hljs-keyword">var</span> firstName = <span class="hljs-string">'Jake'</span>;
<span class="hljs-keyword">var</span> lastName = <span class="hljs-string">'Rawr'</span>;
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">\`My name is <span class="hljs-subst">$\{firstName}</span> <span class="hljs-subst">$\{lastName}</span>\`</span>);
<span class="hljs-comment">// My name is Jake Rawr</span>
</code></pre>
<p>You can do multi-line strings without <code>\n</code>, perform simple logic (ie 2+3) or even use the <a href="https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Conditional_Operator">ternary operator</a> inside <code>$\{}</code> in template strings.</p>
<pre><code class="language-javascript"><span class="hljs-keyword">var</span> val1 = <span class="hljs-number">1</span>, val2 = <span class="hljs-number">2</span>;
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">\`<span class="hljs-subst">$\{val1}</span> is <span class="hljs-subst">$\{val1 &lt; val2 ? 'less than': 'greater than'}</span> <span class="hljs-subst">$\{val2}</span>\`</span>)
<span class="hljs-comment">// 1 is less than 2</span>
</code></pre>
<p>You are also able to modify the output of template strings using a function; they are called <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/template_strings#Tagged_template_strings">tagged template strings</a> for example usages of tagged template strings.</p>
<p>You may also want to <a href="https://hacks.mozilla.org/2015/05/es6-in-depth-template-strings-2">read</a> to understand template strings more.</p>`,
},
{
"title": 'Check if a property is in a Object',
"body": `<p>When you have to check if a property is present in an <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects">object</a>, you probably are doing something like this:</p>
<pre><code class="language-javascript"><span class="hljs-keyword">var</span> myObject = {
name: <span class="hljs-string">'@tips_js'</span>
};
<span class="hljs-keyword">if</span> (myObject.name) { ... }
</code></pre>
<p>That’s ok, but you have to know that there are two native ways for this kind of thing, the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/in"><code>in</code> operator</a> and <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty"><code>Object.hasOwnProperty</code></a>. Every object descended from <code>Object</code>, has both ways available.</p>
<h3><a id="See_the_big_Difference_13"></a>See the big Difference</h3>
<pre><code class="language-javascript"><span class="hljs-keyword">var</span> myObject = {
name: <span class="hljs-string">'@tips_js'</span>
};
myObject.hasOwnProperty(<span class="hljs-string">'name'</span>); <span class="hljs-comment">// true</span>
<span class="hljs-string">'name'</span> <span class="hljs-keyword">in</span> myObject; <span class="hljs-comment">// true</span>
myObject.hasOwnProperty(<span class="hljs-string">'valueOf'</span>); <span class="hljs-comment">// false, valueOf is inherited from the prototype chain</span>
<span class="hljs-string">'valueOf'</span> <span class="hljs-keyword">in</span> myObject; <span class="hljs-comment">// true</span>
</code></pre>
<p>Both differ in the depth at which they check the properties. In other words, <code>hasOwnProperty</code> will only return true if key is available on that object directly. However, the <code>in</code> operator doesn’t discriminate between properties created on an object and properties inherited from the prototype chain.</p>
<p>Here’s another example:</p>
<pre><code class="language-javascript"><span class="hljs-keyword">var</span> myFunc = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
<span class="hljs-keyword">this</span>.name = <span class="hljs-string">'@tips_js'</span>;
};
myFunc.prototype.age = <span class="hljs-string">'10 days'</span>;
<span class="hljs-keyword">var</span> user = <span class="hljs-keyword">new</span> myFunc();
user.hasOwnProperty(<span class="hljs-string">'name'</span>); <span class="hljs-comment">// true</span>
user.hasOwnProperty(<span class="hljs-string">'age'</span>); <span class="hljs-comment">// false, because age is from the prototype chain</span>
</code></pre>
<p>Check the <a href="https://jsbin.com/tecoqa/edit?js,console">live examples here</a>!</p>
<p>I also recommend reading <a href="https://github.com/loverajoel/jstips/issues/62">this discussion</a> about common mistakes made when checking a property’s existence in objects.</p>`,
},
{
"title": 'Hoisting',
"body": `<p>Understanding <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var#var_hoisting">hoisting</a> will help you organize your function scope. Just remember, variable declarations and function definitions are hoisted to the top. Variable definitions are not, even if you declare and define a variable on the same line. Also, a variable <strong>declaration</strong> lets the system know that the variable exists while <strong>definition</strong> assigns it a value.</p>
<pre><code class="language-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">doTheThing</span>(<span class="hljs-params"></span>) </span>{
<span class="hljs-comment">// ReferenceError: notDeclared is not defined</span>
<span class="hljs-built_in">console</span>.log(notDeclared);
<span class="hljs-comment">// Outputs: undefined</span>
<span class="hljs-built_in">console</span>.log(definedLater);
<span class="hljs-keyword">var</span> definedLater;
definedLater = <span class="hljs-string">'I am defined!'</span>
<span class="hljs-comment">// Outputs: 'I am defined!'</span>
<span class="hljs-built_in">console</span>.log(definedLater)
<span class="hljs-comment">// Outputs: undefined</span>
<span class="hljs-built_in">console</span>.log(definedSimulateneously);
<span class="hljs-keyword">var</span> definedSimulateneously = <span class="hljs-string">'I am defined!'</span>
<span class="hljs-comment">// Outputs: 'I am defined!'</span>
<span class="hljs-built_in">console</span>.log(definedSimulateneously)
<span class="hljs-comment">// Outputs: 'I did it!'</span>
doSomethingElse();
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">doSomethingElse</span>(<span class="hljs-params"></span>)</span>{
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">'I did it!'</span>);
}
<span class="hljs-comment">// TypeError: undefined is not a function</span>
functionVar();
<span class="hljs-keyword">var</span> functionVar = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>)</span>{
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">'I did it!'</span>);
}
}
</code></pre>
<p>To make things easier to read, declare all of your variables at the top of your function scope so it is clear which scope the variables are coming from. Define your variables before you need to use them. Define your functions at the bottom of your scope to keep them out of your way.</p>`,
},
{
"title": 'Pseudomandatory parameters in ES6 functions',
"body": `<p>In many programming languages the parameters of a function are by default mandatory and the developer has to explicitly define that a parameter is optional. In Javascript, every parameter is optional, but we can enforce this behavior without messing with the actual body of a function, taking advantage of [<strong>es6’s default values for parameters</strong>] (<a href="http://exploringjs.com/es6/ch_parameter-handling.html#sec_parameter-default-values">http://exploringjs.com/es6/ch_parameter-handling.html#sec_parameter-default-values</a>) feature.</p>
<pre><code class="language-javascript"><span class="hljs-keyword">const</span> _err = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"> message </span>)</span>{
<span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>( message );
}
<span class="hljs-keyword">const</span> getSum = (a = _err(<span class="hljs-string">'a is not defined'</span>), b = _err(<span class="hljs-string">'b is not defined'</span>)) =&gt; a + b
getSum( <span class="hljs-number">10</span> ) <span class="hljs-comment">// throws Error, b is not defined</span>
getSum( <span class="hljs-literal">undefined</span>, <span class="hljs-number">10</span> ) <span class="hljs-comment">// throws Error, a is not defined</span>
</code></pre>
<p><code>_err</code> is a function that immediately throws an Error. If no value is passed for one of the parameters, the default value is going to be used, <code>_err</code> will be called and an Error will be thrown. You can see more examples for the <strong>default parameters feature</strong> on <a href="https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions/default_parameters">Mozilla’s Developer Network </a></p>`,
},
]
},
]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment