Categories
JavaScript Tips

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

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.

Categories
JavaScript Tips

JavaScript Tips — Calculating Time Difference, The Remainder Operator, and More

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.

Get the Time Difference Between two Date-Times and Format it in HH:mm:ss Format

To get the time difference between 2 date times, we can use the diff method from moment.js

This way, we don’t have to do the calculations ourselves,

For instance, we can write:

const earlierDateTime = "04/09/2020 14:00:00";
const laterDateTime = "04/09/2020 16:20:30";

const difference = moment(laterDateTime, "DD/MM/YYYY HH:mm:ss").diff(moment(earlierDateTime, "DD/MM/YYYY HH:mm:ss"))

const diff = moment.utc(difference).format("HH:mm:ss");

We call diff to get the difference of laterDateTime and earlierDateTime and convert the difference to UTC.

This will output the difference in HH:mm:ss format.

We get ‘02:20:30' as the value of diff .

If the difference between the 2 date-times is longer than today, then we’ve to some extra calculations.

For instance, we can write:

const earlierDateTime = "04/09/2020 14:00:00";
const laterDateTime = "14/09/2020 16:20:30";
const ms = moment(laterDateTime, "DD/MM/YYYY HH:mm:ss").diff(moment(earlierDateTime, "DD/MM/YYYY HH:mm:ss"));

const d = moment.duration(ms);

const diff = `${Math.floor(d.asHours())}${moment.utc(ms).format(":mm:ss")}`;
console.log(diff);

We calculate the minutes and seconds between the 2 dates with the diff method.

Then we call the duration method to get the duration.

Then we can use the asHours method on the duration d object to get the hours elapsed.

We use the utc method to format the minutes and seconds.

string.charAt(x) vs string[x]

The charAt and the bracket notation for getting a character from a string are the same.

They’re both supported by almost all modern browsers.

For instance:

"foo bar"[2]

is the same as:

"foo bar".charAt(2)

Check if a JavaScript Object is a DOM Object

To check if an object is a DOM object, we can write:

typeof Node === "object" ? obj instanceof Node :
  obj && typeof obj === "object" && typeof obj.nodeType === "number" && typeof obj.nodeName === "string"

We check if the Node object exists.

If it is, then we check the obj object with the instanceof operator.

Otherwise, we’ve to check if some properties exist.

We check the nodeType property and nodeName is a string.

To check for an element, we can write:

typeof HTMLElement === "object" ? obj instanceof HTMLElement :
  typeof obj === "object" && obj !== null && obj.nodeType === 1 && typeof obj.nodeName === "string"

We check if the HTMLElement object exists in the browser.

If it does, we just use the instanceof operator.

Otherwise, we check if obj is an object, and also check the nodeType and nodeName properties.

nodeType 1 means that the node is an HTML element.

Get the Length of a String

We can use the length property of a string to get its length.

For instance, we can write:

const str = 'foo';
const length = str.length;

Get the Decimal Portion of a Number

To get the decimal portion of a number, we can use the % operator.

We get the remainder of the number divided by 1.

For instance, we can write:

2.555 % 1

Then we get:

0.5550000000000002

returned.

We can also convert it to a string and call split on it:

(2.555).toString().split(".");

The decimal part would be in index 1 of the returned array.

Run a Function When the Page is Loaded

We can function a function when a page is loaded by setting the function as a value of the window.onload property.

For instance, we can write:

window.onload = () => {
  console.log('page loaded');
}

We set the function as the value of onload so it’ll run when the page loads.

Determine if a Number is Odd

We can determine if a number is odd by using the remainder operator.

For example, we can write:

x % 2 !== 0

If x can’t be evenly divided by 2, then we know it’s odd.

Conclusion

We can format a time span into HH:mm:ss format with moment.js.

We can use the % operator to determine if a number is odd.

Most of the time, we can use the built-in constructors to check if an object is a DOM node or element.

Getting the decimal portion of a number can be done by getting the remainder when divided by 1 or convert it to a string and split it.

Categories
JavaScript Tips

JavaScript Tips — Read Files, UNIX Epochs, Variables, and More

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.

How to get Time in Milliseconds Since the UNIX Epoch

To get the time in milliseconds since the UNIX epoch, which is the time since Jan 1, 1970, 12 AM UTC, we can use Date.now() .

For instance, we can write:

const now = Date.now();

and now is the UNIX timestamp in milliseconds.

We can also write:

const now = new Date().valueOf()

to get the same thing.

Dynamically Create CSS Class in JavaScript and Apply it

To create a dynamic CSS class and apply the class to an element, we can create a style element with JavaScript.

Then we can set the className property of the element to apply the class.

For example, we can write:

const style = document.createElement('style');  
style.type = 'text/css';  
style.innerHTML = '.cssClass { color: green; }';  
document.head.appendChild(style);  
document.getElementById('foo').className = 'cssClass';

We create the style element with type attribute set to 'text/css' .

Then we set the text inside the style element with the innerHTML .

Then we get the head with document.head and append the style element to it.

Finally, we set the className to the one we just created.

Rename Key of a JavaScript Object

