Top userful JavaScript shorthands - kowalski7cc

Top userful JavaScript shorthands

The if-else shorthand

if (age < 18) {
  console.log("You cannot drive in some states");
} else {
  console.log("You can drive in some states");
}

shorthand:

console.log(
  age < 18
    ? "Non You cannot drive in some states"
    : "You can drive in some states"
);

react:

<div>
  {age < 18 ? (
    <Button disabled>You cannot drive</Button>
  ) : (
    <Button>Book your exam</Button>
  )}
</div>

Spread Operator Shorthand

let numbers = [2, 3];
let fullNumbers = [1, ...numbers, 4, 5];

react:

function GreetingFunction() {
  return <Greeting firstName='Kowalski' lastName='Dragon' />;
}

becomes

function GreetingFunction() {
  const props = { firstName: "Kowalski", lastName: "Dragon" };
  return <Greeting {...props} />;
}

Destructuring

let people = ["Max", "Anna", "Tom"];
let [firstBoy, , secondBoy] = people;
firstBoy; // Max
secondBoy; // Tom

Or Short-circuit Evaluation

if (variable1 !== null || variable1 !== undefined || variable1 !== "") {
  let variable2 = variable1;
} else {
  let variable2 = "new";
}

shorthand:

const variable2 = variable1 || "new";

Object Property Shorthand

const x = 1920,
  y = 1080;
const obj = { x: x, y: y };

shorthand:

const obj = { x, y };

Arrow Functions Shorthand

function sayHello(name) {
  console.log("Hello", name);
}

setTimeout(function () {
  console.log("Loaded");
}, 2000);

list.forEach(function (item) {
  console.log(item);
});

shorthand:

sayHello = (name) => console.log("Hello", name);

setTimeout(() => console.log("Loaded"), 2000);

list.forEach((item) => console.log(item));

Implicit Return Shorthand

function calcCircumference(diameter) {
  return Math.PI * diameter;
}

shorthand:

calcCircumference = diameter => (
  Math.PI * diameter;
)

Default Parameter Values

function volume(l, w, h) {
  if (w === undefined) w = 3;
  if (h === undefined) h = 4;
  return l * w * h;
}

shorthand:

volume = (l, w = 3, h = 4) => l * w * h;
volume(2); //output: 24

And shorthand with implicit return and arrow function

function isNotEmpty(arr) {
  if (Array.isArray(arr) && arr.length > 0) {
    return true;
  } else {
    return false;
  }
}

shorthand:

const isNotEmpty = (arr) => Array.isArray(arr) && arr.length > 0;

react:

<div>{articles > 0 && <ul>...</ul>}</div>

Template Literals

const welcome = "You have logged in as " + first + " " + last + ".";
const db = "http://" + host + ":" + port + "/" + database;
const welcome = `You have logged in as ${first} ${last}`;
const db = `http://${host}:${port}/${database}`;

Sources