Best javascript syntax sugar

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'); 

default:

 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 the ability to process them as literals and execute them in place (like closing) is fine:

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

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

+79
javascript language-features syntactic-sugar
07 Oct '08 at 23:35
source share
30 answers

Getting current datetime in milliseconds:

 Date.now() 

For example, by the time the code section runs:

 var start = Date.now(); // some code alert((Date.now() - start) + " ms elapsed"); 
+57
Oct 22 '08 at 0:53
source share

Object Membership Test:

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

 ("a" in props) // true
 ("b" in props) // true
 ("c" in props) // false
+32
08 Oct '08 at 0:57
source share

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

 var xml = <elem> </elem>;

You can also replace variables:

 var elem = "html";
 var text = "Some text";
 var xml = <{elem}> {text} </ {elem}>;
+26
07 Oct '08 at 23:41
source share

Using anonymous functions and closing to create a private variable (hiding information) and related get / set methods:

 var getter, setter; (function() { var _privateVar=123; getter = function() { return _privateVar; }; setter = function(v) { _privateVar = v; }; })() 
+25
08 Oct 2018-08-08T00:
source share

The ability to extend native JavaScript types through prototype inheritance.

 String.prototype.isNullOrEmpty = function(input) { return input === null || input.length === 0; } 
+22
Oct 08 '08 at 0:11
source share

Multi-line strings:

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

Since you cannot backslide from subsequent lines without adding a space to the line, people usually prefer concatenation using the plus operator. But this provides a good document here .

+21
08 Oct '08 at 0:13
source share

Use === to compare values and :

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

 if (i == s) // true

 if (i === s) // false
+20
07 Oct '08 at 23:45
source share

Resize Array

Property

length is not read only . You can use it to increase or decrease the size of the 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 undefined value. A sparse array. 
+20
Aug 28 '09 at 7:07
source share

Repeating a line, for example, “-”, a certain number of times, using the join method in an empty array:

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

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

+16
Nov 21 '08 at 13:41
source share

Like the default operator, || is a protective operator, && .

 answer = obj && obj.property 

Unlike

 if (obj) { answer = obj.property; } else { answer = null; } 
+14
Aug 20 '10 at 8:10
source share
 var tags = { name: "Jack", location: "USA" }; "Name: {name}<br>From {location}".replace(/\{(.*?)\}/gim, function(all, match){ return tags[match]; }); 

callback to replace string is just useful.

+13
Mar 31 '09 at 13:37
source share

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" 
+11
Oct 08 '08 at 9:30
source share

This is not exclusive javascript, but saves as three lines of code:

 check ? value1 : value2 
+5
Oct 07 '08 at 23:46
source share

A little more on the example of levik:

 var foo = (condition) ? value1 : value2; 
+4
Oct 08 '08 at 0:07
source share

Array # forEach on Javascript 1.6

 myArray.forEach(function(element) { alert(element); }); 
+4
Oct 08 '08 at 11:24
source share

Following obj || Syntax {default: true}:

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

+4
Aug 03 '09 at 9:10
source share

When analyzing situations with a fixed set of components:

 var str = "John Doe"; 

You can assign results directly to variables using synatx "assign restructuring":

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

This is a bit readable than:

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

As an alternative:

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

Please note that this is Javascript 1.7 . So the Mozilla 2.0+ browser and Chrome 6+ are currently.

+4
12 Oct '10 at 20:16
source share

I forgot:

 (function() { ... }).someMethod(); // Functions as objects 
+2
09 Oct '08 at 6:33
source share

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

Example: you need to know if an object has a valueOf method:

var hasValueOf = !! ({}). valueOf

Bonus syntactic sugar: double-not '!!' in order to convert almost anything to boolean is very concise.

+2
Sep 06 2018-10-06
source share

The arrow function is called immediately:

 var test = "hello, world!"; (() => test)(); //returns "hello, world!"; 
+2
Jun 06 '16 at 5:46
source share

I like being able to eval () json string and returning a fully populated data structure. I hate writing everything at least twice (once for IE, again for Mozilla).

+1
Oct 08 '08 at 3:02
source share

Casting commonly used keywords (or any methods) to simple variables like ths

  var $$ = document.getElementById; $$('samText'); 
+1
Aug 03 '09 at 9:31
source share

A JavaScript class that provides a semi- "Free Interface". This compensates for the impossibility of directly extracting the date from the Date class:

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

This is not a completely free interface, because the following will give us only a numeric value, which is actually not a Date object:

 var today = new Date().setHours(0, 0, 0, 0); 
+1
Aug 19 '10 at 18:30
source share

Default Reserve:

 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) 
+1
Aug 19 '10 at 21:02
source share

I like how easy 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 will be pretty heavy code. The defaults are also fine. For example, a code error message:

 var errorDesc = {301: "Moved Permanently", 404: "Resource not found", 503: "Server down" }[errorNo] || "An unknown error has occurred"; 
+1
Mar 10 2018-11-11T00
source share

Here I just discovered: null check before calling the function:

 a = b && b.length; 

This is the shorter equivalent:

 a = b ? b.length : null; 

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

 a = b && bc && bclength; 
+1
Apr 11 '11 at 23:21
source share

int for string casting

 var i = 12; var s = i+""; 
0
Mar 31 '09 at 13:49
source share
 element.innerHTML = ""; // Replaces body of HTML element with an empty string. 

Shortcut to delete all child nodes of an element.

0
01 Sep '09 at 7:55
source share

Convert string to integer default value by 0, if this is not possible,

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

May be useful in some cases, mainly when 0 is considered a bad result.

0
Jul 06 '17 at 13:08
source share

Template Literals

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

then the variable text will look like below!

10 + 20 = 30

0
Sep 20 '17 at 5:57
source share



All Articles