To rename a key of a JavaScript object, we can add the new key with the value of the old key.

Then we can delete the old key.

We can use Object.assign to do that.

For instance, we can write:

delete Object.assign(o, { [newKey]: o[oldKey] })[oldKey];

We populate the newKey with the bracket notation.

Then we delete the oldKey with the brackets.

Get Data from fs.readFile

We can get data from the fs.readFile by getting them from the data from the callback.

For instance, we can write:

const fs = require('fs');  
  
fs.readFile('./foo.txt', (err, data) => {  
  if (err) {  
    throw err;  
  }  
  console.log(data);  
});

We can also do it synchronously with readFileSync :

const text = fs.readFileSync('foo.txt','utf8')  
console.log (text)

We pass in the path of the file in both examples.

In the 2nd example, we pass in the encoding of the file.

Detect HTTP or HTTPS then force HTTPS in JavaScript

We can check if a URL starts with https , then we can call location.replace to replace the URL to replace it with the https version of the URL.

For instance, we can write:

if (location.protocol !== 'https:') {  
     location.replace(`https:${location.href.substring(location.protocol.length)}`);  
}

We call location.replace and replace the current URL with the https version.

We call substring to remove the http from the original URL.

Getting JavaScript Object Key List

We can get the object key list with the Object.keys method.

For instance, we can write:

const obj = {  
  foo: 1,  
  bar: 2,   
  baz: 3  
}  
const keys = Object.keys(obj);

Now keys have the keys of obj .

Use the onClick Listener to get the ID of the Clicked Button

We can get the ID of the element that’s clicked by using this .

For instance, we can write:

<button id="foo" onClick="onClick(this.id)">button</button>

Then we can write:

const onClick = (clickedId) =>  {  
  console.log(clickedId);  
}

Also, we can get the event object’s target property by writing:

const onClick = (event) =>  {  
  console.log(event.target.id);  
}

Difference Between Variable Declaration Syntaxes in Javascript

There are multiple ways to declare variables.

One way is to use var , which creates a global variable of the global object if it’s at the top level.

Otherwise, it’s function scoped.

For instance, we can write:

var x = 1;

let creates a variable in the block scope.

It’s only available within the block and nested blocks.

For instance, we can write:

let foo = 1;

Then we create a block-scoped variable.

const is also block-scoped, but it’s constant. So we can only assign a value to it once when we declare it.

For instance, we can write:

const bar = 1;

Them we can’t assign it another value after this line.

To create global variables, we can create a new property on the window object.

For instance, we can write:

window.a = 0;

Then we attach the a property to the window object.

And we can access it as a .

We should declare block-scoped variables whenever we can to avoid any confusion.

Conclusion

There are many ways to declare JavaScript variables.

We should use block-scoped variables whenever we can.

Style elements can be dynamically added.

There are a few ways to read files in Node apps.

Categories
JavaScript Tips

JavaScript Tips — Radio Buttons, Changing Dates, and More

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.

Disable Input Conditionally in Vue.js

We can disable an input conditionally in Bue.js by setting the disabled prop of an element.

To do that, we write:

const app = new Vue({
  el: '#app',
  data: {
    disabled: fals,
  },
});

Then we write:

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <button @click="disabled = !disabled">Toggle Enable</button>
  <input type="text" :disabled="disabled">
  <p>{{ $data }}</p>
</div>

We toggle the disabled state when we click the button.

And we set the value of the disabled prop to the disabled state.

Check Whether a Radio Button is Selected with JavaScript

To check whether a radio button is selected with JavaScript, we can get the checked property of an element.

For instance, if we have the following HTML:

<input type="radio" name="gender" id="male" value="Male" />
<input type="radio" name="gender" id="female" value="Female" />

Then we can write:

if (document.getElementById('male').checked) {
  // ...
}
else if (document.getElementById('female').checked) {
  // ...
}

We just get the radio element and check the checked property.

Print Consecutive Values with setTimeout in for loop

If we want to print consecutive values with setTimeout in a for loop, then we’ve to use let to declare the index variable.

let is block-scoped, so it’s confined to the loop.

This means that there will be a distinct index variable for each iteration.

For instance, we can write:

for (let i = 1; i <= 2; i++) {
  setTimeout(() => { console.log(i) }, 100);
}

window.location.href and window.open()

window.location.href is a property that lets us change the current URL of the browser.

Changing the value will redirect the page.

window.open() is a method that lets us pass a URL to it to open it in a new window.

For instance:

window.location.href = 'https://example.com';

will redirect us to https://example.com.

On the other hand, if we write:

window.open('https://example.com');

then we’ll open a new window with the URL.

window.open can take more parameters with settings for the window.

Alternative to the Removed Lodash _.pluck Method

We can just use the array instance’s map method to get the property from each entry that we want.

For instance, if we want to get the id property of each entry, we can write:

const ids = arr.map(a => a.id)

Then we return a new array with the id value of each entry.

Repeat String with Javascript

To repeat a string, we can use the string instance’s repeat method.

For example, if we want to repeat a string 3 times, we can write:

"foo".repeat(3);

Then we get:

"foofoofoo"

Convert UTC Epoch to Local Date

We can convert a UTC epoch to a local date by creating a Date instance.

Then we call setUTCSeconds with the seconds to set the seconds to the UTC epoch in seconds.

For instance, we can write:

const utcSeconds = 575849093;
const d = new Date(0);
d.setUTCSeconds(utcSeconds);

We pass in 0 to set the Date to the start of the UTC epoch.

Then we set the seconds to set the seconds.

Get Start and End of a Day in Javascript

To get the start and end of a day in JavaScript, we can write setHours on the Date instance.

For instance, we can write:

const start = new Date();
start.setHours(0, 0, 0, 0);

const end = new Date();
end.setHours(23, 59, 59, 999);

We create a new Date instance.

Then we call setHours with all zeroes to set it to the beginning of the date.

Then we set it to the end of the day by setting the time to hour 23, minute 59, seconds 59, and 999 milliseconds.

We can call toUTCString on start and end to get the formatted date string.

“elseif” Syntax in JavaScript

We write elseif as else if .

For example, we write:

if (foo) {

} else if (bar) {

} else {

}

Conclusion

We can disable inputs conditionally with Vue.js with props.

To get the checked value of the radio button, we can use the checked property.

We can convert UTC epoch to seconds.

And we can set a date to the start and end of the date.

else if is the way to write a block for a conditional branch.

Categories
JavaScript Tips

JavaScript Tips — Add Seconds, Format Dates, Traverse Objects, and More

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.

Add x Seconds to a Date

We can add x number of seconds to a Date instance by using the getSeconds method to get the number of seconds in the date object.

For instance, we can write:

const date = new Date('2020-01-01 10:11:55');
date.setSeconds(date.getSeconds() + 10);

We create a Date instance.

Then we call setSeconds to set the seconds.

We put the number of seconds from getSeconds plus the number of seconds we want to add.

In this example, we add 10 seconds.

We can also use getTime and add the number of milliseconds to the object.

For instance, we can write:

let date = new Date('2020-01-01 10:11:55');
date = new Date(date.getTime() + 10000);

getTime gets the number of milliseconds since January 1 1970 midnight UTC.

10000 milliseconds is the same as 10 seconds.

Therefore, we can put it in the Date constructor and get the new date that’s 10 seconds after the first Date instance.

Storing Key-Value Pairs

We can store key-value pairs with a plain object or a Map instance.

For instance, we can write:

const hash = {};
hash['james'] = 123;
hash['joe'] = 456;

Or we can write:

const map = new Map();
map.set('james', 123);
map.set('`joe`', `456`);

'james' and 'joe' are both keys and the numbers are their values in both examples.

We can loop through maps with the for-of loop.

For instance, we can write:

for (const key of map) {
  console.log(key);
}

to loop through the keys.

Also, we can write:

for (const [key, value] of map) {
  console.log(key, value);
}

to loop through both the keys and values.

It also has the keys and values methods to let us loop through the keys and values.

For instance, we can write:

for (const key of map.keys()) {
  console.log(key);
}

to loop through the keys.

And we write:

for (const value of map.values()) {
  console.log(value);
}

to loop through the values.

Disabling and Enabling an HTML Input Button

We can use the disabled property to disable or enable an HTML input button.

For instance, we can write:

document.querySelector("button").disabled = true;

to disable the button.

Also, we can write:

document.querySelector("button").disabled = false;

to enable the button.

Display All Methods of an Object

We can use getOwnPropertyNames to get all methods of an object.

For instance, we can write:

const objMethodNames = Object.getOwnPropertyNames(obj).filter((p) => {
   return typeof obj[p] === 'function';
})

We get the property names with obj .

Then we call filter to return the property names that are the name of functions.

Get a UTC Timestamp

To get the UTC timestamp of a Date instance, we can call the getTime method.

For example, we can write:

const date = new Date().getTime();

or we can write:

const date = Date.now();

Output an ISO 8601 Formatted String in JavaScript

We can use the toISOString method to convert a Date instance to an ISO 8601 formatted string.

For example, we can write:

const date = new Date();
date.toISOString();

Then we get:

"2020-06-03T23:29:15.666Z"

Change the “this” Context in setTimeout Callback

We can set the value of this in the callback using the bind method.

It only works with regular functions.

For instance, we can write:

const obj = {
  destroy(){
    //...
  }
}

`setTimeout(`obj`.destroy.bind(`obj`), 1000);`

We have obj with the destroy method.

We call bind to bind the destroy method to obj .

Then the value of this in obj.destroy should be obj for sure.

Make Google Chrome JavaScript Console Log Persistent

By default, the Google Chrome console log is cleared when we refresh the page or load a new page.

To prevent this from happening, we can click Preserve log in the console to stop it from clearing when we refresh the page or load a new one.

Conclusion

We can make the Chrome console log persistent.

bind returns a new function with the value of this we want.

We can use toISOString to format the date-time into a string.

Also, we can use getOwnPropertyNames to get all the keys and filter to return the keys that are keys of methods.