Javascript

Updated: 2020-12-31

JavaScript Engines

Browser

  • Chrome: V8
  • Firefox: SpiderMonkey
  • Safari: Nitro

Beyond Browser

  • Node.js: uses the Google V8 JavaScript engine to execute code

Browser Object Model (BOM)

window object is used to interact with the browser. The following object can be used directly or under window, e.g. window.navigator or navigator

  • document: HTML DOM
  • navigator: to get browser information
  • history
  • screen
  • location: url, host, path, protocol (NOT the user location)

JavaScript Ecosystem

  • React: developed and used by Facebook
  • Angular: developed by Google
  • Vue

Typecheck

  • TypeScript : can be compiled to JavaScript
    • better tooling: advanced autocompletion, navigation, and refactoring
    • developed by Microsoft
    • SUPERSET OF JAVASCRIPT, javascript code is also valid typescript code
  • Flow: also developed by Facebook, so works fine with React

Other notable libs

  • Babel : the compiler
  • D3 / HighCharts : for data visualization
  • Express.js: the node.js web framework
  • WebPack: for apps
  • Rollup: for libs
  • Bootstrap: the CSS framework from Twitter.
  • Polymer: WebComponent, by Google, not yet matured
  • Lerna : build multiple packages from the same repo.
  • ESLint: lint...

Deprecated

  • Moment.js was popular but officially deprecated in 2020.

Add Padding

function addPadding(num, width) {
  var str = num.toString();

  while (str.length < width) {
    str = "0" + str;
  }
  return str;
}

Set default value inside function

function foo(params) {
  var settings = params || {};
}

in vs. hasOwnProperty()

  • in: check prototype chain, all inherited properties will be included.
  • hasOwnProperty(): only check its own properties.

es6 backtick

Template literals can be used multi line and may use "interpolation" to insert the content of variables:

var a = 123,
  str = `---
   a is: ${a}
----`;
console.log(str);

Will output:

---
   a is: 123
---

Javascript does not have an integer type. JavaScript is only able to handle 52bit integers.

Modern js cheatsheet: https://github.com/mbeaudru/modern-js-cheatsheet

Download Canvas as images

Suppose you have a <canvas/> like this:

<canvas id="canvas" width="5" height="5"></canvas>

This will add a link to download the canvas as an image:

<a
  download="image.png" // downloaded file name
  href="#" // this will be modified by `e.target.href`
  onClick={(e) => {
    const dataURL = document.getElementById("canvas").toDataURL("image/png");
    e.target.href = dataURL;
  }}
>
  Download
</a>

The function is .toDataURL()

canvas.toDataURL(type, encoderOptions);
  • type: default value is image/png
  • encoderOptions: image quality, a number between 0 and 1, default value is 0.92.