Best javascript syntactic sugar

JavascriptLanguage FeaturesSyntactic Sugar

Javascript Problem Overview


Here are some gems:

Literals:

var obj = {}; // Object literal, equivalent to var obj = new Object();
var arr = []; // Array literal, equivalent to var arr = new Array();
var regex = /something/; // Regular expression literal, equivalent to var regex = new RegExp('something');

Defaults:

arg = arg || 'default'; // if arg evaluates to false, use 'default', which is the same as:
arg = !!arg ? arg : 'default';

Of course we know anonymous functions, but being able to treat them as literals and execute them on the spot (as a closure) is great:

(function() { ... })(); // Creates an anonymous function and executes it

Question: What other great syntactic sugar is available in javascript?

Javascript Solutions


Solution 1 - Javascript

Getting the current datetime as milliseconds:

Date.now()

For example, to time the execution of a section of code:

var start = Date.now();
// some code
alert((Date.now() - start) + " ms elapsed");

Solution 2 - Javascript

Object membership test:

var props = { a: 1, b: 2 };

("a" in props) // true ("b" in props) // true ("c" in props) // false

Solution 3 - Javascript

In Mozilla (and reportedly IE7) you can create an XML constant using:

var xml = <elem></elem>;

You can substitute variables as well:

var elem = "html";
var text = "Some text";
var xml = <{elem}>{text}</{elem}>;

Solution 4 - Javascript

Using anonymous functions and a closure to create a private variable (information hiding) and the associated get/set methods:

var getter, setter;

(function()
{
   var _privateVar=123;
   getter = function() { return _privateVar; };
   setter = function(v) { _privateVar = v; };
})()

Solution 5 - Javascript

Being able to extend native JavaScript types via prototypal inheritance.

String.prototype.isNullOrEmpty = function(input) {
    return input === null || input.length === 0;
}

Solution 6 - Javascript

Use === to compare value and type:

var i = 0;
var s = "0";

if (i == s) // true

if (i === s) // false

Solution 7 - Javascript

Multi-line strings:

var str = "This is 
all one
string.";

Since you cannot indent the subsequent lines without also adding the whitespace into the string, people generally prefer to concatenate with the plus operator. But this does provide a nice here document capability.

Solution 8 - Javascript

Resize the Length of an Array

length property is a not read only. You can use it to increase or decrease the size of an array.

var myArray = [1,2,3];
myArray.length // 3 elements.
myArray.length = 2; //Deletes the last element.
myArray.length = 20 // Adds 18 elements to the array; the elements have the empty value. A sparse array.

Solution 9 - Javascript

Repeating a string such as "-" a specific number of times by leveraging the join method on an empty array:

var s = new Array(repeat+1).join("-");

Results in "---" when repeat == 3.

Solution 10 - Javascript

Like the default operator, || is the guard operator, &&.

answer = obj && obj.property

as opposed to

if (obj) {
    answer = obj.property;
}
else {
    answer = null;
}

Solution 11 - Javascript

var tags = {
    name: "Jack",
    location: "USA"
};

"Name: {name}<br>From {location}".replace(/\{(.*?)\}/gim, function(all, match){
    return tags[match];
});

callback for string replace is just useful.

Solution 12 - Javascript

Getters and setters:

function Foo(bar)
{
    this._bar = bar;
}

Foo.prototype =
{
    get bar()
    {
        return this._bar;
    },

    set bar(bar)
    {
        this._bar = bar.toUpperCase();
    }
};

Gives us:

>>> var myFoo = new Foo("bar");
>>> myFoo.bar
"BAR"
>>> myFoo.bar = "Baz";
>>> myFoo.bar
"BAZ"

Solution 13 - Javascript

This isn't a javascript exclusive, but saves like three lines of code:

check ? value1 : value2

Solution 14 - Javascript

A little bit more on levik's example:

var foo = (condition) ? value1 : value2;

Solution 15 - Javascript

The Array#forEach on Javascript 1.6

myArray.forEach(function(element) { alert(element); });

Solution 16 - Javascript

Following obj || {default:true} syntax :

calling your function with this : hello(neededOne && neededTwo && needThree) if one parameter is undefined or false then it will call hello(false), sometimes usefull

Solution 17 - Javascript

In parsing situations with a fixed set of component parts:

var str = "John Doe";

You can assign the results directly into variables, using the "destructuring assignment" synatx:

var [fname, lname] = str.split(" ");
alert(lname + ", " + fname);

Which is a bit more readable than:

var a = str.split(" ");
alert(a[1] + ", " + a[0]);

Alternately:

var [str, fname, lname] = str.match(/(.*) (.*)/);

Note that this is a Javascript 1.7 feature. So that's Mozilla 2.0+ and Chrome 6+ browsers, at this time.

Solution 18 - Javascript

Immediately Invoked Arrow function:

var test = "hello, world!";
(() => test)(); //returns "hello, world!";

Solution 19 - Javascript

I forgot:

(function() { ... }).someMethod(); // Functions as objects

Solution 20 - Javascript

Create an anonymous object literal with simply: ({})

Example: need to know if objects have the valueOf method:

var hasValueOf = !!({}).valueOf

