Cool JavaScript things I wish I knew much earlier

Anh-Thi Dinh
draft
⚠️
This is a quick & dirty draft, for me only!

Learn JS the right way

Shortcut Notations

1// Instead of
2var car = new Object();
3var.color = 'red';
4
5// We use
6var car = { color: 'red' };
1// Instead of
2var arr = new Array(1, 2, 3)
3
4// We use
5var arr = [1, 2, 3]
1// The ternary notation
2// Instead of 
3var direction;
4if (x < 1) direction = 1;
5else direction = -1;
6
7// We use
8var direction = x < 1 ? 1 : -1;

Anonymous functions

1// Instead of
2var myApp = function(){
3  var name = 'Thi';
4  function getInfo(){
5    // [...]
6  }
7}();
8
9// We use
10(function(){
11  var name = 'Thi';
12  function getInfo(){
13    // [...]
14  }
15})()

Module pattern or singleton

1var myApp = function(){
2  var name = 'Thi';
3  return getInfo(){
4    // [...]
5  }
6}();
7
8// Then
9myApp.getInfo();