JS notes - ternary, const function

Recently I’m attacking the world of JavaScript - a treasure for the front-end devs but a pain for the data scientists. Here are some notes from my experience working with JavaScript…

Ternary conditional operator

I explained here how to do ternary operator in Python but things get more complicated in JavaScript. In the latest ES6 coding standards, JavaScript is much more simplified than its previous versions. Here is an example of ternary conditional operator:

var price = 25;
var isExpensive = price > 20 ? true : false;
console.log(isExpensive) // >>> true

It replaces:

var price = 25;
var isExpensive;
if (price > 20) {
  isExpensive = true; 
} else {
  isExpensive = false;
}
console.log(isExpensive) // >>> true

For multiple ternary operator, the coding format looks like:

var price = 25;
var origin = 'sweden';
var car = 
  price > 50 
    ? 'porsche'
    : price < 10
      ? 'seat'
      : origin === 'sweden'
        ? 'volvo'
        : 'bmw'
console.log(car) // >>> 'volvo'

Const function

This is a new feature in ES5 and sexy af:

const helloWorld = () => 'Hello World!';

The const function ensures simplicity and immutability. This line of code replaces:

function helloWorld() {
  return 'Hello World!';
}

There are also good reasons to keep using the old way to define functions. Temporal dead zone(TDZ) could be an issue, readability as well.

References