Skip to content

Top 5 WOW JavaScript Syntax Tricks

Posted on:August 27, 2023 at 12:02 PM

The more you interact with a programming language, the more tricks you discover,

I’ve been working with JavaScript for over 6 years, sometimes I like to spice up the codebase.

In this article I will share that spice, tricks or tips, whatever we may call them.

On top of being concise, and foster productivity I personally think they look cool.

The production code base I work on is littered with some of them, they have been battle tested!

Table of contents

Open Table of contents

5 Cheating querySelect

In web devolpment, it is not uncommon to end up with a lot of DOM elements, and need to access them with JavaScript:

<div class="media_webcam">
  <label id="status">Getting Webcam!</label>
  <video id="vid_preview" width="400" height="400" controls></video>
  <button id="startCam">record</button>
</div>

The common way is to assign id’s or classes, and do a query select for all them:

const snap = document.querySelector(".media_webcam");
const label = document.querySelector("#status");
const vid = document.querySelector("#vid_preview");
const btn = document.querySelector("#startCam");

Imagine you have 10 or more ‘different(not groupable)’ elements.

A simple way is to use the parent, to get all the children:

const camcoder = document.querySelector(".media_webcam");
/**
 * @type {[HTMLLabelElement, HTMLVideoElement, HTMLButtonElement]}
 */
let [statusLabel, vid, camBtn] = camcoder.children;

we queried for one element, and got all the children for free.

cambtn.onclick = () => {
  // execute some code
};

I put this at 5, as I rarely use it, I am more on the backend than front currently, but it works, I used this example in this article

4 utils

Working on larger projects, reusable util functions, that perfom simple tasks are valuable,

This example is more of a stylistic choice than WOW, most people are farmiliar with arrow functions.

This example is fun to write, almost like a challenge, can I write one liner utils:

// utils.js

export const isNumber = val => Number(val);
export const isArray = val => Array.isArray(val);
export const isError = val => val instanceof Error;
export const isResponse = val => val instanceof Response;

usage example:

async function pokemonFetch() {
  const pokemons = await fetch("https://pokeapi.co/api/v2/pokemon/");

  if (isResponse(pokemons)) {
    // we got a response
  } else {
  }
}

an internal dataframe I wrote, is littered with these, they are fun to look at,

why not enjoy while working.

3 Coersing to a boolean

JavaScript run’s on top of C/C++ engines or runtimes, it suprising how many C/C++ features seap into JS, you just have to know the other side,

One of my favorite is changing values to booleans,

Of course this idea assumes you farmiliar with JavaScript and thruthiness of values.

!!console.log; // true
!!null; // false
!!global; // true in node, error in the browser
!!window; // true in browser, error in node

an actual usage for these is checking for web API support:

// checking if webcam is supported, w/o trying to open it with getUserMedia()
const hasGetUserMedia = () => !!navigator.mediaDevices?.getUserMedia;

if (hasGetUserMedia()) {
}

2 IF RETURN

I use this more than I can count, to cut functions short,

stopping the function from executing based on a condition:

function runCode() {
  // run some code

  // check for some condition
  if (!someCondition) return; // if the condition is not met do not run the code below

  // some more code
}

With this we can cut our function to a multi part executing function, I cannot think of an example on command

I use this a lot, it has become natural, and part of my coding style.

1 you don’t exist? fine!

Number one is elegant, and useful if you interact with React frequently,

list rendering etc

(msgs.data ?? []).map();

let’s assume msgs.data is a response from a server, and we are expecting an array with messages,

The code above will check if msgs.data is undefined or not,

if it is undefined will return the empty array instead, so we are not mapping over undefined.

another example:

[...(msg ?? []), msg];

This makes checking super easy to write,

conclusion

This is my personal top 5, thank you for reading.

I hope you enjoyed this run down,

if wish to stay update on future articles, you can follow me on twitter.