What is the scope of variables in JavaScript?

TLDR JavaScript has lexical (also called static) scoping and closures. This means you can tell the scope of an identifier by looking at the source code. The four scopes are: Global – visible by everything Function – visible within a function (and its sub-functions and blocks) Block – visible within a block (and its sub-blocks) … Read more

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

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)