· 7 years ago · Feb 08, 2019, 03:04 PM
1Body
2<p>If I have a JavaScript object, say</p>
3
4<pre><code>var myObject = new Object();
5myObject["firstname"] = "Gareth";
6myObject["lastname"] = "Simpson";
7myObject["age"] = 21;
8</code></pre>
9
10<p>is there a built-in or accepted best practice way to get the length of this object?</p>
11
12<p>What's the cleanest, most effective way to validate decimal numbers in JavaScript?</p>
13
14<p>Bonus points for:</p>
15
16<ol>
17<li>Clarity. Solution should be clean and simple.</li>
18<li>Cross-platform.</li>
19</ol>
20
21<p>Test cases:</p>
22
23<pre><code>01. IsNumeric('-1') => true
2402. IsNumeric('-1.5') => true
2503. IsNumeric('0') => true
2604. IsNumeric('0.42') => true
2705. IsNumeric('.42') => true
2806. IsNumeric('99,999') => false
2907. IsNumeric('0x89f') => false
3008. IsNumeric('#abcdef') => false
3109. IsNumeric('1.2.3') => false
3210. IsNumeric('') => false
3311. IsNumeric('blah') => false
34</code></pre>
35
36<p>What's the best way of checking if an object property in JavaScript is undefined?</p>
37
38<p>How can I check the existence of an element in jQuery?</p>
39
40<p>The current code that I have is this:</p>
41
42<pre><code>if ($(selector).length > 0) {
43 // Do something
44}
45</code></pre>
46
47<p>Is there a more elegant way to approach this? Perhaps a plugin or a function?</p>
48
49<p>Given a string of JSON data, how can you safely turn that string into a JavaScript object?</p>
50
51<p>Obviously you can do this unsafely with something like...</p>
52
53<pre><code>var obj = eval("(" + json + ')');
54</code></pre>
55
56<p>...but that leaves us vulnerable to the json string containing other code, which it seems very dangerous to simply eval.</p>
57
58<p>How do you convert decimal values to their hex equivalent in JavaScript?</p>
59
60<p>How can an email address be validated in JavaScript?</p>
61
62<p>What is the reason browsers do not correctly recognize:</p>
63
64<pre><code><script src="foobar.js" /> <!-- self-closing script tag -->
65</code></pre>
66
67<p>Only this is recognized:</p>
68
69<pre><code><script src="foobar.js"></script>
70</code></pre>
71
72<p>Does this break the concept of XHTML support?</p>
73
74<p>Note: This statement is correct at least for all IE (6-8 beta 2).</p>
75
76<p>When encoding a query string to be sent to a web server - when do you use <code>escape()</code> and when do you use <code>encodeURI()</code> or <code>encodeURIComponent()</code>:</p>
77
78<p>Use escape:</p>
79
80<pre><code>escape("% +&=");
81</code></pre>
82
83<p>OR</p>
84
85<p>use encodeURI() / encodeURIComponent()</p>
86
87<pre><code>encodeURI("http://www.google.com?var1=value1&var2=value2");
88
89encodeURIComponent("var1=value1&var2=value2");
90</code></pre>
91
92<p>I'm trying to create globally-unique identifiers in JavaScript. I'm not sure what routines are available on all browsers, how "random" and seeded the built-in random number generator is, etc..</p>
93
94<p>The GUID / UUID should be at least 32 characters and should stay in the ASCII range to avoid trouble when passing them around.</p>
95
96<p>I am using <code>setInterval(fname, 10000);</code> to call a function every 10 seconds in JavaScript. Is it possible to stop calling it on some event? </p>
97
98<p>I want the user to be able to stop the repeated refresh of data.</p>
99
100<p>How would you explain JavaScript closures to someone with a knowledge of the concepts they consist of (for example functions, variables and the like), but does not understand closures themselves?</p>
101
102<p>I have seen <a href="http://en.wikipedia.org/wiki/Scheme_%28programming_language%29" rel="noreferrer">the Scheme example</a> given on Wikipedia, but unfortunately it did not help.</p>
103
104<p>What is the most efficient way to clone a JavaScript object? I've seen <code>obj = eval(uneval(o));</code> being used, but <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/uneval" rel="noreferrer">that's non-standard and only supported by Firefox</a>.<br/><br/> I've done things like <code>obj = JSON.parse(JSON.stringify(o));</code> but question the efficiency. <br/><br/> I've also seen recursive copying functions with various flaws.
105<br />
106I'm surprised no canonical solution exists.</p>
107
108<p>What's the fastest way to count the number of keys/properties of an object? It it possible to do this without iterating over the object? i.e. without doing</p>
109
110<pre><code>var count = 0;
111for (k in myobj) if (myobj.hasOwnProperty(k)) count++;
112</code></pre>
113
114<p>(Firefox did provide a magic <code>__count__</code> property, but this was removed somewhere around version 4.)</p>
115
116<p>Is there a way to use constants in JavaScript?</p>
117
118<p>If not, what's the common practice for specifying variables that are used as constants?</p>
119
120<p>I have a JavaScript widget which provides standard extension points. One of them is the <code>beforecreate</code> function. It should return <code>false</code> to prevent an item from being created. </p>
121
122<p>I've added an Ajax call into this function using jQuery:</p>
123
124<pre><code>beforecreate: function (node, targetNode, type, to) {
125 jQuery.get('http://example.com/catalog/create/' + targetNode.id + '?name=' + encode(to.inp[0].value),
126
127 function (result) {
128 if (result.isOk == false)
129 alert(result.message);
130 });
131}
132</code></pre>
133
134<p>But I want to prevent my widget from creating the item, so I should return <code>false</code> in the mother-function, not in the callback. Is there a way to perform a synchronous AJAX request using jQuery or any other in-browser API?</p>
135
136<p>I'm trying to direct a browser to a different page. If I wanted a GET request, I might say</p>
137
138<pre><code>document.location.href = 'http://example.com/q=a';
139</code></pre>
140
141<p>But the resource I'm trying to access won't respond properly unless I use a POST request. If this were not dynamically generated, I might use the HTML</p>
142
143<pre><code><form action="http://example.com/" method="POST">
144 <input type="hidden" name="q" value="a">
145</form>
146</code></pre>
147
148<p>Then I would just submit the form from the DOM.</p>
149
150<p>But really I would like JavaScript code that allows me to say</p>
151
152<pre><code>post_to_url('http://example.com/', {'q':'a'});
153</code></pre>
154
155<p>What's the best cross browser implementation?</p>
156
157<p><strong>Edit</strong> </p>
158
159<p>I'm sorry I was not clear. I need a solution that changes the location of the browser, just like submitting a form. If this is possible with <a href="http://en.wikipedia.org/wiki/XMLHttpRequest" rel="noreferrer">XMLHttpRequest</a>, it is not obvious. And this should not be asynchronous, nor use XML, so Ajax is not the answer.</p>
160
161<p>The following are two methods of building a link that has the sole purpose of running JavaScript code. Which is better, in terms of functionality, page load speed, validation purposes, etc.?</p>
162
163<p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false">
164<div class="snippet-code">
165<pre class="snippet-code-js lang-js prettyprint-override"><code>function myJsFunc() {
166 alert("myJsFunc");
167}</code></pre>
168<pre class="snippet-code-html lang-html prettyprint-override"><code><a href="#" onclick="myJsFunc();">Run JavaScript Code</a></code></pre>
169</div>
170</div>
171</p>
172
173<p>or</p>
174
175<p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false">
176<div class="snippet-code">
177<pre class="snippet-code-js lang-js prettyprint-override"><code>function myJsFunc() {
178 alert("myJsFunc");
179}</code></pre>
180<pre class="snippet-code-html lang-html prettyprint-override"><code> <a href="javascript:void(0)" onclick="myJsFunc();">Run JavaScript Code</a></code></pre>
181</div>
182</div>
183</p>
184
185<p>How do I check if an object has a property in JavaScript?</p>
186
187<p>Consider:</p>
188
189<pre><code>x = {'key': 1};
190if ( x.hasOwnProperty('key') ) {
191 //Do this
192}
193</code></pre>
194
195<p>Is that the best way to do it?</p>
196
197<p>I would like to format a price in JavaScript.<br>
198I'd like a function which takes a <code>float</code> as an argument and returns a <code>string</code> formatted like this:</p>
199
200<pre><code>"$ 2,500.00"
201</code></pre>
202
203<p>What's the best way to do this?</p>
204
205<p>I have some HTML menus, which I show completely when a user clicks on the head of these menus. I would like to hide these elements when the user clicks outside the menus' area.</p>
206
207<p>Is something like this possible with jQuery?</p>
208
209<pre><code>$("#menuscontainer").clickOutsideThisElement(function() {
210 // Hide the menus
211});
212</code></pre>
213
214<p>I saw this <a href="https://stackoverflow.com/questions/10230/checking-for-string-contents-string-length-vs-empty-string">thread</a>, but I didn't see a JavaScript specific example. Is there a simple <code>string.Empty</code> available in JavaScript, or is it just a case of checking for <code>""</code>?</p>
215
216<p>How can I convert a JavaScript string value to be in all lower case letters?</p>
217
218<p>Example: "Your Name" to "your name"</p>
219
220<p>I have one text input and one button (see below). How can I use JavaScript to <strong>trigger the button's click event</strong> when the <kbd>Enter</kbd> key is pressed inside the text box?</p>
221
222<p>There is already a different submit button on my current page, so I can't simply make the button a submit button. And, I <em>only</em> want the <kbd>Enter</kbd> key to click this specific button if it is pressed from within this one text box, nothing else.</p>
223
224<pre><code><input type="text" id="txtSearch" />
225<input type="button" id="btnSearch" value="Search" onclick="doSomething();" />
226</code></pre>
227
228<p>I would like to upload a file asynchronously with jQuery. This is my HTML:</p>
229
230<pre><code><span>File</span>
231<input type="file" id="file" name="file" size="10"/>
232<input id="uploadbutton" type="button" value="Upload"/>
233</code></pre>
234
235<p>And here my <code>Jquery</code> code:</p>
236
237<pre><code>$(document).ready(function () {
238 $("#uploadbutton").click(function () {
239 var filename = $("#file").val();
240
241 $.ajax({
242 type: "POST",
243 url: "addFile.do",
244 enctype: 'multipart/form-data',
245 data: {
246 file: filename
247 },
248 success: function () {
249 alert("Data Uploaded: ");
250 }
251 });
252 });
253});
254</code></pre>
255
256<p>Instead of the file being uploaded, I am only getting the filename. What can I do to fix this problem?</p>
257
258<h3>Current Solution</h3>
259
260<p>I am using the <a href="http://malsup.com/jquery/form/#code-samples" rel="noreferrer">jQuery Form Plugin</a> to upload files.</p>
261
262<p>What is the best method for adding options to a <code><select></code> from a JavaScript object using jQuery?</p>
263
264<p>I'm looking for something that I don't need a plugin to do, but I would also be interested in the plugins that are out there.</p>
265
266<p>This is what I did:</p>
267
268<pre><code>selectValues = { "1": "test 1", "2": "test 2" };
269
270for (key in selectValues) {
271 if (typeof (selectValues[key] == 'string') {
272 $('#mySelect').append('<option value="' + key + '">' + selectValues[key] + '</option>');
273 }
274}
275</code></pre>
276
277<p><strong>A clean/simple solution:</strong></p>
278
279<p>This is a cleaned up and simplified <a href="https://stackoverflow.com/questions/170986/what-is-the-best-way-to-add-options-to-a-select-from-an-array-with-jquery/171007#171007">version of matdumsa's</a>:</p>
280
281<pre><code>$.each(selectValues, function(key, value) {
282 $('#mySelect')
283 .append($('<option>', { value : key })
284 .text(value));
285});
286</code></pre>
287
288<p>Changes from matdumsa's: (1) removed the close tag for the option inside append() and (2) moved the properties/attributes into an map as the second parameter of append().</p>
289
290<p>I need to be able to merge two (very simple) JavaScript objects at runtime. For example I'd like to:</p>
291
292<pre><code>var obj1 = { food: 'pizza', car: 'ford' }
293var obj2 = { animal: 'dog' }
294
295obj1.merge(obj2);
296
297//obj1 now has three properties: food, car, and animal
298</code></pre>
299
300<p>Does anyone have a script for this or know of a built in way to do this? I do not need recursion, and I do not need to merge functions, just methods on flat objects.</p>
301
302<p>How can you change the href for a hyperlink using jQuery?</p>
303
304<p>What is the best method in jQuery to add an additional row to a table as the last row?</p>
305
306<p>Is this acceptable?</p>
307
308<pre><code>$('#myTable').append('<tr><td>my data</td><td>more data</td></tr>');
309</code></pre>
310
311<p>Are there limitations to what you can add to a table like this (such as inputs, selects, number of rows)?</p>
312
313<p>It is possible to toggle the visibility of an element, using the functions <code>.hide()</code>, <code>.show()</code> or <code>.toggle()</code>.</p>
314
315<p>How would you test if an element is visible or hidden?</p>
316
317<p>I need to serialize an object to JSON. I'm using jQuery. Is there a "standard" way to do this?</p>
318
319<p>My specific situation: I have an array defined as shown below:</p>
320
321<pre><code>var countries = new Array();
322countries[0] = 'ga';
323countries[1] = 'cd';
324...
325</code></pre>
326
327<p>and I need to turn this into a string to pass to <code>$.ajax()</code> like this:</p>
328
329<pre><code>$.ajax({
330 type: "POST",
331 url: "Concessions.aspx/GetConcessions",
332 data: "{'countries':['ga','cd']}",
333...
334</code></pre>
335
336<p>How can I change a class of an HTML element in response to an <code>onClick</code> event using JavaScript?</p>
337
338<p>All right, say I have this:</p>
339
340<pre><code><select id='list'>
341 <option value='1'>Option A</option>
342 <option value='2'>Option B</option>
343 <option value='3'>Option C</option>
344</select>
345</code></pre>
346
347<p>What would the selector look like if I wanted to get "Option B" when I have the value '2'?</p>
348
349<p>Please note that this is not asking how to get the <em>selected</em> text value, but just any one of them, whether selected or not, depending on the value attribute. I tried:</p>
350
351<pre><code>$("#list[value='2']").text();
352</code></pre>
353
354<p>But it is not working.</p>
355
356<p>I have a bit of code where I am looping through all the select boxes on a page and binding a <code>.hover</code> event to them to do a bit of twiddling with their width on <code>mouse on/off</code>.</p>
357
358<p>This happens on page ready and works just fine.</p>
359
360<p>The problem I have is that any select boxes I add via Ajax or DOM after the initial loop won't have the event bound.</p>
361
362<p>I have found this plugin (<a href="http://brandonaaron.net/docs/livequery/#getting-started" rel="noreferrer">jQuery Live Query Plugin</a>), but before I add another 5k to my pages with a plugin, I want to see if anyone knows a way to do this, either with jQuery directly or by another option.</p>
363
364<p>I'm using <code>$.post()</code> to call a servlet using Ajax and then using the resulting HTML fragment to replace a <code>div</code> element in the user's current page. However, if the session times out, the server sends a redirect directive to send the user to the login page. In this case, jQuery is replacing the <code>div</code> element with the contents of the login page, forcing the user's eyes to witness a rare scene indeed. </p>
365
366<p>How can I manage a redirect directive from an Ajax call with jQuery 1.2.6?</p>
367
368<p>Say I create an object as follows:</p>
369
370<pre><code>var myObject = {
371 "ircEvent": "PRIVMSG",
372 "method": "newURI",
373 "regex": "^http://.*"
374};
375</code></pre>
376
377<p>What is the best way to remove the property <code>regex</code> to end up with new <code>myObject</code> as follows?</p>
378
379<pre><code>var myObject = {
380 "ircEvent": "PRIVMSG",
381 "method": "newURI"
382};
383</code></pre>
384
385<p>How can I get a timestamp in JavaScript?</p>
386
387<p>Something similar to Unix's timestamp, that is, a single number that represents the current time and date. Either as a number or a string.</p>
388
389<p>What is the most concise and efficient way to find out if a JavaScript array contains an object?</p>
390
391<p>This is the only way I know to do it:</p>
392
393<pre><code>function contains(a, obj) {
394 for (var i = 0; i < a.length; i++) {
395 if (a[i] === obj) {
396 return true;
397 }
398 }
399 return false;
400}
401</code></pre>
402
403<p>Is there a better and more concise way to accomplish this?</p>
404
405<p>This is very closely related to Stack Overflow question <em><a href="https://stackoverflow.com/questions/143847/best-way-to-find-an-item-in-a-javascript-array">Best way to find an item in a JavaScript Array?</a></em> which addresses finding objects in an array using <code>indexOf</code>.</p>
406
407<p><code>console.log("double");</code> vs <code>console.log('single');</code></p>
408
409<p>I see more and more JavaScript libraries out there using single quotes when handling strings. What are the reasons to use one over the other? I thought they're pretty much interchangeable.</p>
410
411<p>Can I convert a string representing a boolean value (e.g., 'true', 'false') into a intrinsic type in JavaScript?</p>
412
413<p>I have a hidden form in HTML that is updated based upon a user's selection within a list. This form contains some fields which represent boolean values and are dynamically populated with an intrinsic boolean value. However, once this value is placed into the hidden input field it becomes a string.</p>
414
415<p>The only way I could find to determine the field's boolean value, once it was converted into a string, was to depend upon the literal value of its string representation.</p>
416
417<pre><code>var myValue = document.myForm.IS_TRUE.value;
418var isTrueSet = myValue == 'true';
419</code></pre>
420
421<p>Is there a better way to accomplish this?</p>
422
423<p>I'm refactoring some old JavaScript code and there's a lot of DOM manipulation going on.</p>
424
425<pre><code>var d = document;
426var odv = d.createElement("div");
427odv.style.display = "none";
428this.OuterDiv = odv;
429
430var t = d.createElement("table");
431t.cellSpacing = 0;
432t.className = "text";
433odv.appendChild(t);
434</code></pre>
435
436<p>I would like to know if there is a better way to do this using jQuery. I've been experimenting with:</p>
437
438<pre><code>var odv = $.create("div");
439$.append(odv);
440// And many more
441</code></pre>
442
443<p>But I'm not sure if this is any better.</p>
444
445<p>How can I check if a string ends with a particular character in JavaScript?</p>
446
447<p>Example: I have a string </p>
448
449<pre><code>var str = "mystring#";
450</code></pre>
451
452<p>I want to know if that string is ending with <code>#</code>. How can I check it?</p>
453
454<ol>
455<li><p>Is there a <code>endsWith()</code> method in JavaScript?</p></li>
456<li><p>One solution I have is take the length of the string and get the last character and check it.</p></li>
457</ol>
458
459<p>Is this the best way or there is any other way?</p>
460
461<p>What is the preferred syntax for defining enums in JavaScript? Something like:</p>
462
463<pre><code>my.namespace.ColorEnum = {
464 RED : 0,
465 GREEN : 1,
466 BLUE : 2
467}
468
469// later on
470
471if(currentColor == my.namespace.ColorEnum.RED) {
472 // whatever
473}
474</code></pre>
475
476<p>Or is there a more preferable idiom?</p>
477
478<p>I have a layout similar to this:</p>
479
480<pre><code><div id="..."><img src="..."></div>
481</code></pre>
482
483<p>and would like to use a jQuery selector to select the child <code>img</code> inside the <code>div</code> on click.</p>
484
485<p>To get the <code>div</code>, I've got this selector:</p>
486
487<pre><code>$(this)
488</code></pre>
489
490<p>How can I get the child <code>img</code> using a selector?</p>
491
492<p>Is there a JavaScript equivalent of Java's <code>class.getName()</code>?</p>
493
494<p>How do you safely encode a URL using JavaScript such that it can be put into a GET string?</p>
495
496<pre><code>var myUrl = "http://example.com/index.html?param=1&anotherParam=2";
497var myOtherUrl = "http://example.com/index.html?url=" + myUrl;
498</code></pre>
499
500<p>I assume that you need to encode the <code>myUrl</code> variable on that second line?</p>
501
502<p>I've recently started maintaining someone else's JavaScript code. I'm fixing bugs, adding features, and also trying to tidy up the code and make it more consistent.</p>
503
504<p>The previous developer uses two ways of declaring functions and I can't work out if there is a reason behind it or not.</p>
505
506<p>The two ways are:</p>
507
508<pre><code>var functionOne = function() {
509 // Some code
510};
511</code></pre>
512
513
514
515<pre><code>function functionTwo() {
516 // Some code
517}
518</code></pre>
519
520<p>What are the reasons for using these two different methods and what are the pros and cons of each? Is there anything that can be done with one method that can't be done with the other?</p>
521
522<p>How do I append an object (such as a string or number) to an array in JavaScript? </p>
523
524<p>I'm using <a href="http://en.wikipedia.org/wiki/JSLint" rel="noreferrer">JSLint</a> to go through JavaScript, and it's returning many suggestions to replace <code>==</code> (two equals signs) with <code>===</code> (three equals signs) when doing things like comparing <code>idSele_UNVEHtype.value.length == 0</code> inside of an <code>if</code> statement.</p>
525
526<p>Is there a performance benefit to replacing <code>==</code> with <code>===</code>? </p>
527
528<p>Any performance improvement would be welcomed as many comparison operators exist.</p>
529
530<p>If no type conversion takes place, would there be a performance gain over <code>==</code>?</p>
531
532<p>What is the best way to copy text to the clipboard? (multi-browser)</p>
533
534<p>I have tried: </p>
535
536<pre><code>function copyToClipboard(text) {
537 if (window.clipboardData) { // Internet Explorer
538 window.clipboardData.setData("Text", text);
539 } else {
540 unsafeWindow.netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
541 const clipboardHelper = Components.classes["@mozilla.org/widget/clipboardhelper;1"].getService(Components.interfaces.nsIClipboardHelper);
542 clipboardHelper.copyString(text);
543 }
544}
545</code></pre>
546
547<p>but in Internet Explorer it gives a syntax error. In Firefox, it says <code>unsafeWindow is not defined</code>.</p>
548
549<p>A nice trick without flash: <a href="https://stackoverflow.com/questions/17527870/how-does-trello-access-the-users-clipboard">How does Trello access the user's clipboard?</a></p>
550
551<p>I am using jQuery. How do I get the path of the current URL and assign it to a variable?</p>
552
553<p>Example URL:</p>
554
555<pre><code>http://localhost/menuname.de?foo=bar&amp;number=0
556</code></pre>
557
558<p>I'd like to do something like this to tick a <code>checkbox</code> using <strong>jQuery</strong>:</p>
559
560<pre><code>$(".myCheckBox").checked(true);
561</code></pre>
562
563<p>or </p>
564
565<pre><code>$(".myCheckBox").selected(true);
566</code></pre>
567
568<p>Does such a thing exist?</p>
569
570<p>I want to match a portion of a string using a <a href="http://en.wikipedia.org/wiki/Regular_expression" rel="noreferrer">regular expression</a> and then access that parenthesized substring:</p>
571
572<pre><code>var myString = "something format_abc"; // I want "abc"
573
574var arr = /(?:^|\s)format_(.*?)(?:\s|$)/.exec(myString);
575
576console.log(arr); // Prints: [" format_abc", "abc"] .. so far so good.
577console.log(arr[1]); // Prints: undefined (???)
578console.log(arr[0]); // Prints: format_undefined (!!!)
579</code></pre>
580
581<p>What am I doing wrong?</p>
582
583<hr>
584
585<p>I've discovered that there was nothing wrong with the regular expression code above: the actual string which I was testing against was this:</p>
586
587<pre><code>"date format_%A"
588</code></pre>
589
590<p>Reporting that "%A" is undefined seems a very strange behaviour, but it is not directly related to this question, so I've opened a new one, <em><a href="https://stackoverflow.com/questions/432826/why-is-a-matched-substring-returning-undefined-in-javascript">Why is a matched substring returning "undefined" in JavaScript?</a></em>.</p>
591
592<hr>
593
594<p>The issue was that <code>console.log</code> takes its parameters like a <code>printf</code> statement, and since the string I was logging (<code>"%A"</code>) had a special value, it was trying to find the value of the next parameter.</p>
595
596<p>When embedding JavaScript in an HTML document, where is the proper place to put the <code><script></code> tags and included JavaScript? I seem to recall that you are not supposed to place these in the <code><head></code> section, but placing at the beginning of the <code><body></code> section is bad, too, since the JavaScript will have to be parsed before the page is rendered completely (or something like that). This seems to leave the <em>end</em> of the <code><body></code> section as a logical place for <code><script></code> tags.</p>
597
598<p>So, where <em>is</em> the right place to put the <code><script></code> tags?</p>
599
600<p>(This question references <a href="https://stackoverflow.com/questions/436154/why-does-the-call-to-this-jquery-function-fail-in-firefox">this question</a>, in which it was suggested that JavaScript function calls should be moved from <code><a></code> tags to <code><script></code> tags. I'm specifically using jQuery, but more general answers are also appropriate.)</p>
601
602<p>I want to know how to get the X and Y position of HTML elements such as <code>img</code> and <code>div</code> in JavaScript.</p>
603
604<p>Using jQuery, how can I <strong>cancel/abort an Ajax request</strong> that I have not yet received the response from?</p>
605
606<p>Is there a null coalescing operator in Javascript?</p>
607
608<p>For example, in C#, I can do this:</p>
609
610<pre><code>String someString = null;
611var whatIWant = someString ?? "Cookies!";
612</code></pre>
613
614<p>The best approximation I can figure out for Javascript is using the conditional operator:</p>
615
616<pre><code>var someString = null;
617var whatIWant = someString ? someString : 'Cookies!';
618</code></pre>
619
620<p>Which is sorta icky IMHO. Can I do better?</p>
621
622<p>Can someone suggest a way to compare the values of <strong>two dates</strong> greater than, less than, and not in the past using JavaScript? The values will be coming from text boxes.</p>
623
624<p>I would like to create a String.replaceAll() method in JavaScript and I'm thinking that using a RegEx would be most terse way to do it. However, I can't figure out how to pass a variable in to a RegEx. I can do this already which will replace all the instances of "B" with "A".</p>
625
626<pre><code>"ABABAB".replace(/B/g, "A");
627</code></pre>
628
629<p>But I want to do something like this:</p>
630
631<pre><code>String.prototype.replaceAll = function(replaceThis, withThis) {
632 this.replace(/replaceThis/g, withThis);
633};
634</code></pre>
635
636<p>But obviously this will only replace the text "replaceThis"...so how do I pass this variable in to my RegEx string?</p>
637
638<p>I would like to find out, in JavaScript, which element currently has focus. I've been looking through the DOM and haven't found what I need, yet. Is there a way to do this, and how?</p>
639
640<p>The reason I was looking for this:</p>
641
642<p>I'm trying to make keys like the arrows and <code>enter</code> navigate through a table of input elements. Tab works now, but enter, and arrows do not by default it seems. I've got the key handling part set up but now I need to figure out how to move the focus over in the event handling functions.</p>
643
644<p>How do I trim a string in JavaScript?</p>
645
646<p>What is the scope of variables in javascript? Do they have the same scope inside as opposed to outside a function? Or does it even matter? Also, where are the variables stored if they are defined globally?</p>
647
648<p>I'm loading elements via AJAX. Some of them are only visible if you scroll down the page.<br>
649Is there any way I can know if an element is now in the visible part of the page?</p>
650
651<p>I've been told not to use <code>for...in</code> with arrays in JavaScript. Why not?</p>
652
653<p>What is the difference between using <a href="https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/delete" rel="noreferrer">the <code>delete</code> operator</a> on the array element as opposed to using <a href="https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/splice" rel="noreferrer">the <code>Array.splice</code> method</a>? </p>
654
655<p>For example:</p>
656
657<pre><code>myArray = ['a', 'b', 'c', 'd'];
658
659delete myArray[1];
660// or
661myArray.splice (1, 1);
662</code></pre>
663
664<p>Why even have the splice method if I can delete array elements like I can with objects?</p>
665
666<p>How can I redirect the user from one page to another using jQuery or pure JavaScript?</p>
667
668<p>The primitive types (Number, String, etc.) are passed by value, but Objects are unknown, because they can be both passed-by-value (in case we consider that a variable holding an object is in fact a reference to the object) and passed-by-reference (when we consider that the variable to the object holds the object itself).</p>
669
670<p>Although it doesn't really matter at the end, I want to know what is the correct way to present the arguments passing conventions. Is there an excerpt from JavaScript specification, which defines what should be the semantics regarding this?</p>
671
672<blockquote>
673 <p><strong>Possible Duplicate:</strong><br>
674 <a href="https://stackoverflow.com/questions/359494/javascript-vs-does-it-matter-which-equal-operator-i-use">Javascript === vs == : Does it matter which “equal” operator I use?</a> </p>
675</blockquote>
676
677
678
679<p>What is the difference between <code>==</code> and <code>===</code> in JavaScript? I have also seen <code>!=</code> and <code>!==</code> operators. Are there more such operators?</p>
680
681<p>I'm not that into dynamic programming languages but I've written my fair share of JavaScript code. I never really got my head around this prototype-based programming, does any one know how this works? </p>
682
683<pre><code>var obj = new Object();
684obj.prototype.test = function() { alert('Hello?'); };
685var obj2 = new obj();
686obj2.test();
687</code></pre>
688
689<p>I remember a lot discussion I had with people a while back (I'm not exactly sure what I'm doing) but as I understand it, there's no concept of a class. It's just an object, and instances of those objects are clones of the original, right?</p>
690
691<p>But what is the exact purpose of this ".prototype" property in JavaScript? How does it relate to instantiating objects?</p>
692
693<h3>Update: correct way</h3>
694
695<pre><code>var obj = new Object(); // not a functional object
696obj.prototype.test = function() { alert('Hello?'); }; // this is wrong!
697
698function MyObject() {} // a first class functional object
699MyObject.prototype.test = function() { alert('OK'); } // OK
700</code></pre>
701
702<p>Also these <a href="http://ejohn.org/apps/learn/#64" rel="noreferrer">slides</a> really helped a lot.</p>
703
704<p>I am looking for a JavaScript array insert method, in the style of:</p>
705
706<pre><code>arr.insert(index, item)
707</code></pre>
708
709<p>Preferably in jQuery, but any JavaScript implementation will do at this point.</p>
710
711<p>I have two radio buttons and want to post the value of the selected one.
712How can I get the value with jQuery?</p>
713
714<p>I can get all of them like this:</p>
715
716<pre><code>$("form :radio")
717</code></pre>
718
719<p>How do I know which one is selected?</p>
720
721<p>I'm looking for a good JavaScript equivalent of the C/PHP <code>printf()</code> or for C#/Java programmers, <code>String.Format()</code> (<code>IFormatProvider</code> for .NET).</p>
722
723<p>My basic requirement is a thousand separator format for numbers for now, but something that handles lots of combinations (including dates) would be good.</p>
724
725<p>I realize Microsoft's <a href="http://en.wikipedia.org/wiki/Ajax_%28programming%29" rel="noreferrer">Ajax</a> library provides a version of <code>String.Format()</code>, but we don't want the entire overhead of that framework.</p>
726
727<p>How would I write the equivalent of C#'s <a href="http://msdn.microsoft.com/en-us/library/baketfxw.aspx" rel="noreferrer"><code>String.StartsWith</code></a> in JavaScript?</p>
728
729<pre><code>var haystack = 'hello world';
730var needle = 'he';
731
732haystack.startsWith(needle) == true
733</code></pre>
734
735<p>Note: This is an old question, and as pointed out in the comments ECMAScript 2015 (ES6) introduced the <a href="https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith" rel="noreferrer"><code>.startsWith</code></a> method. However, at the time of writing this update (2015) <a href="http://kangax.github.io/compat-table/es6/#test-String.prototype_methods_String.prototype.startsWith" rel="noreferrer">browser support is far from complete</a>.</p>
736
737<p>After an AJAX request, sometimes my application may return an empty object, like:</p>
738
739<pre><code>var a = {};
740</code></pre>
741
742<p>How can I check whether that's the case?</p>
743
744<p>I have a JavaScript object like the following:</p>
745
746<pre><code>var p = {
747 "p1": "value1",
748 "p2": "value2",
749 "p3": "value3"
750};
751</code></pre>
752
753<p>Now I want to loop through all <code>p</code> elements (<code>p1</code>, <code>p2</code>, <code>p3</code>...) And get their keys and values. How can I do that?</p>
754
755<p>I can modify the JavaScript object if necessary. My ultimate goal is to loop through some key value pairs and if possible I want to avoid using <code>eval</code>.</p>
756
757<p>I have an object, <code>x</code>. I'd like to copy it as object <code>y</code>, such that changes to <code>y</code> do not modify <code>x</code>. I realized that copying objects derived from built-in JavaScript objects will result in extra, unwanted properties. This isn't a problem, since I'm copying one of my own, literal-constructed objects.</p>
758
759<p>How do I correctly clone a JavaScript object?</p>
760
761<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
762<div class="snippet-code">
763<pre class="snippet-code-js lang-js prettyprint-override"><code>var funcs = [];
764for (var i = 0; i < 3; i++) { // let's create 3 functions
765 funcs[i] = function() { // and store them in funcs
766 console.log("My value: " + i); // each should log its value.
767 };
768}
769for (var j = 0; j < 3; j++) {
770 funcs[j](); // and now let's run each one to see
771}</code></pre>
772</div>
773</div>
774</p>
775
776<p>It outputs this:</p>
777
778<blockquote>
779 <p>My value: 3<br>
780 My value: 3<br>
781 My value: 3</p>
782</blockquote>
783
784<p>Whereas I'd like it to output:</p>
785
786<blockquote>
787 <p>My value: 0<br>
788 My value: 1<br>
789 My value: 2</p>
790</blockquote>
791
792<hr>
793
794<p>The same problem occurs when the delay in running the function is caused by using event listeners:</p>
795
796<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
797<div class="snippet-code">
798<pre class="snippet-code-js lang-js prettyprint-override"><code>var buttons = document.getElementsByTagName("button");
799for (var i = 0; i < buttons.length; i++) { // let's create 3 functions
800 buttons[i].addEventListener("click", function() { // as event listeners
801 console.log("My value: " + i); // each should log its value.
802 });
803}</code></pre>
804<pre class="snippet-code-html lang-html prettyprint-override"><code><button>0</button><br>
805<button>1</button><br>
806<button>2</button></code></pre>
807</div>
808</div>
809</p>
810
811<p>… or asynchronous code, e.g. using Promises:</p>
812
813<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
814<div class="snippet-code">
815<pre class="snippet-code-js lang-js prettyprint-override"><code>// Some async wait function
816const wait = (ms) => new Promise((resolve, reject) => setTimeout(resolve, ms));
817
818for(var i = 0; i < 3; i++){
819 wait(i * 100).then(() => console.log(i)); // Log `i` as soon as each promise resolves.
820}</code></pre>
821</div>
822</div>
823</p>
824
825<p>What’s the solution to this basic problem?</p>
826
827<p>ECMAScript 6 introduced <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let" rel="noreferrer">the <code>let</code> statement</a>. I've heard it described as a "local" variable, but I'm still not quite sure how it behaves differently than the <code>var</code> keyword.</p>
828
829<p>What are the differences? When should <code>let</code> be used over <code>var</code>?</p>
830
831<p>I would like to check whether a variable is either an array or a single value in JavaScript.</p>
832
833<p>I have found a possible solution...</p>
834
835<pre><code>if (variable.constructor == Array)...
836</code></pre>
837
838<p>Is this the best way this can be done?</p>
839
840<p>I have the following code in Ruby. I want to convert this code into JavaScript. what's the equivalent code in JS?</p>
841
842<pre><code>text = <<"HERE"
843This
844Is
845A
846Multiline
847String
848HERE
849</code></pre>
850
851<p>I have a script that uses <code>$(document).ready</code>, but it doesn't use anything else from jQuery. I'd like to lighten it up by removing the jQuery dependency.</p>
852
853<p>How can I implement my own <code>$(document).ready</code> functionality without using jQuery? I know that using <code>window.onload</code> will not be the same, as <code>window.onload</code> fires after all images, frames, etc. have been loaded.</p>
854
855<p>I saw some code that seems to use an operator I don't recognize, in the form of two exclamation points, like so: <code>!!</code>. Can someone please tell me what this operator does?</p>
856
857<p>The context in which I saw this was,</p>
858
859<pre><code>this.vertical = vertical !== undefined ? !!vertical : this.vertical;
860</code></pre>
861
862<p>Is there any way I can modify the URL of the current page without reloading the page?</p>
863
864<p>I would like to access the portion <strong>before</strong> the # hash if possible.</p>
865
866<p>I only need to change the portion <strong>after</strong> the domain, so its not like I'm violating cross-domain policies.</p>
867
868<pre><code> window.location.href = "www.mysite.com/page2.php"; // sadly this reloads
869</code></pre>
870
871<p>How do I create a <code>div</code> element in <strong>jQuery</strong>?</p>
872
873<p>I would like a JavaScript function to have optional arguments which I set a default on, which gets used if the value isn't defined. In Ruby you can do it like this:</p>
874
875<pre><code>def read_file(file, delete_after = false)
876 # code
877end
878</code></pre>
879
880<p>Does this work in JavaScript?</p>
881
882<pre><code>function read_file(file, delete_after = false) {
883 // Code
884}
885</code></pre>
886
887<p>Is there a plugin-less way of retrieving <a href="http://en.wikipedia.org/wiki/Query_string" rel="nofollow noreferrer">query string</a> values via jQuery (or without)? </p>
888
889<p>If so, how? If not, is there a plugin which can do so?</p>
890
891<p>How can I loop through all members in a JavaScript object including values that are objects.</p>
892
893<p>For example, how could I loop through this (accessing the "your_name" and "your_message" for each)?</p>
894
895<pre><code>var validation_messages = {
896 "key_1": {
897 "your_name": "jimmy",
898 "your_msg": "hello world"
899 },
900 "key_2": {
901 "your_name": "billy",
902 "your_msg": "foo equals bar"
903 }
904}
905</code></pre>
906
907<p>Is there something in JavaScript similar to <code>@import</code> in CSS that allows you to include a JavaScript file inside another JavaScript file?</p>
908
909<p>Is there a better way to engineer a <code>sleep</code> in JavaScript than the following <code>pausecomp</code> function (<a href="http://www.sean.co.uk/a/webdesign/javascriptdelay.shtm" rel="noreferrer">taken from here</a>)?</p>
910
911<pre><code>function pausecomp(millis)
912{
913 var date = new Date();
914 var curDate = null;
915 do { curDate = new Date(); }
916 while(curDate-date < millis);
917}
918</code></pre>
919
920<p>This is not a duplicate of <a href="https://stackoverflow.com/questions/758688/sleep-in-javascript-delay-between-actions">Sleep in JavaScript - delay between actions</a>; I want a <em>real sleep</em> in the middle of a function, and not a delay before a piece of code executes.</p>
921
922<p>I have a string, <code>12345.00</code>, and I would like it to return <code>12345.0</code>.</p>
923
924<p>I have looked at <code>trim</code>, but it looks like it is only trimming whitespace and <code>slice</code> which I don't see how this would work. Any suggestions?</p>
925
926<p>How do I display the content of a JavaScript object in a string format like when we <code>alert</code> a variable?</p>
927
928<p>The same formatted way I want to display an object.</p>
929
930<p>I read the following objects using Ajax and stored them in an array:</p>
931
932<pre><code>var homes = [
933 {
934 "h_id": "3",
935 "city": "Dallas",
936 "state": "TX",
937 "zip": "75201",
938 "price": "162500"
939 }, {
940 "h_id": "4",
941 "city": "Bevery Hills",
942 "state": "CA",
943 "zip": "90210",
944 "price": "319250"
945 }, {
946 "h_id": "5",
947 "city": "New York",
948 "state": "NY",
949 "zip": "00010",
950 "price": "962500"
951 }
952];
953</code></pre>
954
955<p>How do I create a function to sort the objects by the <code>price</code> property in <em>ascending</em> <strong>or</strong> <em>descending</em> order using only JavaScript?</p>
956
957<p>How do I make the first letter of a string uppercase, but not change the case of any of the other letters?</p>
958
959<p>For example:</p>
960
961<ul>
962<li><code>"this is a test"</code> -> <code>"This is a test"</code></li>
963<li><code>"the Eiffel Tower"</code> -> <code>"The Eiffel Tower"</code></li>
964<li><code>"/index.html"</code> -> <code>"/index.html"</code></li>
965</ul>
966
967<p>I have a URL with some GET parameters as follows:</p>
968
969<pre><code>www.test.com/t.html?a=1&b=3&c=m2-m3-m4-m5
970</code></pre>
971
972<p>I need to get the whole value of <code>c</code>. I tried to read the URL, but I got only <code>m2</code>. How do I do this using JavaScript?</p>
973
974<p>All I want is to get the website URL. Not the URL as taken from a link. On the page loading I need to be able to grab the full, current URL of the website and set it as a variable to do with as I please.</p>
975
976<p>I want to select all the elements that have the two classes <code>a</code> and <code>b</code>.</p>
977
978<pre><code><element class="a b">
979</code></pre>
980
981<p>So, only the elements that have <em>both</em> classes.</p>
982
983<p>When I use <code>$(".a, .b")</code> it gives me the union, but I want the intersection.</p>
984
985<p>I noticed that JavaScript's <code>new Date()</code> function is very smart in accepting dates in several formats.</p>
986
987<pre><code>Xmas95 = new Date("25 Dec, 1995 23:15:00")
988Xmas95 = new Date("2009 06 12,12:52:39")
989Xmas95 = new Date("20 09 2006,12:52:39")
990</code></pre>
991
992<p>I could not find documentation anywhere showing all the valid string formats while calling <code>new Date()</code> function.</p>
993
994<p>This is for converting a string to a date. If we look at the opposite side, that is, converting a date object to a string, until now I was under the impression that JavaScript doesn't have a built-in API to format a date object into a string.</p>
995
996<blockquote>
997 <p><strong>Editor's note:</strong> The following approach is the asker's attempt that worked on a particular browser but does <em>not</em> work in general; <strong>see the answers on this page</strong> to see some actual solutions.</p>
998</blockquote>
999
1000<p>Today, I played with the <code>toString()</code> method on the date object and surprisingly it serves the purpose of formatting date to strings.</p>
1001
1002<pre><code>var d1 = new Date();
1003d1.toString('yyyy-MM-dd'); //Returns "2009-06-29" in Internet Explorer, but not Firefox or Chrome
1004d1.toString('dddd, MMMM ,yyyy') //Returns "Monday, June 29,2009" in Internet Explorer, but not Firefox or Chrome
1005</code></pre>
1006
1007<p>Also here I couldn't find any documentation on all the ways we can format the date object into a string.</p>
1008
1009<p>Where is the documentation which lists the format specifiers supported by the <code>Date()</code> object?</p>
1010
1011<p>Have a table column I'm trying to expand and hide: </p>
1012
1013<p>jQuery seems to hide the <code>td</code> elements when I select it by <a href="http://docs.jquery.com/Selectors/class#class" rel="noreferrer">class</a> but not by element's <a href="http://docs.jquery.com/Selectors/element#element" rel="noreferrer">name</a>. </p>
1014
1015<p>For example, why does: </p>
1016
1017<pre><code>$(".bold").hide(); // selecting by class works
1018$("tcol1").hide(); // select by element name does not work
1019</code></pre>
1020
1021<p>Note the HTML below, the second column has the same name for all rows. How could I create this collection using the <code>name</code> attribute?</p>
1022
1023<pre><code><tr>
1024 <td>data1</td>
1025 <td name="tcol1" class="bold"> data2</td>
1026</tr>
1027<tr>
1028 <td>data1</td>
1029 <td name="tcol1" class="bold"> data2</td>
1030</tr>
1031<tr>
1032 <td>data1</td>
1033 <td name="tcol1" class="bold"> data2</td>
1034</tr>
1035</code></pre>
1036
1037<p>How do I check if a particular key exists in a JavaScript object or array?</p>
1038
1039<p>If a key doesn't exist, and I try to access it, will it return false? Or throw an error?</p>
1040
1041<p>How do I get the selected value from a dropdown list using JavaScript?</p>
1042
1043<p>I tried the methods below but they all return the selected index instead of the value:</p>
1044
1045<pre><code>var as = document.form1.ddlViewBy.value;
1046var e = document.getElementById("ddlViewBy");
1047var strUser = e.options[e.selectedIndex].value;
1048var value = document.getElementById("ddlViewBy").value;
1049</code></pre>
1050
1051<p>I have an array of JavaScript objects:</p>
1052
1053<pre><code>var objs = [
1054 { first_nom: 'Lazslo', last_nom: 'Jamf' },
1055 { first_nom: 'Pig', last_nom: 'Bodine' },
1056 { first_nom: 'Pirate', last_nom: 'Prentice' }
1057];
1058</code></pre>
1059
1060<p>How can I sort them by the value of <code>last_nom</code> in JavaScript?</p>
1061
1062<p>I know about <code>sort(a,b)</code>, but that only seems to work on strings and numbers. Do I need to add a <code>toString()</code> method to my objects?</p>
1063
1064<p>How do I convert a string to an integer in JavaScript?</p>
1065
1066<p>I have this string:</p>
1067
1068<pre><code>"Test abc test test abc test test test abc test test abc"
1069</code></pre>
1070
1071<p>Doing</p>
1072
1073<pre><code>str = str.replace('abc', '');
1074</code></pre>
1075
1076<p>seems to only remove the first occurrence of <code>abc</code> in the string above. How can I replace <strong>all</strong> occurrences of it?</p>
1077
1078<p>I've a <code><button></code> on the page, when this button is pressed a hidden <code><div></code> is shown using jQuery.</p>
1079
1080<p>How do I scroll to the top of the page using a JavaScript/jQuery command in that function? It is desirable even if the scroll bar instantly jumps to the top. I'm not looking for a smooth scrolling.</p>
1081
1082<p>Here is my object literal:</p>
1083
1084<pre><code>var obj = {key1: value1, key2: value2};
1085</code></pre>
1086
1087<p>How can I add <code>{key3: value3}</code> to the object?</p>
1088
1089<p>How do I convert all elements of my form to a JavaScript object? </p>
1090
1091<p>I'd like to have some way of automatically building a JavaScript object from my form, without having to loop over each element. I do not want a string, as returned by <code>$('#formid').serialize();</code>, nor do I want the map returned by <code>$('#formid').serializeArray();</code></p>
1092
1093<p>I need to determine if a value exists in an array.</p>
1094
1095<p>I am using the following function:</p>
1096
1097<pre><code>Array.prototype.contains = function(obj) {
1098 var i = this.length;
1099 while (i--) {
1100 if (this[i] == obj) {
1101 return true;
1102 }
1103 }
1104 return false;
1105}
1106</code></pre>
1107
1108<p>The above function always returns false.</p>
1109
1110<p>The array values and the function call is as below:</p>
1111
1112<pre><code>arrValues = ["Sam","Great", "Sample", "High"]
1113alert(arrValues.contains("Sam"));
1114</code></pre>
1115
1116<p>Is there a way to empty an array and if so possibly with <code>.remove()</code>?</p>
1117
1118<p>For instance, </p>
1119
1120<pre><code>A = [1,2,3,4];
1121</code></pre>
1122
1123<p>How can I empty that?</p>
1124
1125<p>I would like to move one DIV element inside another. For example, I want to move this (including all children):</p>
1126
1127<pre><code><div id="source">
1128...
1129</div>
1130</code></pre>
1131
1132<p>into this:</p>
1133
1134<pre><code><div id="destination">
1135...
1136</div>
1137</code></pre>
1138
1139<p>so that I have this:</p>
1140
1141<pre><code><div id="destination">
1142 <div id="source">
1143 ...
1144 </div>
1145</div>
1146</code></pre>
1147
1148<pre><code><a href="javascript:void(0)" id="loginlink">login</a>
1149</code></pre>
1150
1151<p>I've seen such <code>href</code>s many times, but I don't know what exactly that means.</p>
1152
1153<p>Recently, I ran some of my JavaScript code through Crockford's <a href="http://www.jslint.com/" rel="noreferrer">JSLint</a>, and it gave the following error:</p>
1154
1155<blockquote>
1156 <p>Problem at line 1 character 1: Missing "use strict" statement.</p>
1157</blockquote>
1158
1159<p>Doing some searching, I realized that some people add <code>"use strict";</code> into their JavaScript code. Once I added the statement, the error stopped appearing. Unfortunately, Google did not reveal much of the history behind this string statement. Certainly it must have something to do with how the JavaScript is interpreted by the browser, but I have no idea what the effect would be.</p>
1160
1161<p>So what is <code>"use strict";</code> all about, what does it imply, and is it still relevant?</p>
1162
1163<p>Do any of the current browsers respond to the <code>"use strict";</code> string or is it for future use?</p>
1164
1165<p>I want a 5 character string composed of characters picked randomly from the set <code>[a-zA-Z0-9]</code>.</p>
1166
1167<p>What's the best way to do this with JavaScript?</p>
1168
1169<p>I'd like to tell the difference between valid and invalid date objects in JS, but couldn't figure out how:</p>
1170
1171<pre><code>var d = new Date("foo");
1172console.log(d.toString()); // shows 'Invalid Date'
1173console.log(typeof d); // shows 'object'
1174console.log(d instanceof Date); // shows 'true'
1175</code></pre>
1176
1177<p>Any ideas for writing an <code>isValidDate</code> function?</p>
1178
1179<ul>
1180<li>Ash recommended <code>Date.parse</code> for parsing date strings, which gives an authoritative way to check if the date string is valid.</li>
1181<li>What I would prefer, if possible, is have my API accept a Date instance and to be able to check/assert whether it's valid or not. Borgar's solution does that, but I need to test it across browsers. I also wonder whether there's a more elegant way.</li>
1182<li>Ash made me consider not having my API accept <code>Date</code> instances at all, this would be easiest to validate.</li>
1183<li>Borgar suggested testing for a <code>Date</code> instance, and then testing for the <code>Date</code>'s time value. If the date is invalid, the time value is <code>NaN</code>. I checked with <a href="http://www.ecma-international.org/ecma-262/6.0/index.html#sec-time-values-and-time-range" rel="noreferrer">ECMA-262</a> and this behavior is in the standard, which is exactly what I'm looking for.</li>
1184</ul>
1185
1186<p>When I want to prevent other event handlers from executing after a certain event is fired, I can use one of two techniques. I'll use jQuery in the examples, but this applies to plain-JS as well:</p>
1187
1188<h3>1. <code>event.preventDefault()</code></h3>
1189
1190<pre><code>$('a').click(function (e) {
1191 // custom handling here
1192 e.preventDefault();
1193});
1194</code></pre>
1195
1196<h3>2. <code>return false</code></h3>
1197
1198<pre><code>$('a').click(function () {
1199 // custom handling here
1200 return false;
1201});
1202</code></pre>
1203
1204<p>Is there any significant difference between those two methods of stopping event propagation?</p>
1205
1206<p>For me, <code>return false;</code> is simpler, shorter and probably less error prone than executing a method. With the method, you have to remember about correct casing, parenthesis, etc. </p>
1207
1208<p>Also, I have to define the first parameter in callback to be able to call the method. Perhaps, there are some reasons why I should avoid doing it like this and use <code>preventDefault</code> instead? What's the better way?</p>
1209
1210<pre><code>$input.disabled = true;
1211</code></pre>
1212
1213<p>or </p>
1214
1215<pre><code>$input.disabled = "disabled";
1216</code></pre>
1217
1218<p>Which is the standard way? And, conversely, how do you enable a disabled input?</p>
1219
1220<p>How do I set and unset a cookie using jQuery, for example create a cookie named <code>test</code> and set the value to <code>1</code>?</p>
1221
1222<blockquote>
1223 <p><strong><em>NOTE</strong>: This question was asked from the viewpoint of ECMAScript version 3 or 5. The answers might become outdated with the introduction of new features in the release of ECMAScript 6.</em></p>
1224</blockquote>
1225
1226<p>What exactly is the function of the <code>var</code> keyword in JavaScript, and what is the difference between</p>
1227
1228<pre><code>var someNumber = 2;
1229var someFunction = function() { doSomething; }
1230var someObject = { }
1231var someObject.someProperty = 5;
1232</code></pre>
1233
1234<p>and</p>
1235
1236<pre><code>someNumber = 2;
1237someFunction = function() { doSomething; }
1238someObject = { }
1239someObject.someProperty = 5;
1240</code></pre>
1241
1242<p>?</p>
1243
1244<p>When would you use either one, and why/what does it do?</p>
1245
1246<p>How do I get current date in JavaScript?</p>
1247
1248<p>How can I generate a random whole number between two specified variables in Javascript, e.g. <code>x = 4</code> and <code>y = 8</code> would output any of 4, 5, 6, 7, 8?</p>
1249
1250<p>I have two JavaScript arrays:</p>
1251
1252<pre><code>var array1 = ["Vijendra","Singh"];
1253var array2 = ["Singh", "Shakya"];
1254</code></pre>
1255
1256<p>I want the output to be:</p>
1257
1258<pre><code>var array3 = ["Vijendra","Singh","Shakya"];
1259</code></pre>
1260
1261<p>The output array should have repeated words removed.</p>
1262
1263<p>How do I merge two arrays in JavaScript so that I get only the unique items from each array in the same order they were inserted into the original arrays?</p>
1264
1265<p>How can I get the selected text (not the selected value) from a drop-down list in jQuery?</p>
1266
1267<p>The <code>new</code> keyword in JavaScript can be quite confusing when it is first encountered, as people tend to think that JavaScript is not an object-oriented programming language.</p>
1268
1269<ul>
1270<li>What is it?</li>
1271<li>What problems does it solve?</li>
1272<li>When is it appropriate and when not?</li>
1273</ul>
1274
1275<p>Usually I would expect a <code>String.contains()</code> method, but there doesn't seem to be one. </p>
1276
1277<p>What is a reasonable way to check for this?</p>
1278
1279<p>How do I debug a Node.js server application?</p>
1280
1281<p>Right now I'm mostly using <em>alert debugging</em> with print statements like this:</p>
1282
1283<pre><code>sys.puts(sys.inspect(someVariable));
1284</code></pre>
1285
1286<p>There must be a better way to debug. I know that <a href="http://en.wikipedia.org/wiki/Google_Chrome" rel="noreferrer">Google Chrome</a> has a command-line debugger. Is this debugger available for Node.js as well?</p>
1287
1288<p>What is the difference between using <code>call</code> and <code>apply</code> to invoke a function?</p>
1289
1290<pre><code>var func = function() {
1291 alert('hello!');
1292};
1293</code></pre>
1294
1295<p><code>func.apply();</code> vs <code>func.call();</code></p>
1296
1297<p>Are there performance differences between the two aforementioned methods? When is it best to use <code>call</code> over <code>apply</code> and vice versa?</p>
1298
1299<p>I'd like to store a JavaScript object in HTML5 <code>localStorage</code>, but my object is apparently being converted to a string.</p>
1300
1301<p>I can store and retrieve primitive JavaScript types and arrays using <code>localStorage</code>, but objects don't seem to work. Should they? </p>
1302
1303<p>Here's my code:</p>
1304
1305<pre><code>var testObject = { 'one': 1, 'two': 2, 'three': 3 };
1306console.log('typeof testObject: ' + typeof testObject);
1307console.log('testObject properties:');
1308for (var prop in testObject) {
1309 console.log(' ' + prop + ': ' + testObject[prop]);
1310}
1311
1312// Put the object into storage
1313localStorage.setItem('testObject', testObject);
1314
1315// Retrieve the object from storage
1316var retrievedObject = localStorage.getItem('testObject');
1317
1318console.log('typeof retrievedObject: ' + typeof retrievedObject);
1319console.log('Value of retrievedObject: ' + retrievedObject);
1320</code></pre>
1321
1322<p>The console output is</p>
1323
1324<pre class="lang-none prettyprint-override"><code>typeof testObject: object
1325testObject properties:
1326 one: 1
1327 two: 2
1328 three: 3
1329typeof retrievedObject: string
1330Value of retrievedObject: [object Object]
1331</code></pre>
1332
1333<p>It looks to me like the <code>setItem</code> method is converting the input to a string before storing it.</p>
1334
1335<p>I see this behavior in Safari, Chrome, and Firefox, so I assume it's my misunderstanding of the <a href="http://www.w3.org/TR/webstorage/" rel="noreferrer">HTML5 Web Storage</a> spec, not a browser-specific bug or limitation.</p>
1336
1337<p>I've tried to make sense of the <em>structured clone</em> algorithm described in <a href="http://www.w3.org/TR/html5/infrastructure.html" rel="noreferrer">http://www.w3.org/TR/html5/infrastructure.html</a>. I don't fully understand what it's saying, but maybe my problem has to do with my object's properties not being enumerable (???) </p>
1338
1339<p>Is there an easy workaround?</p>
1340
1341<hr>
1342
1343<p>Update: The W3C eventually changed their minds about the structured-clone specification, and decided to change the spec to match the implementations. See <a href="https://www.w3.org/Bugs/Public/show_bug.cgi?id=12111" rel="noreferrer">https://www.w3.org/Bugs/Public/show_bug.cgi?id=12111</a>. So this question is no longer 100% valid, but the answers still may be of interest.</p>
1344
1345<p>I understand JSON, but not JSONP. <a href="http://en.wikipedia.org/wiki/JSON" rel="noreferrer">Wikipedia's document on JSON</a> is (was) the top search result for JSONP. It says this:</p>
1346
1347<blockquote>
1348 <p>JSONP or "JSON with padding" is a JSON extension wherein a prefix is specified as an input argument of the call itself.</p>
1349</blockquote>
1350
1351<p>Huh? What call? That doesn't make any sense to me. JSON is a data format. There's no call.</p>
1352
1353<p>The <a href="http://remysharp.com/2007/10/08/what-is-jsonp/" rel="noreferrer">2nd search result</a> is from some guy named <a href="https://stackoverflow.com/users/22617/remy-sharp">Remy</a>, who writes this about JSONP:</p>
1354
1355<blockquote>
1356 <p>JSONP is script tag injection, passing the response from the server in to a user specified function.</p>
1357</blockquote>
1358
1359<p>I can sort of understand that, but it's still not making any sense.</p>
1360
1361<hr>
1362
1363<p>So what is JSONP? Why was it created (what problem does it solve)? And why would I use it? </p>
1364
1365<hr>
1366
1367<p><strong>Addendum</strong>: I've just created <a href="http://en.wikipedia.org/wiki/JSONP" rel="noreferrer">a new page for JSONP</a> on Wikipedia; it now has a clear and thorough description of JSONP, based on <a href="https://stackoverflow.com/users/25330/jvenema">jvenema</a>'s answer.</p>
1368
1369<p>Are there any good resources to get started with Node.JS? Any good tutorials, blogs or books?</p>
1370
1371<p>Of course, I have visited its official website <a href="http://nodejs.org/" rel="noreferrer">http://nodejs.org/</a>, but I didn't think the documentation they have is a good starting point.</p>
1372
1373<p>I've been trying to find a way to write to a file when using Node.js, but with no success. How can I do that?</p>
1374
1375<pre><code>[1,2,3].forEach(function(el) {
1376 if(el === 1) break;
1377});
1378</code></pre>
1379
1380<p>How can I do this using the new <code>forEach</code> method in JavaScript? I've tried <code>return;</code>, <code>return false;</code> and <code>break</code>. <code>break</code> crashes and <code>return</code> does nothing but continue iteration.</p>
1381
1382<p>How do I determine if variable is <code>undefined</code> or <code>null</code>? My code is as follows:</p>
1383
1384<pre class="lang-js prettyprint-override"><code>var EmpName = $("div#esd-names div#name").attr('class');
1385if(EmpName == 'undefined'){
1386 //DO SOMETHING
1387};
1388</code></pre>
1389
1390<pre class="lang-html prettyprint-override"><code><div id="esd-names">
1391 <div id="name"></div>
1392</div>
1393</code></pre>
1394
1395
1396
1397<p>But if I do this, the JavaScript interpreter halts execution.</p>
1398
1399<p>Why does Google prepend <code>while(1);</code> to their (private) JSON responses?</p>
1400
1401<p>For example, here's a response while turning a calendar on and off in <a href="https://calendar.google.com/calendar/about/" rel="noreferrer">Google Calendar</a>:</p>
1402
1403<pre><code>while(1);[['u',[['smsSentFlag','false'],['hideInvitations','false'],
1404 ['remindOnRespondedEventsOnly','true'],
1405 ['hideInvitations_remindOnRespondedEventsOnly','false_true'],
1406 ['Calendar ID stripped for privacy','false'],['smsVerifiedFlag','true']]]]
1407</code></pre>
1408
1409<p>I would assume this is to prevent people from doing an <code>eval()</code> on it, but all you'd really have to do is replace the <code>while</code> and then you'd be set. I would assume the eval prevention is to make sure people write safe JSON parsing code.</p>
1410
1411<p>I've seen this used in a couple of other places, too, but a lot more so with Google (Mail, Calendar, Contacts, etc.) Strangely enough, <a href="https://www.google.com/docs/about/" rel="noreferrer">Google Docs</a> starts with <code>&&&START&&&</code> instead, and Google Contacts seems to start with <code>while(1); &&&START&&&</code>.</p>
1412
1413<p>What's going on here?</p>
1414
1415<p>I am trying to print an integer in <a href="http://en.wikipedia.org/wiki/JavaScript" rel="noreferrer">JavaScript</a> with commas as thousands separators. For example, I want to show the number 1234567 as "1,234,567". How would I go about doing this? </p>
1416
1417<p>Here is how I am doing it:</p>
1418
1419<pre><code>function numberWithCommas(x) {
1420 x = x.toString();
1421 var pattern = /(-?\d+)(\d{3})/;
1422 while (pattern.test(x))
1423 x = x.replace(pattern, "$1,$2");
1424 return x;
1425}
1426</code></pre>
1427
1428<p>Is there a simpler or more elegant way to do it? It would be nice if it works with floats also, but that is not necessary. It does not need to be locale-specific to decide between periods and commas. </p>
1429
1430<p>In Java you can use a <code>for</code> loop to traverse objects in an array as follows:</p>
1431
1432<pre><code>String[] myStringArray = {"Hello", "World"};
1433for (String s : myStringArray)
1434{
1435 // Do something
1436}
1437</code></pre>
1438
1439<p>Can you do the same in JavaScript?</p>
1440
1441<p>I have noticed that there doesn't appear to be a clear explanation of what the <code>this</code> keyword is and how it is correctly (and incorrectly) used in JavaScript on the Stack Overflow site.</p>
1442
1443<p>I have witnessed some very strange behaviour with it and have failed to understand why it has occurred.</p>
1444
1445<p>How does <code>this</code> work and when should it be used?</p>
1446
1447<p>Is there any way to disable the <a href="https://en.wikipedia.org/wiki/Same_origin_policy" rel="noreferrer">Same-origin policy</a> on Google's <a href="http://en.wikipedia.org/wiki/Google_Chrome" rel="noreferrer">Chrome</a> browser?</p>
1448
1449<p>This is strictly for development, not production use.</p>
1450
1451<p>What is the most appropriate way to test if a variable is undefined in JavaScript? I've seen several possible ways:</p>
1452
1453<pre><code>if (window.myVariable)
1454</code></pre>
1455
1456<p>Or</p>
1457
1458<pre><code>if (typeof(myVariable) != "undefined")
1459</code></pre>
1460
1461<p>Or</p>
1462
1463<pre><code>if (myVariable) //This throws an error if undefined. Should this be in Try/Catch?
1464</code></pre>
1465
1466<p>How can I get <code>windowWidth</code>, <code>windowHeight</code>, <code>pageWidth</code>, <code>pageHeight</code>, <code>screenWidth</code>, <code>screenHeight</code>, <code>pageX</code>, <code>pageY</code>, <code>screenX</code>, <code>screenY</code> which will work in all major browsers?</p>
1467
1468<p><img src="https://i.stack.imgur.com/6xPdH.png" alt="screenshot describing which values are wanted"></p>
1469
1470<p>Is there a solid way to detect whether or not a user is using a mobile device in jQuery? Something similar to the CSS @media attribute? I would like to run a different script if the browser is on a handheld device.</p>
1471
1472<p>The jQuery <code>$.browser</code> function is not what I am looking for.</p>
1473
1474<p>How can I format a JavaScript date object to print as <code>10-Aug-2010</code>?</p>
1475
1476<p>What are the differences between JavaScript's <a href="https://developer.mozilla.org/en/docs/Web/API/GlobalEventHandlers/onload" rel="noreferrer"><code>window.onload</code></a> and jQuery's <a href="https://api.jquery.com/ready/" rel="noreferrer"><code>$(document).ready()</code></a> method?</p>
1477
1478<pre><code>!function () {}();
1479</code></pre>
1480
1481<p>How can I determine whether a variable is a string or something else in JavaScript?</p>
1482
1483<p>If I defined an object in JS with:</p>
1484
1485<pre><code>var j={"name":"binchen"};
1486</code></pre>
1487
1488<p>How can I convert the object to JSON? The output string should be:</p>
1489
1490<pre><code>'{"name":"binchen"}'
1491</code></pre>
1492
1493<p>I have a web server written in <a href="http://en.wikipedia.org/wiki/Node.js" rel="noreferrer">Node.js</a> and I would like to launch with a specific folder. I'm not sure how to access arguments in JavaScript. I'm running node like this:</p>
1494
1495<pre><code>$ node server.js folder
1496</code></pre>
1497
1498<p>here <code>server.js</code> is my server code. Node.js help says this is possible:</p>
1499
1500<pre><code>$ node -h
1501Usage: node [options] script.js [arguments]
1502</code></pre>
1503
1504<p>How would I access those arguments in JavaScript? Somehow I was not able to find this information on the web.</p>
1505
1506<p>I want to be able to preview a file (image) before it is uploaded. The preview action should be executed all in the browser without using Ajax to upload the image.</p>
1507
1508<p>How can I do this?</p>
1509
1510<p>How do I check if an element exists if the element is created by <code>.append()</code> method?
1511<code>$('elemId').length</code> doesn't work for me.</p>
1512
1513<p>I'm trying to write a function that either accepts a list of strings, or a single string. If it's a string, then I want to convert it to an array with just the one item. Then I can loop over it without fear of an error. </p>
1514
1515<p>So how do I check if the variable is an array?</p>
1516
1517<hr>
1518
1519<p>I've rounded up the various solutions below and created a <a href="http://jsperf.com/js-isarray-comparison" rel="noreferrer">jsperf test</a>.</p>
1520
1521<p>How can I display JSON in an easy-to-read (for human readers) format? I'm looking primarily for indentation and whitespace, with perhaps even colors / font-styles / etc.</p>
1522
1523<p>Is there a way to read environment variables in Node.js code?</p>
1524
1525<p>Like for example Python's <code>os.environ['HOME']</code>.</p>
1526
1527<p>I'm trying to open a <a href="http://en.wikipedia.org/wiki/Uniform_Resource_Locator" rel="noreferrer">URL</a> in a new tab, as opposed to a popup window. I've seen related questions where the responses would look something like:</p>
1528
1529<pre><code>window.open(url,'_blank');
1530window.open(url);
1531</code></pre>
1532
1533<p>But none of them worked for me, the browser still tried to open a popup window.</p>
1534
1535<p>I want to parse a JSON string in JavaScript. The response is something like</p>
1536
1537<pre><code>var response = '{"result":true,"count":1}';
1538</code></pre>
1539
1540<p>How can I get the values <code>result</code> and <code>count</code> from this?</p>
1541
1542<p>Is there a way to generate a random number in a specified range (e.g. from 1 to 6: 1, 2, 3, 4, 5, or 6) in JavaScript?</p>
1543
1544<p>I am new to this kind of stuff, but lately I've been hearing a lot about how good <a href="http://en.wikipedia.org/wiki/Node.js" rel="nofollow noreferrer">Node.js</a> is. Considering how much I love working with jQuery and JavaScript in general, I can't help but wonder how to decide when to use Node.js. The web application I have in mind is something like <a href="https://en.wikipedia.org/wiki/Bitly" rel="nofollow noreferrer">Bitly</a> - takes some content, archives it. </p>
1545
1546<p>From all the homework I have been doing in the last few days, I obtained the following information. Node.js </p>
1547
1548<ul>
1549<li>is a command-line tool that can be run as a regular web server and lets one run JavaScript programs</li>
1550<li>utilizes the great <a href="http://en.wikipedia.org/wiki/V8_%28JavaScript_engine%29" rel="nofollow noreferrer">V8 JavaScript engine</a></li>
1551<li>is very good when you need to do several things at the same time</li>
1552<li>is event-based so all the wonderful <a href="http://en.wikipedia.org/wiki/Ajax_%28programming%29" rel="nofollow noreferrer">Ajax</a>-like stuff can be done on the server side</li>
1553<li>lets us share code between the browser and the backend</li>
1554<li>lets us talk with MySQL</li>
1555</ul>
1556
1557<p>Some of the sources that I have come across are:</p>
1558
1559<ul>
1560<li><a href="http://www.stoimen.com/blog/2010/11/16/diving-into-node-js-introduction-and-installation/" rel="nofollow noreferrer">Diving into Node.js – Introduction and Installation</a></li>
1561<li><a href="http://debuggable.com/posts/understanding-node-js:4bd98440-45e4-4a9a-8ef7-0f7ecbdd56cb" rel="nofollow noreferrer">Understanding NodeJS</a></li>
1562<li><a href="http://blog.osbutler.com/categories/node-by-example/?page=3" rel="nofollow noreferrer">Node by Example</a> (<a href="http://archive.is/exhaR" rel="nofollow noreferrer">Archive.is</a>)</li>
1563<li><a href="http://dailyjs.com/2010/11/01/node-tutorial/" rel="nofollow noreferrer">Let’s Make a Web App: NodePad</a></li>
1564</ul>
1565
1566<p>Considering that Node.js can be run almost out-of-the-box on <a href="http://en.wikipedia.org/wiki/Amazon_Elastic_Compute_Cloud" rel="nofollow noreferrer">Amazon's EC2</a> instances, I am trying to understand what type of problems require Node.js as opposed to any of the mighty kings out there like <a href="http://en.wikipedia.org/wiki/PHP" rel="nofollow noreferrer">PHP</a>, <a href="http://en.wikipedia.org/wiki/Python_%28programming_language%29" rel="nofollow noreferrer">Python</a> and <a href="http://en.wikipedia.org/wiki/Ruby_%28programming_language%29" rel="nofollow noreferrer">Ruby</a>. I understand that it really depends on the expertise one has on a language, but my question falls more into the general category of: When to use a particular framework and what type of problems is it particularly suited for?</p>
1567
1568<p>Which method of checking if a variable has been initialized is better/correct?
1569(Assuming the variable could hold anything (string, int, object, function, etc.))</p>
1570
1571<pre><code>if (elem) { // or !elem
1572</code></pre>
1573
1574<p>or</p>
1575
1576<pre><code>if (typeof(elem) !== 'undefined') {
1577</code></pre>
1578
1579<p>or</p>
1580
1581<pre><code>if (elem != null) {
1582</code></pre>
1583
1584<p>What is the purpose of Node.js module.exports and how do you use it?</p>
1585
1586<p>I can't seem to find any information on this, but it appears to be a rather important part of Node.js as I often see it in source code. </p>
1587
1588<p>According to the <a href="http://nodejs.org/docs/v0.4.2/api/globals.html#module" rel="noreferrer">Node.js documentation</a>:</p>
1589
1590<blockquote>
1591 <p><strong>module</strong> </p>
1592
1593 <p>A reference to the current
1594 <code>module</code>. In particular <code>module.exports</code>
1595 is the same as the exports object. See
1596 <code>src/node.js</code> for more information.</p>
1597</blockquote>
1598
1599<p>But this doesn't really help.</p>
1600
1601<p>What exactly does <code>module.exports</code> do, and what would a simple example be?</p>
1602
1603<p>How can I refresh a page with jQuery?</p>
1604
1605<p>Is there a universal JavaScript function that checks that a variable has a value and ensures that it's not <code>undefined</code> or <code>null</code>? I've got this code, but I'm not sure if it covers all cases:</p>
1606
1607<pre><code>function isEmpty(val){
1608 return (val === undefined || val == null || val.length <= 0) ? true : false;
1609}
1610</code></pre>
1611
1612<p>I have an array of integers, and I'm using the <code>.push()</code> method to add elements to it.</p>
1613
1614<p>Is there a simple way to remove a specific element from an array? The equivalent of something like <code>array.remove(int);</code>.</p>
1615
1616<p>I have to use <em>core</em> JavaScript - <em>no</em> frameworks are allowed.</p>
1617
1618<p>So <a href="http://api.jquery.com/category/version/1.6/" rel="noreferrer">jQuery 1.6</a> has the new function <a href="http://api.jquery.com/prop/" rel="noreferrer"><code>prop()</code></a>.</p>
1619
1620<pre><code>$(selector).click(function(){
1621 //instead of:
1622 this.getAttribute('style');
1623 //do i use:
1624 $(this).prop('style');
1625 //or:
1626 $(this).attr('style');
1627})
1628</code></pre>
1629
1630<p>or in this case do they do the same thing?</p>
1631
1632<p>And if I <em>do</em> have to switch to using <code>prop()</code>, all the old <code>attr()</code> calls will break if i switch to 1.6?</p>
1633
1634<p><strong>UPDATE</strong></p>
1635
1636<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
1637<div class="snippet-code">
1638<pre class="snippet-code-js lang-js prettyprint-override"><code>selector = '#id'
1639
1640$(selector).click(function() {
1641 //instead of:
1642 var getAtt = this.getAttribute('style');
1643 //do i use:
1644 var thisProp = $(this).prop('style');
1645 //or:
1646 var thisAttr = $(this).attr('style');
1647
1648 console.log(getAtt, thisProp, thisAttr);
1649});</code></pre>
1650<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.0/jquery.min.js"></script>
1651<div id='id' style="color: red;background: orange;">test</div></code></pre>
1652</div>
1653</div>
1654</p>
1655
1656<p>(see also this fiddle: <a href="http://jsfiddle.net/maniator/JpUF2/" rel="noreferrer">http://jsfiddle.net/maniator/JpUF2/</a>)</p>
1657
1658<p>The console logs the <code>getAttribute</code> as a string, and the <code>attr</code> as a string, but the <code>prop</code> as a <code>CSSStyleDeclaration</code>, Why? And how does that affect my coding in the future?</p>
1659
1660<p>I have this <code>input</code> element:</p>
1661
1662<pre><code><input type="text" class="textfield" value="" id="subject" name="subject">
1663</code></pre>
1664
1665<p>Then I have some other elements, like other text inputs, textareas, etc.</p>
1666
1667<p>When the user clicks on that <code>input</code> with <code>#subject</code>, the page should scroll to the last element of the page with a nice animation. It should be a scroll to bottom and not to top.</p>
1668
1669<p>The last item of the page is a <code>submit</code> button with <code>#submit</code>:</p>
1670
1671<pre><code><input type="submit" class="submit" id="submit" name="submit" value="Ok, Done.">
1672</code></pre>
1673
1674<p>The animation should not be too fast and should be fluid.</p>
1675
1676<p>I am running the latest jQuery version. I prefer to not install any plugin but to use the default jQuery features to achieve this.</p>
1677
1678<p>This is valid and returns the string <code>"10"</code> in JavaScript (<a href="http://sla.ckers.org/forum/read.php?24,33349,33405" rel="noreferrer">more examples here</a>):</p>
1679
1680<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
1681<div class="snippet-code">
1682<pre class="snippet-code-js lang-js prettyprint-override"><code>console.log(++[[]][+[]]+[+[]])</code></pre>
1683</div>
1684</div>
1685</p>
1686
1687<p>Why? What is happening here?</p>
1688
1689<p>I've got an array:</p>
1690
1691<pre><code>myArray = [{'id':'73','foo':'bar'},{'id':'45','foo':'bar'}, etc.]
1692</code></pre>
1693
1694<p>I'm unable to change the structure of the array. I'm being passed an id of <code>45</code>, and I want to get <code>'bar'</code> for that object in the array. </p>
1695
1696<p>How do I do this in JavaScript or using jQuery?</p>
1697
1698<p>When copying an array in JavaScript to another array:</p>
1699
1700<pre><code>var arr1 = ['a','b','c'];
1701var arr2 = arr1;
1702arr2.push('d'); //Now, arr1 = ['a','b','c','d']
1703</code></pre>
1704
1705<p>I realized that <code>arr2</code> refers to the same array as <code>arr1</code>, rather than a new, independent array. How can I copy the array to get two independent arrays?</p>
1706
1707<p>I have a need to add or prepend elements at the beginning of an array.</p>
1708
1709<p>For example, if my array looks like below:</p>
1710
1711<pre><code>[23, 45, 12, 67]
1712</code></pre>
1713
1714<p>And the response from my AJAX call is <code>34</code>, I want the updated array to be like the following:</p>
1715
1716<pre><code>[34, 23, 45, 12, 67]
1717</code></pre>
1718
1719<p>Currently I am planning to do it like this:</p>
1720
1721<pre><code>var newArray = [];
1722newArray.push(response);
1723
1724for (var i = 0; i < theArray.length; i++) {
1725 newArray.push(theArray[i]);
1726}
1727
1728theArray = newArray;
1729delete newArray;
1730</code></pre>
1731
1732<p>Is there any better way to do this? Does Javascript have any built-in functionality that does this?</p>
1733
1734<p>The complexity of my method is <code>O(n)</code> and it would be really interesting to see better implementations.</p>
1735
1736<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
1737<div class="snippet-code">
1738<pre class="snippet-code-js lang-js prettyprint-override"><code>var obj = {
1739 name: "Simon",
1740 age: "20",
1741 clothing: {
1742 style: "simple",
1743 hipster: false
1744 }
1745}
1746
1747for(var propt in obj){
1748 alert(propt + ': ' + obj[propt]);
1749}</code></pre>
1750</div>
1751</div>
1752</p>
1753
1754<p>How does the variable <code>propt</code> represent the properties of the object? It's not a built-in method or property. Why does it come up with every property in the object?</p>
1755
1756<p>How can I loop through all the entries in an array using JavaScript?</p>
1757
1758<p>I thought it was something like this:</p>
1759
1760<pre><code>forEach(instance in theArray)
1761</code></pre>
1762
1763<p>Where <code>theArray</code> is my array, but this seems to be incorrect.</p>
1764
1765<p>How does data binding work in the <code>AngularJS</code> framework?</p>
1766
1767<p>I haven't found technical details on <a href="http://angularjs.org" rel="noreferrer">their site</a>. It's more or less clear how it works when data is propagated from view to model. But how does AngularJS track changes of model properties without setters and getters?</p>
1768
1769<p>I found that there are <a href="https://stackoverflow.com/questions/1029241/javascript-object-watch-for-all-browsers">JavaScript watchers</a> that may do this work. But they are not supported in <a href="http://en.wikipedia.org/wiki/Internet_Explorer_6" rel="noreferrer">Internet Explorer 6</a> and <a href="http://en.wikipedia.org/wiki/Internet_Explorer_7" rel="noreferrer">Internet Explorer 7</a>. So how does AngularJS know that I changed for example the following and reflected this change on a view?</p>
1770
1771<pre><code>myobject.myproperty="new value";
1772</code></pre>
1773
1774<p>Okay, this might just be a silly question, though I'm sure there are plenty of other people asking the same question from time to time. Me, I just want to make 100% sure about it either way. With jQuery we all know the wonderful</p>
1775
1776<pre><code>$('document').ready(function(){});
1777</code></pre>
1778
1779<p>However, let's say I want to run a function that is written in standard JavaScript with no library backing it, and that I want to launch a function as soon as the page is ready to handle it. What's the proper way to approach this?</p>
1780
1781<p>I know I can do:</p>
1782
1783<pre><code>window.onload="myFunction()";
1784</code></pre>
1785
1786<p>...or I can use the <code>body</code> tag:</p>
1787
1788<pre><code><body onload="myFunction()">
1789</code></pre>
1790
1791<p>...or I can even try at the bottom of the page after everything, but the end <code>body</code> or <code>html</code> tag like:</p>
1792
1793<pre><code><script type="text/javascript">
1794 myFunction();
1795</script>
1796</code></pre>
1797
1798<p>What is a cross-browser(old/new)-compliant method of issuing one or more functions in a manner like jQuery's <code>$.ready()</code>?</p>
1799
1800<p>I'd like to round at most 2 decimal places, but <em>only if necessary</em>.</p>
1801
1802<p>Input:</p>
1803
1804<pre><code>10
18051.7777777
18069.1
1807</code></pre>
1808
1809<p>Output:</p>
1810
1811<pre><code>10
18121.78
18139.1
1814</code></pre>
1815
1816<p>How can I do this in <code>JavaScript</code>? </p>
1817
1818<p>Since the upgrade to iOS 6, we are seeing Safari's web view take the liberty of caching <code>$.ajax</code> calls. This is in the context of a PhoneGap application so it is using the Safari WebView. Our <code>$.ajax</code> calls are <code>POST</code> methods and we have cache set to false <code>{cache:false}</code>, but still this is happening. We tried manually adding a <code>TimeStamp</code> to the headers but it did not help.</p>
1819
1820<p>We did more research and found that Safari is only returning cached results for web services that have a function signature that is static and does not change from call to call. For instance, imagine a function called something like:</p>
1821
1822<pre><code>getNewRecordID(intRecordType)
1823</code></pre>
1824
1825<p>This function receives the same input parameters over and over again, but the data it returns should be different every time.</p>
1826
1827<p>Must be in Apple's haste to make iOS 6 zip along impressively they got too happy with the cache settings. Has anyone else seen this behavior on iOS 6? If so, what exactly is causing it?</p>
1828
1829<hr>
1830
1831<p>The workaround that we found was to modify the function signature to be something like this:</p>
1832
1833<pre><code>getNewRecordID(intRecordType, strTimestamp)
1834</code></pre>
1835
1836<p>and then always pass in a <code>TimeStamp</code> parameter as well, and just discard that value on the server side. This works around the issue. I hope this helps some other poor soul who spends 15 hours on this issue like I did!</p>
1837
1838<p>Can you please describe what the TypeScript language is?</p>
1839
1840<p>What can it do that JavaScript or available libraries cannot do, that would give me reason to consider it?</p>
1841
1842<p>Why would someone prefer either the <a href="http://lodash.com/">lodash.js</a> or <a href="http://underscorejs.org/">underscore.js</a> utility library over the other?</p>
1843
1844<p>Lodash seems to be a drop-in replacement for underscore, the latter having been around longer.</p>
1845
1846<p>I think both are brilliant, but I do not know enough about how they work to make an educated comparison, and I would like to know more about the differences.</p>
1847
1848<p>I have a function <code>foo</code> which makes an Ajax request. How can I return the response from <code>foo</code>? </p>
1849
1850<p>I tried returning the value from the <code>success</code> callback as well as assigning the response to a local variable inside the function and returning that one, but none of those ways actually return the response.</p>
1851
1852<pre><code>function foo() {
1853 var result;
1854
1855 $.ajax({
1856 url: '...',
1857 success: function(response) {
1858 result = response;
1859 // return response; // <- I tried that one as well
1860 }
1861 });
1862
1863 return result;
1864}
1865
1866var result = foo(); // It always ends up being `undefined`.
1867</code></pre>
1868
1869<p>Suppose I'm familiar with developing client-side applications in <a href="http://jquery.com/" rel="noreferrer">jQuery</a>, but now I'd like to start using <a href="http://angularjs.org/" rel="noreferrer">AngularJS</a>. Can you describe the paradigm shift that is necessary? Here are a few questions that might help you frame an answer:</p>
1870
1871<ul>
1872<li>How do I architect and design client-side web applications differently? What is the biggest difference?</li>
1873<li>What should I stop doing/using; What should I start doing/using instead?</li>
1874<li>Are there any server-side considerations/restrictions?</li>
1875</ul>
1876
1877<p>I'm not looking for a detailed comparison between <code>jQuery</code> and <code>AngularJS</code>.</p>
1878
1879<p>I copied package.json from another project and now want to bump all of the dependencies to their latest versions since this is a fresh project and I don't mind fixing something if it breaks.</p>
1880
1881<p>What's the easiest way to do this?</p>
1882
1883<p>The best way I know of now is to run <code>npm info express version</code> then update package.json manually for each one. There must be a better way.</p>
1884
1885<pre><code>{
1886 "name": "myproject",
1887 "description": "my node project",
1888 "version": "1.0.0",
1889 "engines": {
1890 "node": "0.8.4",
1891 "npm": "1.1.65"
1892 },
1893 "private": true,
1894 "dependencies": {
1895 "express": "~3.0.3", // how do I get these bumped to latest?
1896 "mongodb": "~1.2.5",
1897 "underscore": "~1.4.2",
1898 "rjs": "~2.9.0",
1899 "jade": "~0.27.2",
1900 "async": "~0.1.22"
1901 }
1902}
1903</code></pre>
1904
1905<hr>
1906
1907<p>I am now a collaborator on <a href="https://github.com/tjunnone/npm-check-updates" rel="noreferrer">npm-check-updates</a>, which is a great solution to this problem.</p>
1908
1909<p>I'm seeing error messages about a file, <code>min.map</code>, being not found:</p>
1910
1911<blockquote>
1912 <p>GET jQuery's jquery-1.10.2.min.map is triggering a 404 (Not Found)</p>
1913</blockquote>
1914
1915<hr>
1916
1917<h3>Screenshot</h3>
1918
1919<p><img src="https://i.stack.imgur.com/M6CMw.png" alt="enter image description here"></p>
1920
1921<p>Where is this coming from?</p>
1922
1923<p>What is the fundamental difference between <code>bower</code> and <code>npm</code>? Just want something plain and simple. I've seen some of my colleagues use <code>bower</code> and <code>npm</code> interchangeably in their projects.</p>
1924
1925<p>I have a constructor function which registers an event handler:</p>
1926
1927<p><div class="snippet" data-lang="js" data-hide="false">
1928<div class="snippet-code">
1929<pre class="snippet-code-js lang-js prettyprint-override"><code>function MyConstructor(data, transport) {
1930 this.data = data;
1931 transport.on('data', function () {
1932 alert(this.data);
1933 });
1934}
1935
1936// Mock transport object
1937var transport = {
1938 on: function(event, callback) {
1939 setTimeout(callback, 1000);
1940 }
1941};
1942
1943// called as
1944var obj = new MyConstructor('foo', transport);</code></pre>
1945</div>
1946</div>
1947</p>
1948
1949<p>However, I'm not able to access the <code>data</code> property of the created object inside the callback. It looks like <code>this</code> does not refer to the object that was created but to an other one.</p>
1950
1951<p>I also tried to use an object method instead of an anonymous function:</p>
1952
1953<pre><code>function MyConstructor(data, transport) {
1954 this.data = data;
1955 transport.on('data', this.alert);
1956}
1957
1958MyConstructor.prototype.alert = function() {
1959 alert(this.name);
1960};
1961</code></pre>
1962
1963<p>but it exhibits the same problems.</p>
1964
1965<p>How can I access the correct object?</p>
1966
1967<p>I'm planning to use AngularJS in my big applications. So I'm in the process to find out the right modules to use.</p>
1968
1969<p>What is the difference between <strong>ngRoute (angular-route.js)</strong> and <strong>ui-router (angular-ui-router.js)</strong> modules?</p>
1970
1971<p>In many articles when <em>ngRoute</em> is used, route is configured with <strong><em>$routeProvider</em></strong>. However, when used with <em>ui-router</em>, route is configured with <strong><em>$stateProvider and $urlRouterProvider</em></strong>. </p>
1972
1973<p>Which module should I use for better manageability and extensibility?</p>
1974
1975<p>So apparently because of the recent scams, the developer tools is exploited by people to post spam and even used to "hack" accounts. Facebook has blocked the developer tools, and I can't even use the console.</p>
1976
1977<p><img src="https://i.stack.imgur.com/Wiatp.png" alt="Enter image description here"></p>
1978
1979<p>How did they do that?? <a href="https://stackoverflow.com/questions/7559409/disable-developer-tools">One Stack Overflow post claimed that it is not possible</a>, but Facebook has proven them wrong.</p>
1980
1981<p>Just go to Facebook and open up the developer tools, type one character into the console, and this warning pops up. No matter what you put in, it will not get executed.</p>
1982
1983<p>How is this possible?</p>
1984
1985<p>They even blocked auto-complete in the console:</p>
1986
1987<p><img src="https://i.stack.imgur.com/j0Zmx.png" alt="Enter image description here"></p>
1988
1989<p><strong>What I am looking for:</strong></p>
1990
1991<p>A way to style one <strong>HALF</strong> of a character. (In this case, half the letter being transparent)</p>
1992
1993<p><strong>What I have currently searched for and tried (With no luck):</strong></p>
1994
1995<ul>
1996<li>Methods for styling half of a character/letter</li>
1997<li>Styling part of a character with CSS or JavaScript</li>
1998<li>Apply CSS to 50% of a character</li>
1999</ul>
2000
2001<p>Below is an example of what I am trying to obtain.</p>
2002
2003<p><img src="https://i.stack.imgur.com/SaH8v.png" alt="x"></p>
2004
2005<p>Does a CSS or JavaScript solution exist for this, or am I going to have to resort to images? I would prefer not to go the image route as this text will end up being generated dynamically.</p>
2006
2007<hr>
2008
2009<p><strong>UPDATE:</strong></p>
2010
2011<p>Since many have asked why I would ever want to style half of a character, this is why. My city had recently spent $250,000 to define a new "brand" for itself. This <strong><a href="https://web.archive.org/web/20140428135239/http://halifaxdefined.ca/img/halifax_logo_new.png" rel="noreferrer">logo</a></strong> is what they came up with. Many people have complained about the simplicity and lack of creativity and continue to do so. My goal was to come up with this <strong><a href="http://gameovercancer.ca/tests/brandgenerator/" rel="noreferrer">website</a></strong> as a joke. Type in 'Halifax' and you will see what I mean.</p>
2012
2013<p>I've read <a href="https://stackoverflow.com/questions/32021763/what-could-be-the-downsides-of-using-redux-instead-of-flux">this answer</a>, <a href="http://redux.js.org/docs/recipes/ReducingBoilerplate.html" rel="noreferrer">reducing boilerplate</a>, looked at few GitHub examples and even tried redux a little bit (todo apps). </p>
2014
2015<p>As I understand, <a href="http://redux.js.org/docs/introduction/Motivation.html" rel="noreferrer">official redux doc motivations</a> provide pros comparing to traditional MVC architectures. BUT it doesn't provide an answer to the question: </p>
2016
2017<p><strong>Why you should use Redux over Facebook Flux?</strong> </p>
2018
2019<p><em>Is that only a question of programming styles: functional vs non-functional? Or the question is in abilities/dev-tools that follow from redux approach? Maybe scaling? Or testing?</em></p>
2020
2021<p><em>Am I right if I say that redux is a flux for people who come from functional languages?</em> </p>
2022
2023<p><strong>To answer this question you may compare the complexity of implementation redux's motivation points on flux vs redux.</strong></p>
2024
2025<p>Here are motivation points from <a href="http://redux.js.org/docs/introduction/Motivation.html" rel="noreferrer">official redux doc motivations</a>:</p>
2026
2027<ol>
2028<li>Handling optimistic updates (<em>as I understand, it hardly depends on 5th point. Is it hard to implement it in facebook flux?</em>)</li>
2029<li>Rendering on the server (<em>facebook flux also can do this. Any benefits comparing to redux?</em>)</li>
2030<li>Fetching data before performing route transitions (<em>Why it can't be achieved in facebook flux? What's the benefits?</em>)</li>
2031<li>Hot reload (<em>It's possible with <a href="http://gaearon.github.io/react-hot-loader/" rel="noreferrer">React Hot Reload</a>. Why do we need redux?</em>)</li>
2032<li>Undo/Redo functionality</li>
2033<li>Any other points? Like persisting state...</li>
2034</ol>
2035
2036<blockquote>
2037 <p><strong>Moderator note:</strong> Please resist the urge to edit the code or remove this notice. The pattern of whitespace may be part of the question and therefore should not be tampered with unnecessarily. If you are in the "whitespace is insignificant" camp, you should be able to accept the code as is.</p>
2038</blockquote>
2039
2040<p>Is it ever possible that <code>(a== 1 && a ==2 && a==3)</code> could evaluate to <code>true</code> in JavaScript?</p>
2041
2042<p>This is an interview question asked by a major tech company. It happened two weeks back, but I'm still trying to find the answer. I know we never write such code in our day-to-day job, but I'm curious.</p>