When should I use double or single quotes in JavaScript?

The most likely reason for use of single vs. double in different libraries is programmer preference and/or API consistency. Other than being consistent, use whichever best suits the string. Using the other type of quote as a literal: alert(‘Say “Hello”‘); alert(“Say ‘Hello'”); This can get complicated: alert(“It’s \”game\” time.”); alert(‘It\’s “game” time.’); Another option, new … Read more

Get selected value in dropdown list using JavaScript

Given a select element that looks like this: <select id=”ddlViewBy”> <option value=”1″>test1</option> <option value=”2″ selected=”selected”>test2</option> <option value=”3″>test3</option> </select> Running this code: var e = document.getElementById(“ddlViewBy”); var value = e.value; var text = e.options[e.selectedIndex].text; Results in: value == 2 text == “test2” Interactive example: var e = document.getElementById(“ddlViewBy”); function onChange() { var value = e.value; var … Read more

Iterate through object properties

Iterating over properties requires this additional hasOwnProperty check: for (var prop in obj) { if (Object.prototype.hasOwnProperty.call(obj, prop)) { // do stuff } } It’s necessary because an object’s prototype contains additional properties for the object which are technically part of the object. These additional properties are inherited from the base object class, but are still … Read more

JavaScript equivalent to printf/String.Format

Current JavaScript From ES6 on you could use template strings: let soMany = 10; console.log(`This is ${soMany} times easier!`); // “This is 10 times easier! See Kim’s answer below for details. Older answer Try sprintf() for JavaScript. If you really want to do a simple format method on your own, don’t do the replacements successively … Read more

How to format numbers as currency strings

Intl.NumberFormat JavaScript has a number formatter (part of the Internationalization API). // Create our number formatter. var formatter = new Intl.NumberFormat(‘en-US’, { style: ‘currency’, currency: ‘USD’, // These options are needed to round to whole numbers if that’s what you want. //minimumFractionDigits: 0, // (this suffices for whole numbers, but will print 2500.10 as $2,500.1) … Read more

$(document).ready equivalent without jQuery

There is a standards based replacement,DOMContentLoaded that is supported by over 99% of browsers, though not IE8: document.addEventListener(“DOMContentLoaded”, function(event) { //do work }); jQuery’s native function is much more complicated than just window.onload, as depicted below. function bindReady(){ if ( readyBound ) return; readyBound = true; // Mozilla, Opera and webkit nightlies currently support this … Read more

error code: 521