Bonus syntactic sugar: the double-not '!!' for converting pretty much anything into a Boolean very succinctly.

Solution 21 - Javascript

I love being able to eval() a json string and get back a fully populated data structure. I Hate having to write everything at least twice (once for IE, again for Mozilla).

Solution 22 - Javascript

Assigining the frequently used keywords (or any methods) to the simple variables like ths

  var $$ = document.getElementById;

  $$('samText');

Solution 23 - Javascript

JavaScript's Date class providing a semi-"Fluent Interface". This makes up for not being able to extract the date portion from a Date class directly:

var today = new Date((new Date()).setHours(0, 0, 0, 0));

It's not a fully Fluent Interface because the following will only give us a numerical value which is not actually a Date object:

var today = new Date().setHours(0, 0, 0, 0);

Solution 24 - Javascript

Default fallback:

var foo = {}; // empty object literal

alert(foo.bar) // will alert "undefined"

alert(foo.bar || "bar"); // will alert the fallback ("bar")

A practical example:

// will result in a type error
if (foo.bar.length === 0)

// with a default fallback you are always sure that the length
// property will be available.
if ((foo.bar || "").length === 0) 

Solution 25 - Javascript

I love how simple it is to work with lists:

var numberName = ["zero", "one", "two", "three", "four"][number];

And hashes:

var numberValue = {"zero":0, "one":1, "two":2, "three":3, "four":4}[numberName];

In most other languages this would be quite heavy code. Value defaults are also lovely. For example error code reporting:

var errorDesc = {301: "Moved Permanently",
                 404: "Resource not found",
                 503: "Server down"
                }[errorNo] || "An unknown error has occurred";
                 

Solution 26 - Javascript

Here's one I just discovered: null check before calling function:

a = b && b.length;

This is a shorter equivalent to:

a = b ? b.length : null;

The best part is that you can check a property chain:

a = b && b.c && b.c.length;

Solution 27 - Javascript

int to string cast

var i = 12;
var s = i+"";

Solution 28 - Javascript

element.innerHTML = "";  // Replaces body of HTML element with an empty string.

A shortcut to delete all child nodes of element.

Solution 29 - Javascript

Convert string to integer defaulting to 0 if imposible,

0 | "3" //result = 3
0 | "some string" -> //result = 0
0 | "0" -> 0 //result = 0

Can be useful in some cases, mostly when 0 is considered as bad result

Solution 30 - Javascript

Template literals

var a = 10;
var b = 20;
var text = `${a} + ${b} = ${a+b}`;

then the text variable will be like below!

> 10 + 20 = 30

Solution 31 - Javascript

optional chaining (?.) can be used so instead of:

if(error && error.response && error.response.msg){ // do something}

we can:

if(error?.response?.msg){ // do something }

more about optional chaining here

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestioneyelidlessnessView Question on Stackoverflow
Solution 1 - JavascriptChris NoeView Answer on Stackoverflow
Solution 2 - JavascriptChris NoeView Answer on Stackoverflow
Solution 3 - JavascriptChris NoeView Answer on Stackoverflow
Solution 4 - JavascriptAshView Answer on Stackoverflow
Solution 5 - Javascriptsteve_cView Answer on Stackoverflow
Solution 6 - JavascriptChris NoeView Answer on Stackoverflow
Solution 7 - JavascriptChris NoeView Answer on Stackoverflow
Solution 8 - Javascriptpramodc84View Answer on Stackoverflow
Solution 9 - JavascriptJ cView Answer on Stackoverflow
Solution 10 - JavascriptSkilldrickView Answer on Stackoverflow
Solution 11 - JavascriptSerkan YersenView Answer on Stackoverflow
Solution 12 - JavascriptJonny BuchananView Answer on Stackoverflow
Solution 13 - JavascriptlevikView Answer on Stackoverflow
Solution 14 - JavascriptVirtuosiMediaView Answer on Stackoverflow
Solution 15 - JavascriptPablo CabreraView Answer on Stackoverflow
Solution 16 - JavascriptvvoView Answer on Stackoverflow
Solution 17 - JavascriptChris NoeView Answer on Stackoverflow
Solution 18 - JavascriptGerard SimpsonView Answer on Stackoverflow
Solution 19 - JavascripteyelidlessnessView Answer on Stackoverflow
Solution 20 - JavascriptmkoistinenView Answer on Stackoverflow
Solution 21 - JavascriptdicroceView Answer on Stackoverflow
Solution 22 - JavascriptRameshVelView Answer on Stackoverflow
Solution 23 - JavascriptpalswimView Answer on Stackoverflow
Solution 24 - JavascriptcllpseView Answer on Stackoverflow
Solution 25 - JavascriptmanixrockView Answer on Stackoverflow
Solution 26 - Javascriptming_codesView Answer on Stackoverflow
Solution 27 - JavascriptMartijn LaarmanView Answer on Stackoverflow
Solution 28 - Javascriptpramodc84View Answer on Stackoverflow
Solution 29 - JavascriptRaimondsView Answer on Stackoverflow
Solution 30 - JavascriptMohan KumarView Answer on Stackoverflow
Solution 31 - JavascriptAmin DannakView Answer on Stackoverflow