Categories
JavaScript Tips

JavaScript Tips — Sorting Keys, Checking Characters, and More

Spread the love

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.

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 *