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.

Categories
JavaScript Tips

Useful JavaScript Tips — Sets, Hidden Elements, and Loops

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.

Sets

Sets are useful data structures for storing items without duplicates.

It’s an iterable object and it’s created with the Set constructor.

Initialize a Set

We can create a set with the Set constructor.

We write:

const set = new Set()

Add Items to a Set

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

So, we can write:

set.add('foo');
set.add('bar');

Check if an item is in a Set

Sets have a has method to check if an item is in the set.

For example, we can write:

set.has('foo');
set.has('bar');

Delete Item from a Set

We can call delete to remove a Set item.

For instance, we can write:

set.delete('foo');

Determine the Number of Items in a Set

The size property lets us get the number of items in a Set.

We can write:

set.size

Remove All Items from a Set

The clear method removes all items from a Set.

For example, we can write:

set.clear()

Iterate Items in a Set

We can use the for-of loop to loop through items in a Set.

For instance, we can write:

for (const k of set.keys()) {
  console.log(k)
}

to loop through the keys of the set.

Likewise, we can use the values() method to do the same thing:

for (const v of set.values()) {
  console.log(v)
}

There’s also the entries method to return an iterator:

const i = set.entries();

Then we can use the next method to get the next entry in the sequence:

i.next()

The returned object has the value or done properties.

done is false when there’s a next item in the sequence and true otherwise.

value has the value from the set.

Initialize Sets with Values

We can create sets with values using the Set constructor:

const set = new Set([1, 2, 3]);

Convert to an Array

We can convert to a Set to an array with the spread operator:

const arr = [...s.keys()]

or:

const arr = [...s.values()]

WeakSet

A WeakSet is a special kind of Set .

The items never get garbage collected in a Set.

Items in a WeakSet can be garbage collected.

Also, we can’t iterate over the items in a WeakSet.

We can’t clear all items from a WeakSet.

We also can’t check its size.

However, it has the add method to add items.

has method is available for checking if an item exists.

delete is used to delete an item.

Check if an Element is Hidden

We can check if an element is hidden using jQuery.

For instance, we can write:

$(element).is(":visible");

This checks for display: none .

Also, we can write:

$(element).is(":hidden");

and check for visibility: hidden .

We can get all the elements that are hidden with:

$(element).is(":hidden");

And we can get the ones with the visible selector with:

$('element:visible')

Deep Cloning an Object

We can deep clone an object with the JSON.stringify and JSON.parse method.

For instance, we can write:

const cloned = `JSON.parse(JSON.stringify(object));`

We can use it to clone the object with the function values inside the object.

Infinity will be converted to null and undefined values will be removed.

Also, regex literals are also removed.

Therefore, we can use this if we don’t have those values that’ll be converted or lost.

We can use the Lodash cloneDeep method to clone objects easily.

It clones everything in an object.

Object.assign and the spread syntax also copies the values of all enumerable own properties from one object to another.

We can write:

const cloned = Object.assign({}, obj);

or:

const cloned = {...obj };

For Each Loop

The best bet for loop through all items of an array easily for the for-of loop,

The Array instance also has the forEach method.

The old fashioned for loop can also do it.

We can write:

for (const a of arr){
  console.log(a);
}

or:

arr.forEach(a => {
  console.log(a);
})

or:

for (let i = 0; i < arr.length; i++){
  console.log(arr[i]);
}

Conclusion

Sets are a useful data structure for storing data without duplicates.

Also, we can check for hidden elements with jQuery.

There are many ways to iterate through an array.