Categories
JavaScript Tips

JavaScript Tips — Singletons, Resizing IFrames, Formatting Seconds, and More

Spread the love

As with any kind of app, there are difficult issues to solve when we write apps for JavaScript. In this article, we’ll look at some solutions to common JavaScript problems.

Check if a JavaScript Function is Defined

We can check if a JavaScript function is defined with the typeof operator.

For instance, we can write:

typeof callback === "function"

We check if callback is a function of this.

Implement Singleton in JavaScript

To implement a singleton in JavaScript, we can create an object literal:

const obj = {
  foo() {
    // ...
  },
  bar() {
    // ...
  },
  baz: 1
};

Since it’s not created from a constructor, there will always be one instance of it.

If we want private members, we can put it inside an IIFE:

const obj = (() => {
  let privateVar = '';

  const privateMethod = () => {
    // ...
  }

  return {
    foo() {
      console.log(privateVar)
      // ...
    },
    bar() {
    }
  };
})();

We return an object inside a function and call it immediately. The private variables are put outside the object’s code. Public members are in the returned object, and they can access private members inside it. We can also export an object in a module to make a singleton object available to other modules.

For instance, we can write:

module.js

const privateArr = []

function privateFn () {
  // ...
}

export default {
  foo() {
    // ...
  },
  bar() {
    // ...
  }
}

We export an object with the members we want to make public.

We can import it by writing:

import obj from './module.js'

We don’t need braces to import default exports.

Adjust the Width and Height of iframe to Fit with Content in it

To resize the iframe to fit with its content’s width and height, we can get the iframe’s width and height with scrollWidth and scrollHeight to get the dimensions of its contents.

Then we can write:

window.addEventListener('DOMContentLoaded', (e) => {
  const iFrame = document.getElementById('iFrame');
  `iFrame.width  = iFrame.contentWindow.document.body.scrollWidth;
  iFrame.height = iFrame.contentWindow.document.body.scrollHeight;`
} );

We get the width and height of the iframe with:

iFrame.contentWindow.document.body.scrollWidth

and:

iFrame.contentWindow.document.body.scrollHeight

respectively to set those to the width and height properties of the iframe.

variable === undefined vs. typeof variable === “undefined”

We can compare to undefined with the === operator or we can use the typeof operator to check for undefined. They do the same thing. However, typeof works with undeclared variables and comparing directly with === will give us an error.

Convert the Number of Seconds to a Time String with Format hh:mm:ss

To convert a number of seconds to a time string, we can do some calculations with the number of seconds.

For instance, we can write:

const toHHMMSS = (str) => {
  `const secNum = parseInt(`str``, 10);
  let hours = Math.floor(secNum / 3600);
  let minutes = Math.floor((secNum - (hours * 3600)) / 60);
  let seconds = secNum - (hours * 3600) - (minutes * 60);

  if (hours < 10) { hours = `0${hours}`; }
  if (minutes < 10) { minutes = `0${minutes}`; }
  if (seconds < 10) { seconds = `0${seconds}`; }
  return [hours, minutes, seconds].join(':');
}``

We create the toHHMMSS function that takes the seconds string. Inside it, we call parseInt to parse the string to a decimal number. Then we get the hours by dividing it by 3600 seconds. Then we divide subtract the number of hours in seconds from secNum and divide by 60 to get the minutes.

Next, we subtract both quantities converted to seconds from secNum to get the seconds. Then we add the leading 0 if any of them are less than 10. Finally, we join them together with join .

Clone a JavaScript Object Except for One Key

We can clone a JavaScript object except for one key with the destructuring syntax.

For instance, if we have:

const obj = { foo: 1, bar: 2, baz: 3 };

and we want to omit foo from the cloned object, we can write:

let { foo, ...clone } = obj;

Then clone will have the cloned object without the foo property.

Conclusion

Destructuring assignment is handy for cloning an object without some keys. We can format a second string to hours, minutes, and seconds with some calculations. A singleton object can be created with object literals.

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 *