Skip to content

Instantly share code, notes, and snippets.

@cisoun
Last active March 30, 2022 18:09
Show Gist options
  • Save cisoun/9e74cb870c6d2775776c97dc24bab094 to your computer and use it in GitHub Desktop.
Save cisoun/9e74cb870c6d2775776c97dc24bab094 to your computer and use it in GitHub Desktop.
JavaScript tricks

JavaScript Tricks

Object declaration

// Method 1
function obj() {
  return { a: 1 };
}

// Method 2
function Obj() {
  this.a = 1;
}

let x = obj();
let y = new Obj();

console.log(x instanceof obj); // false
console.log(y instanceof Obj); // true

Q: Which one to use?

A: Use Method 2 if you need to know its type. Useful when throwing an object (as exception) and identify its type in a try/catch context.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment