Categories
JavaScript Tips

JavaScript Tips — Date Difference, Sleep, 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.

Pause a Node Program for a Period of Time

We can pause a Node program for a period of time with the setTuimeout method.

For instance, we can write:

setTimeout(() => console.log('pause'), 3000);

We can also create a promise with the setTimeout function in it.

For instance, we can write:

const sleep = (ms) => {
  return new Promise((resolve) => {
    setTimeout(resolve, ms);
  });
}

We created a sleep function to return a promise.

resolve is called when the timeout is over.

ms is the timeout duration in milliseconds.

Then we can use it by writing:

const run = async () {
  console.log('foo');
  await sleep(1000);
  console.log('bar');
}

We call sleep to pause the run function between the 2 console logs.

Update Nested State Properties in React

We can updated nested state properties by using the spread operator.

For instance, we can write:

this.setState({ foo: { ...this.state.foo, flag: false } });

Then we set the foo state with the new value of flag while retaining the rest of the this.state.foo object.

setState is used in class components.

If we use hooks, we can write:

setFoo({ ...foo, flag: false });

where setFoo is the state change function returned by useState .

How to Get a Key in a JavaScript Object by its Value

We can get a key in a JavaScript object by its value by inverting the keys and values.

Then we can get the value by the key of the inverted object.

To do that, we can use Underscore’s invert method.

For instance, we can write:

const obj = {
  foo: 3,
  bar: 4
};

(_.invert(obj))[3];

We flipped the obj keys an values and return the new object with invert .

Then we can get the key by the value of the original object.

The same method is available with Lodash.

Passing Arguments Forward to Another JavaScript Function

To pass an arguments forward to another function, we can use the apply method.

For instance, we can write:

const a = (...args) => {
  b.apply(null, args);
}

const b = (...args) => {
  console.log(args);
}

Then we can call a :

a(1, 2, 3);​

We call the a function with the arguments we want to pass in.

Then we use apply to call b with the same arguments.

args is an array of arguments that are passed in.

Likewise, we can use the spread operator to spread the arguments instead of using apply :

const a = (...args) => {
  b(...args);
}

const b = (...args) => {
  console.log(args);
}

Moment.js Date-Time Comparison

We can compare date and time by using the diff method.

For instance, we can write:

moment().diff(dateTime, 'minutes')

moment() and dateTime are both moment objects.

We call diff on moment() to compare that with dateTime and get the difference in minutes by passing in 'minutes' .

moment() gets the current date-time as a moment object.

Alias a Default import in Javascript

To alias a default import in JavaScript, we can just name it whatever we want.

For instance, we can write:

import alias from './module';

to import the module ‘s default import with the name alias .

Or we can write:

import { default as alias } from './module';

to do the same thing.

Convert Array to JSON

To convert an array to JSON, we can call JSON.stringify on the array.

For instance, we can write:

const str = JSON.stringify(arr);

where arr is the array.

Get Distinct Values from an Array of Objects

To get distinct values from an array of objects, we can use the map method and put the items into a set to remove the duplicates.

For instance, we can write:

const distincts = [...`new Set(arr.map((item) => item.id))]`

We call the map method on arr to get all the id property values into an array.

Then we use the Set constructor to create a set from the array of id values to remove the duplicates.

Finally, we convert the set back to an array with the spread operator.

Conclusion

We can pause a program by using promises.

Sets are useful for removing duplicates.

We can use the rest operator to get all the arguments of an object.

Categories
JavaScript Tips

JavaScript Tips — Sorting Keys, Checking Characters, and More

As with many kinds of apps, there are difficult issues to solve when we write apps using JavaScript. In this article, we’ll look at some solutions to common JavaScript problems.

Check if a Function Exists

We can check if a function exists with the typeof operator.

For instance, we can write:

if (typeof obj.onChange !== "undefined") {
  // ...
}

or:

if (typeof obj.onChange !== "function") {
  // ...
}

We check if onChange is a function.

Pass a Variable Number of Arguments to a Function

We can pass a variable number of arguments to a function. To do that, we can use the rest operator:

const log = (...args) => {
  console.log(args);
}

args is the array of the arguments passed in. We can also use it with fixed parameters.

For instance, we can write:

const log = (x, ...args) => {
  console.log(args);
}

x is set to the first argument’s value if it’s called.

Then the rest are included in args because of the rest operator.

How to do String Interpolation in JavaScript

We can use template literals to do string interpolation in JavaScript.

For example, we can write:

const age = 30;
console.log(`I'm ${age} years old`);

Then we get I'm 30 years old logged.

Show or Hide Element in React

We can show or hide elements in React by using boolean expressions.

For instance, we can write:

const Search = () => {
  const [showResults, setShowResults] = React.useState(false);
  const onClick = () => setShowResults(true)
  return (
    <div>
      <input type="submit" value="Search" onClick={onClick} />
      { showResults ? <Results /> : undefined }
    </div>
  )
}

We use the showResults state to show the Results component if it’s true .

Otherwise, we render undefined , which means we show nothing.

Sort JavaScript Object by Key

We can sort the JavaScript object by key by sorting the keys and then inserting them into a new object.

For instance, we can write:

const unordered = {
  b: 'foo',
  c: 'bar',
  a: 'baz'
};

const ordered = {};

Object.keys(unordered).sort().forEach((key) => {
  ordered[key] = unordered[key];
});

We have the unordered object with keys that aren’t in alphabetical order. Then we get the keys as an array with Object.keys and call sort to make them sorted in alphabetical order. Next, we loop through each one with forEach and insert them into ordered . This works because non-numerical keys are sorted by their insertion order.

Get the Last Character of a String

To get the last character of a string, we can use the slice method to do this.

For instance, we can write:

str.slice(-1);

which returns a new string with the last character excluded.

-1 means the last index.

How to Detect Escape Keypress with Plain JavaScript

To detect escape keypress, we can use the key property of the event object to do it.

For instance, we can write:

const keyPress = (e) => {
  if (e.key === "Escape") {
    // ...
  }
}

We get the key property and check that it’s 'Escape' .

Count the Number of Occurrences of a Character in a String

We can use the match method to get all the occurrences in a string that matches a given pattern.

For example, we can write:

("baz foo bar".match(/o/g) || []).length

We get all the o ‘s from the string and get its length.

Also, we can use the split method:

"baz foo bar"`.split("o").length - 1`

We split the string by 'o' and get the length property subtracted by 1.

However, this is slow since we’ve to split the string.

We can also call map :

const str = "baz foo bar";
str
  .split('')
  .map((e, i) => {
    if(e === 'o') return i;
  })
  .filter(Boolean)

We split the string and then call map to get the items that match the character. map maps the item to a truthy value, which is an index and pass call filtet to pass it into the Boolean function to get all the truth entries.

Those are the matches.

Conclusion

There are a few ways to check if a function exists. We can check the number of occurrences of a character in multiple ways. Sorting an object by its key is also possible.

Categories
JavaScript Tips

Useful JavaScript Tips — Time and Numbers

Like any kind of apps, JavaScript apps also have to be written well.

Otherwise, we run into all kinds of issues later on.

In this article, we’ll look at some tips we should follow to write JavaScript code faster and better.

Get the Current Timestamp

There are several ways to get the UNIX timestamp from a Date instance.

The timestamp is a number of milliseconds from January 1, 1970, 12 AM UTC.

We can use the Date.now() method to get the timestamp.

Then we get something like 1589399748029.

We can also use the new Date().getTime() method.

new Date().valueOf() does the same thing.

To express the timestamp in seconds, we just divide it by 1000.

So we can write:

Math.floor(Date.now() / 1000)

The Value of this

this can take on different values depending on where it’s used.

Outside of an object, this is always undefined in strict mode,

Otherwise, it’s the global object.

this will be bound to the object at the top level of the method.

For instance, if we have:

const person = {
  name: 'james',
  greet() {
    console.log(`hi ${this.name}`)
  }
}

Then when we call person.greet() , we have 'hi james' logged.

this doesn’t bind to arrow functions. It’ll just take the value of this outside.

We can also set the value of this explicitly.

To do this, we can use the bind method to do it.

For instance, we can write:

const joe = person.greet.bind({ name: 'joe' });

Then when we call joe , we get 'hi joe' .

bind returns a function.

We can change the value of this and call the function with the new this with call and apply .

For instance, we can write:

person.greet.call({ name: 'joe' });

or:

person.greet.apply({ name: 'joe' });

The difference between the 2 is how they take arguments.

For instance, if we have:

const person = {
  name: 'james',
  greet(greeting) {
    console.log(`${greeting} ${this.name}`)
  }
}

Then we can call person.greet by writing:

person.greet.call({ name: 'joe' }, 'hello');

Then we get 'hello james' because we passed in 'hello' as the first argument.

To call apply , we pass the arguments as an array.

For instance, we write:

person.greet.call({ name: 'joe' }, ['hello']);

Then we get the same result.

In HTML event element handlers, this is bound to the element.

For instance, if we have:

document.querySelector('button').addEventListener('click', function(e) {
  console.log(this)
}

Then this ‘s value is the button.

Convert a String to a Number

There are many ways to convert a string to a number.

Number

We can convert a string to a number with the Number function.

For instance, we can write:

const count = Number('123');

Then count is '123' .

parseInt

To parse a string into an integer, we can use parseInt .

For instance, we can write:

const count = parseInt('123', 10)

The first argument is the string to convert and the 2nd argument is the radix.

Then we convert the string to the decimal.

As long as the number begins with a number, it’ll convert the numerical part.

If we have:

const count = parseInt('123 bottles', 10)

then we get 123.

parseFloat

To parse a string to a float, we can use parseFloat .

For instance, we can write:

parseFloat('1.20')

Then we get 1.2.

Unary +

Also, we can use the + operator to do the same thing as parseFloat .

For example, we can write:

+'1.20'

and get the same thing.

Math.floor

Likewise, we can use Math.floor to round a string to the floor of it.

We can pass in a string straight to the method and it’ll do the conversion for us.

For instance, if we write:

Math.floor('9.81')

and we get 9.

Use * 1

We can convert a string to a number by multiplying it by 1.

For example, we can write:

'9.20' * 1

and we get 9.2.

Format a Number to a Currency Value

JavaScript has a Intl.NumberFormat constructor to convert a number to a currency value.

For instance, we can write:

const formatter = new Intl.NumberFormat('en-US', {
  style: 'currency',
  currency: 'USD',
  minimumFractionDigits: 2
})

const price = formatter.format(888);

Then we get “$888.00” as the value of price .

The style is the formatting style, and we set that to 'currency' to convert it to a currency string.

currency is the currency we want to format the string to.

minimumFractionDigits is the minimum number of decimal digits.

Conclusion

We can do many things with numbers.

We can format them to a currency string.

Also, there are many ways to convert a string to a number.

Categories
JavaScript Tips

Useful JavaScript Tips —Maps, Checkboxes, and Existence

Like any kind of apps, JavaScript apps also have to be written well.

Otherwise, we run into all kinds of issues later on.

In this article, we’ll look at some tips we should follow to write JavaScript code faster and better.

Maps

Maps are useful for storing key-value pairs.

It’s created using the Map constructor.

To create it, we write:

const map = new Map();

Add Items to a Map

We can add items to a Map by using the set method.

For instance, we can write:

map.set('color', 'brown');
map.set('age', 2);

Get an Item from a Map by Key

We can use the get method to get a map item by its key.

For example, we can write:

map.get('color');
map.get('age');

Delete an Item from a Map by Key

Map instance has the delete method to remove an item by its key.

For instance, we can write:

map.delete('color');

Delete All Items from a Map

We can delete all items from a Map with the clear method.

For example, we write:

map.clear()

Check if a Map has an Item with the Given Key

The has method lets us check if an item with the given key is in the Map instance.

For instance, we can write:

const hasColor = map.has('color');

Find the Number of Items in a Map

The size property returns the number of items in a Map .

For example, we write:

const size = map.size;

Create a Map with Values

We can pass in an array with key-value pairs in the constructor.

For instance, we can write:

const map = new Map([['color', 'white'], ['breed', 'poodle'], ['age', 2]])

The first entry is the key and the 2nd is the value in each array entry.

Iterate Over Map Keys

Map instances has the keys method.

It returns an iterator with the map keys so we can loop through them.

For instance, we can write:

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

Iterate Over Map Values

We can loop through the values with the values method.

For instance, we can write:

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

Iterate Over Key-Value Pairs

Map instances have the entries method to loop through the key-value pairs.

For example, we can write:

for (const [key, val] of map.`entries`()) {
  console.log(key, val)
}

We can also write;

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

Convert Maps to an Array

We can spread the map keys and values to an array.

For example, we can write:

const keys = [...m.keys()]

and:

const values = [...m.values()]

WeakMaps

WeakMaps are a special kind of map that has entries that can be garbage collected.

Also, we can’t iterate over the kets or values in a WeakMap.

We also can’t clear all items from a WeakMap.

Its size also can’t be checked.

However, we can get an item with its key with get

We also can add an item to a WeakMap with set .

We can check for the item with the given key with has .

And we can delete an item from a Weakmap with delete .

Check if a Checkbox is Checked

We can find out whether a checkbox is checked with the checked property.

For instance, we can write:

document.getElementById('selected').checked

to see if the checkbox with ID selected is checked.

Check for an Undefined Object Property

There are several ways to check for an undefined object property.

We can directly compare a property to undefined :

obj.prop === undefined

Also, we can use the hasOwnProperty method:

!obj.hasOwnProperty('prop')

It checks for own properties of obj with the name given in the argument.

Also, we can use the typeof operator:

typeof obj.prop === 'undefined'

Check if a DOM Element Exists

We can do that easily with jQuery.

We can select the elements and get the length of the returned list:

$(selector).length

We can also call the exists method:

$(selector).exists()

Also, we cause plain JavaScript’s querySelectorAll method:

document.querySelectorAll(`selector).length`

Conclusion

Maps are useful for storing key-value pairs.

Also, we can check if an element is checked with the checked value.

We can get if elements exist by selecting them and getting the length of the returned list.

Categories
JavaScript Tips

JavaScript Tips — Array Values, Number to String, 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.

Check if a Value Exists at a Certain Array Index

We can check if a value exists at a certain array index.

To do that, we can write:

if (typeof array[index] !== 'undefined') {
  //...
}

or:

if (typeof array[index] !== 'undefined' && array[index] !== null) {
  //...
}

This way, we check if the array entry exists by checking that it’s not undefined or null .

How to Iterate over a JSON structure?

We can loop through an array with the for-of loop.

For instance, we can write:

const cars = [{ name: 'Suzuki' }, { name: 'BMW' }];

for (const car of cars) {
  console.log(car.name);
}

We also can write:

const cars = [{ name: 'Suzuki' }, { name: 'BMW' }];

for (const { name } of cars) {
  console.log(name);
}

We restructured the car object by getting its name property directly.

Pushing Element at the Beginning of an Array

To add an element at the beginning of an array, we can use the unshift method to do this.

For instance, we can write:

array.unshift('foo');

Now we have 'foo' as the first entry of array .

The Best way to Convert a Number to a String

There are a few ways to convert a number to a string.

We can write:

  • String(n)
  • n.toString()
  • “”+n
  • n+””

According to tests like this one http://jsben.ch/#/ghQYR, toString is the fastest in Firefox.

It can be done 1 million times in 0.1 seconds.

However in Chrome num + '' is faster according to http://jsben.ch/#/ghQYR

Split Array into Chunks

We can split an array into chunks by using a for loop:

const chunk = 10;
let tempArray = [];
for (let i = 0; i < array.length; i += chunk) {
  tempArray = array.slice(i, i + chunk);
}

We loop through the array, then we get the chunks by incrementing i with chunk .

Then in the loop body, we call slice to get the chunk of the array.

The slice is from index i to i + chunk — 1 .

Convert Array to Object

We can use Object.assign to convert an object to an array.

For instance, we can write:

Object.assign({}, ['a', 'b', 'c']);

We put the array entries into the empty object.

We can also use the spread operator:

{ ...['a', 'b', 'c'] }

Difference Between npx and npm

npx lets us run a package directly from the NPM repository without installing it.

It’s useful for packages that we don’t use often.

npx always runs the latest version of a package.

npm is used for managing packages, including installation.

We can use npm to install package with npm install .

Or we can use it to run scripts with npm run .

What do Multiple Arrow Functions Mean?

Multiple arrow functions means that it’s nested.

For instance, if we have:

handleChange = field => e => {
  e.preventDefault();
  // ...
}

Then we have a function that takes the field parameter, then it returns a function with the e parameter.

This is also known as a curried function.

We return a function that applies one parameter at a time instead of applying them all at once.

This is handy for sharing functions that have some arguments applied to it.

If we write:

const add = x => y => x + y

then we can apply one argument to it by writing:

const add2 = add(2)

Then we can call that by writing:

add2(3)

and get 5 or:

add2(6)

and get 8 for example.

Filter Object Array Based on Attributes

We can use the filter method to filter an object array based on attributes.

For instance, we can write:

const homesIWant = homes.filter((el) => {
  return el.price <= 2000 &&
    el.sqft >= 500 &&
    el.numBeds >= 2 &&
    el.numBaths >= 2.5;
});

We return an array that has all the homes entries with price less than or equal to 2000, sqft bigger than or equal to 500, numBeds bigger than or equal to 2, and numBaths bigger than 2.5.

Conclusion

We can iterate over arrays with the for-of loop.

We can get chunks of an array by incrementing by the chunk length.

filter lets us filter arrays by whatever condition we want.

npx and npm are different.