Categories
JavaScript Tips

JavaScript Tips — Semicolons, Download Files, Escaping Strings, and More

Spread the love

Like any kind of apps, there are difficult issues to solve when we write JavaScript apps.

In this article, we’ll look at some solutions to common JavaScript problems.

Rules for JavaScript’s Automatic Semicolon Insertion (ASI)

JavaScript inserts semicolons automatically if they’re not included.

It follows some rules for inserting items.

It’s added after the following pieces of code:

  • empty statement
  • var statement
  • do-while
  • continue
  • break
  • return
  • throw

Therefore, we should make sure that we add them or JavaScript do it for us.

The location may be unexpected.

The Best Way to Break from Nested Loops

We can use the break statement to break nested loops.

For instance, we can write:

for (const i of a) {
  for (const j of b) {
    breakCheck = true;
    break;
  }
  if (breakCheck) {
    break
  };
}

We set the breakCheck flag in the inner loop.

Then we use break to break the inner loop.

Then we check the breakCheck flag and end the outer loop.

Print a Selected Element

We can make an element printable by using some CSS.

If we have:

<div id=“printarea”>
  hello world
</div>

Then we can use the following CSS to make the div printable:

@media print {
  body * {
    visibility: hidden;
  }
  #printarea, #printarea * {
    visibility: visible;
  }
  #printarea {
    position: absolute;
    left: 0;
    top: 0;
  }
}

We use the print media query to hide the body when it’s printed and only show the div with the ID printarea .

Random Color Generator

We can generate a random color by creating a hex string with 6 characters to create a color code.

For instance, we can write:

const getRandomColor = () => {
  const letters = '0123456789ABCDEF';
  const color = '#';
  for (let i = 0; i < 6; i++) {
    color += letters[Math.floor(Math.random() * 16)];
  }
  return color;
}

We get a random index with Math.floor(Math.random() * 16) .

And we use that to get a random character from the letters array.

Then we return the color code string.

Download a File with Node.js Without Using Third-Party Libraries

We can download a file by creating a write stream.

Then we can pass in the write stream to the http.get method.

The response data is then piped into the write stream.

For instance, we can write:

`const http = require('http');
const fs = require('fs');

const file = fs.createWriteStream("img.jpg");
const request = http.get("`https://placeimg.com/640/480/any`", (response) => {
  response.pipe(file);
});`

We use the http module’s get method to do the download.

And we call pipe with the write stream to save the file.

Auto-Reload Files in Node.js

To restart our app automatically when our code files change, we can use Nodemon.

To use it, we just run:

npm install nodemon -g

to install the package.

Then we run:

nodemon app.js

to run the program with the app.js , where app.js is the entry point of our app.

Private Properties in JavaScript ES6 Classes

Private class members are coming to JavaScript classes.

They’re denoted by the # character.

For example, we can write:

class Foo {
  #property;

  constructor(){
    this.#property = "test";
  }

  #privateMethod() {
    return 'hello world';
  }

  getPrivateMessage() {
    return this.#privateMethod();
  }
}

Anything that’s prefixed with # is a private member.

It can be used with Babel 7 with the stage 3 preset.

Escaping Strings

We can replace all the strings that we want to escape with a backslash.

For instance, we can write:

const escapeRegex = (string) => {
  return string.replace(/[-/^$*+?.()|[]{}]/g, '$&');
}

We call replace with a regex that matches all the characters that we want to escape.

And we replace them by adding a backslash before those characters.

So if we call it:

const escaped = escapeRegex('//');

Then escaped is “//” .

We can also use the Lodash escapeRegExp method to do the same.

If we write:

const escaped = _.`escapeRegExp`('//');

Conclusion

Automatic semicolon insertion is done by the JavaScript interpreter.

Nodemon lets us watch for code file changes and reload our app automatically.

We can break from nested loops with flags to end the outer loop.

We can create a write stream to pipe our response to.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *