Categories
JavaScript Tips

JavaScript Tips — Wait for All Promises, Heights, 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.

Skip Over an Element in .map()

We can skip over an element in map by using filter to filter out the entries we don’t want first.

For instance, we can write:

const sources = images.filter((img) => {
  return img.src.split('.').pop() !== "json"
})
.map(img => img.src);

Now we only map the items that doesn’t end with 'json' .

Interpolate Variables in Strings in JavaScript

We can use template strings to interpolate variables in strings.

For example, we can write:

const a = 5;
const b = 1;
console.log(`sum is ${a + b}.`);

We interpolated the result of a + b into our string in the last line.

The Optimum Way to Compare Strings in JavaScript?

To compare 2 strings in JavaScript, we can use the localeCompare method.

For instance, we can write:

strA.localeCompare(strB)

This lets us compare strings in a locale-sensitive manner.

Wait Until All Promises Complete Even if Some Rejected

To wait for promises to complete, we can use the Promise.allSettled method.

It’ll complete even though some may be rejected.

For instance, we can write:

Promise.allSettled([promise1, promise2])
.then(([result1, result2]) => {
  // ...
});

We pass in an array of promises.

Then we call then and we get all the results in an array.

Each result object has the status and reason or value properties.

status is the promise’s status. If it’s fulfilled, status will be 'fulfilled' . Otherwise, it’ll be 'rejected' .

value is the resolved value.

reason is the error for rejection.

For loop for HTMLCollection elements

To loop through a HTMLCollection object, we can use the for-of loop to do it.

For instance, we can write:

const els = document.getElementsByClassName("foo");
for (const item of els) {
  console.log(item.id);
}

We get all the items with class name foo .

Then we use the for-of loop to loop through them.

To convert it to an array, we can use the Array.from or the spread operator:

const arr = Array.from(document.getElementsByClassName("foo"));

or:

const arr = [...document.getElementsByClassName("foo")];

Now we can use array methods on it.

Get the Number of Days Between Two Date Strings

We can get the number of days between 2 days by parsing the dates and then get their difference.

Assuming that our dates are in MM/DD/YYYY format, we can write:

const parseDate = (str) => {
  const [month, day, year] = str.split('/');
  return new Date(year, month-1, day);
}

const dateDiff = (first, second) => {
  return Math.round((second - first)/(1000 * 60 * 60 * 24));
}

We split the str date string.

Then we pass the split items into the Date constructor as arguments.

year has the year, month has the month, but we’ve to subtract it by 1 since JavaScript constructor assumes that 0 is January, 1 is February, etc.

day is the day of the month.

In dateDiff , we get the difference by subtraction the second by the first .

They’re both Date instances.

Then we divide by the number of milliseconds in a day.

Then we can write:

const diff = dateDiff(parseDate('2/1/2000'), parseDate('3/2/2000'));

to use it.

Use a Variable for a Key in a JavaScript Object Literal

We can use a variable for a key in JavaScript object literals.

For instance, we can write:

const prop = "foo",
const obj = { [prop]: 10 };

We just pass in prop into the brackets, then the key would be foo .

Get the Rendered Height of an Element

We can use the clientHeight , offsetHeight , and scrollHeight to get the rendered height of an element.

For example, we can write:

const height = document.querySelector('div').clientHeight;

or:

const height = document.querySelector('div').offsetHeight;

or:

const height = document.querySelector('div').scrollHeight;

clientHeight includes the height and vertical padding.

offsetHeight includes the height, vertical padding, and vertical borders.

scrollHeight includes the height of the contained document, vertical padding, and vertical borders.

Conclusion

We can use filter with map to map selected entries of arrays.

There are a few ways to get the height of elements.

We can get the number of days between 2 dates by create date objects then subtracting them and dividing them by the number of milliseconds in a day.

Promise.allSettled lets us wait for all promises to finish regardless of their status.

Categories
JavaScript Tips

JavaScript Tips — Throwing Errors, Hostnames, 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.

Extract the Hostname Portion of a URL

We can extract the hostname portion of the URL with the hostname property of window.location.

For instance, if we go to http://example.com/, then window.location.hostname returns “example.com”.

Get the First N Number of Elements from an Array

To get the first n number of elements from an array, we can use the slice method.

For instance, we can write:

arr.slice(0, n)

to get the first n elements of an array.

It doesn’t include the item with index n.

We can also set the length property of the array.

So arr.length = n will truncate arr into length n.

Find a Value in an Array of Objects in Javascript

To find a value in an array of objects with the given value, we can use the find method.

For instance, if we have the given array:

const arr = [
  { name: "james", value:"foo", other: "that" },
  { name: "mary", value:"bar", other: "that" }
];

Then we can write:

const obj = arr.find(o => o.name === 'james');

to find the entry with the name property set to ‘james’and assign it toobj` .

Conditionally add a Property to an Object

We can add a property to an object conditionally with the ternary operator.

For instance, we can write:

const obj = {
  b: addB ? 5 : undefined,
  c: addC ? 5 : undefined,
}

where addB and addC are boolean expressions to determine if b and c should have a value respectively.

Round to 1 Decimal Place in Javascript

To round a number to one decimal place, we can use the toFixed method to do it.

For instance, we can write:

number.toFixed(1)

to round it to 1 decimal place.

Why does Node.js’ fs.readFile() Return a Buffer Instead of a String?

If no encoding is specified, then fs.readFile returns a buffer.

To make it return a string, we pass in the encoding.

For instance, we can write:

fs.readFile("foo.txt", "utf8", (err, data) => {...});

We read the content of foo.txt and specifies the encoding is 'utf8' to make sure it’s read as text.

Is Node.js Array.forEach Asynchronous?

Node.js’s array forEach method is the same as the regular forEach method.

Therefore, it’s a synchronous function.

If we want to iterate asynchronously, we can use the for-of loop with promises or async.each from the async library:

async.each(files, saveFile, (err) => {
  //...
});

We pass in the array to iterate as the first argument.

The function to run on each entry as the 2nd argument.

The last argument is the callback to call when iteration is done.

er us the error object that’s defined when an error is encountered.

Generate Formatted Easy-to-Read JSON Straight from an Object

JSON.stringify can be used to format JSON that’s stringified.

For instance, we can write:

JSON.stringify(obj, null, 2);

to indent the stringified JSON with 2 spaces.

We can also pass in an indentation character:

JSON.stringify(obj, null, 't');

Then we indent with tabs.

Difference Between ‘throw new Error’ and ‘throw obj’

There are differences between throwing errors and throwing any other kind of object.

Error objects have a name, message, and the stack trace.

Throwing any other kinds of objects will expose the message to the user.

For instance, we can write:

try {
  throw "error";
} catch (e) {
  console.log(e);
}

Then the console log would log 'error' .

There won’t be a name and message properties.

On the other hand, if we have:

try {
  throw new Error("error")
} catch (e) {
  console.log(e.name, e.message);
}

Then e.name would be 'Error' and e.message would be 'error' .

Conclusion

We can extract the hostname portion of the URL with the window.location.hostname property.

We can use slice to get the first n entries from an array.

To find an object with the given property value from an array of objects, we can use find .

There’s a difference between throwing Error instances and any other kinds of objects or values.

Categories
JavaScript Tips

JavaScript Tips — Getting Keypresses, Callbacks to Promises 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.

Converting Existing Callbacks to Promises

There are a few ways to convert existing callbacks to promises.

One way is to use the Promise constructor.

For instance, we can write:

return new Promise((resolve, reject) => {  
  window.onload = resolve;  
});

We can put our callback code in the callback and then call resolve on it when it’s done running the code.

We can also use a library to do it.

jQuery has the Deferred property to let us do that:

$.Deferred((dfrd) => {  
   getData(id, dfrd.resolve, dfrd.reject);  
}).promise();

We call Deferred with a callback to returns a deferred object.

Then we call promise to return a promise.

We call resolve and reject in our async code like we do with the Promise constructor.

For Node style callbacks, we can also use the Promise constructor as we do before:

return new Promise((resolve, reject) => {  
  getStuff(param, (err, data) => {  
    if (err !== null) reject(err);  
    else resolve(data);  
  });  
});

We call reject when we encounter an error and resolve is we get data.

We can also use a library like Bluebird to convert Node-style callbacks to promises:

Promise.promisifyAll(asyncCode);

Promise is the Bluebird Promise object and it has the promisifyAll method to convert Node callbacks to promises.

Capture HTML Canvas as Image

We can capture HTML canvas as an image with the toDataURL method.

For instance, we can write:

const canvas = document.getElementById("mycanvas");  
const img = canvas.toDataURL("image/png");

We can use the img string directly as the value of the src attribute of the img tag.

Convert a Comma-Separated String to an Array

To convert a comma-separated string into an array, we can use the split method.

For instance, we can write:

const array = string.split(',');

If string is 'foo,baz'baz' , then we get ['foo', 'bar', 'baz'] as the value of array .

Static Variables in JavaScript

We can create a static variable in JavaScriopt by attaching them as properties of constructors.

For instance, we can write;

function Foo(){}  
Foo.bar = 'baz';

Then bar is a static property of the Foo constructor.

For classes, we can write:

class Foo {  
  static foo = 'bar'  
}

We use the static keyword to define the static foo property.

In either case, we can access it with Foo.bar .

Check that a Number is a Float or Integer

We can check if a floating point number is an integer with the remainder operator.

We write:

n % 1 === 0;

to do that, where n is a number.

If it can be evenly divisible by 1, then we know it’s an integer.

We can also use the Number.isSafeInteger method to check.

And there’s also a Number.isInteger method.

They both take a number that we want to check:

`Number.isInteger(1);  
Number.`isSafeInteger`(1);`

Obfuscate JavaScript

To obfuscate JavaScript,m we can use the Uglify JS package to do it.

We can install it by running:

npm install -g uglify-js

Uglified code can be reversed.

Also, private strings can still be visible after they’re uglified,.

window.onload vs document.onload

There is a difference between window.onload and document.onload .

window.onload is run when the entire page loads, which includes images, CSS, scripts, etc,.

document.onload is called when the DOM is ready, which can be prior to images and other external resources are loaded.

Get Which Key was Pressed with jQuery Event Keypress

We can get the key that’s pressed with the keyCode or which properties.

To check if the enter key is pressed, we check for code 13:

const code = e.keyCode || e.which;  
if (code === 13) {   
  //...  
}

Self-References in Object Literals

We can use a getter to return data that are derived from other properties in the object.

For instance, we can write:

const foo = {  
  a: 5,  
  b: 6,  
  get sum() {  
    return this.a + this.b;  
  }  
}

We have the sum getter which is derived from adding a and b together.

Since getters are methods, we can use this inside it.

Conclusion

There many ways to convert callbacks to promises.

We can use getters to create properties that are derived from other properties.

JavaScript constructors can have static variables.

We can get the key that’s pressed.

Categories
JavaScript Tips

JavaScript Tips — Express Request Size, Debounce, 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.

Error: Request Entity Too Large in Express Apps

We get the request entity too large error in our Express apps if we make a request that exceeds the allowable size limit.

To adjust the limit, we can write:

app.use(express.json({ limit: '50mb' }));
app.use(express.urlencoded({ limit: '50mb' }));

We have the limit property that lets us set the max size for a request.

json sets the max size of a JSON request.

urlencoded sets the same for URL encoded requests.

React Parse Error: Adjacent JSX Elements Must be Wrapped in an Enclosing Tag

We can’t have multiple elements at the top level in a React component.

To make sure that’s not the case, we can wrap them around a fragment or a root element.

For instance, we can write:

return (
  <div>
    <Comp1 />
    <Comp2 />
  </div>
)

to wrap Comp1 and Comp2 around a div.

We can use fragments as follows:

return (
  <>
    <Comp1 />
    <Comp2 />
  </>
)

or:

`return (
  <`React.Fragment`>
    <Comp1 />
    <Comp2 />
  </`React.Fragment`>
)`

They’re both the same.

Fragments are wrapper components that don’t render an element.

Check if a Selector Matches Something in jQuery

We can check the length property of the jQuery object to see if anything has the given selector.

For instance, we can write:

if ($(selector).length ) {
  //...
}

We check if there are any elements with the given selector exist.

If there’s nothing, the length is 0. Otherwise, then length is bigger than 0.

Run JavaScript Function when the User Finishes Typing Instead of on Key Up

We can delay the key up handler by using the debounce method from Underscore or Lodash.

For instance, we can write:

$('#input-box').keyup(_.debounce(callback, 500));

We call the debounce function with our callback and the delay in milliseconds.

Looping Through Array and Removing Items, Without Breaking the for Loop

To loop through an array and remove items, we can use the while loop to loop through an item in reverse.

For example, we can write:

let i = arr.length;
while (i--) {
  // ...
  if (...) {
    arr.splice(i, 1);
  }
}

We use the while loop with the index going down from the length to 0.

0 is falsy, so it’ll break when it’s 0.

In the body, we call splice to remove the item with the given index.

Looping backward ensures that reindexing doesn’t affect the next item of the iteration.

Reindexing only affects the items from the current point to the end of the array.

Another way to do the same thing in a shorter way is to use the filter method:

arr = arr.filter((el) => {
  return el.seconds > 0;
});

Then we return an array with the seconds property bigger than 0.

We then assign that as the new value of arr .

Listening for Variable Changes in JavaScript

We can use a proxy object to listen for variable changes.

For instance, we can write:

const targetObj = {};
const targetProxy = new Proxy(targetObj, {
  set(target, key, value) {
    console.log(key, value);
    target[key] = value;
    return true;
  }
});

We create a new Proxy instance that has the set method to listen to the key and value as it’s assigned to targetObj .

Then when we assign properties to the proxy:

targetProxy.foo = "bar";

the set method will be called.

trim() Method in JavaScript not working in IE

The string instance’s trim method isn’t available in IE.

Therefore, we’ve to add it ourselves.

For instance, we can write:

if (typeof String.prototype.trim !== 'function') {
  String.prototype.trim = function() {
    return this.replace(/^s+|s+$/g, '');
  }
}

We check if the trim instance is a function or not, then we set it to our function if it’s not.

Conclusion

We can add the trim method to IE with a small polyfill.

The max of a request in Express can be changed.

We can use React fragments as wrapper elements that render nothing.

If we loop through an array backwards, then reindexing won’t affect the loop since it’s only applied to items from the given index to the end.

Categories
JavaScript Tips

Useful JavaScript Tips — Sleep and Math

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.

Pause Execution of a Function

We can pause execution of a function by creating our own sleep function.

For instance, we can write:

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

We return a promise with the setTimeour function. The callback is the resolve function.

ms is the amount of pause execution in ms .

Then we can use it by writing:

const foo = async () => {
  await sleep(2000);
  // do more stuff
}

We called sleep with 2000 so the function will pause for 2 seconds before running the code below the sleep call.

It can be used with a loop:

const loop = async () => {
  for (const item of arr) {
    await sleep(2000);
    console.log(item);
  }
}

for-of loops can be used with promises.

So sleep will pause the loop body for 2 seconds.

Generate Random and Unique Strings

We can use the randomstring package to generate random strings.

For instance,e we can wrote:

const randomstring = require('randomstring');
`randomstring.generate(20);`

to generate a string of length 20.

To generate multiple unique strings, we can put all the items in a set.

For instance, we can write:

`const randomstring = require('randomstring');
`const strings = new Set()

while (strings.size < 50) {
  strings.add(randomstring.generate(20));
}

Then we generate unique strings until the set has 50 strings.

Then we can retrieve the strings with the values method.

For instance, we can write:

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

JavaScript Math Object

JavaScript Math object has many properties and methods to make doing math easier.

Math.abs()

The Math.abs method returns the absolute value of a number.

We can write:

Math.abs(-10)

and get 10.

Math.acos()

Returns the arccosine of the argument.

For instance, we can write:

Math.acos(0.3)

and we get 1.2661036727794992.

Math.asin()

Returns the arcsine of the argument.

For instance, we can write:

Math.asin(0.5)

and we get 0.5235987755982989.

Math.atan()

Returns the rectangle of the argument.

For example, we can write:

Math.atan(20)

and we get 1.5208379310729538.

Math.atan2()

Returns the arctangent of the quotient of its arguments.

For instance, we can write:

Math.atan2(3, 2)

and get 0.982793723247329.

Math.ceil()

Rounds a number up to the nearest integer.

For instance, we can write:

Math.ceil(1.99999)

and get 2.

Math.cos()

Returns the cosine of the angle expressed in radians.

For example, we can write:

Math.cos(0)

and get 1.

Math.exp()

Returns the value of e multiplied per exponent that’s passed as the argument.

For example, we can write:

Math.exp(2)

and get 7.38905609893065.

Math.floor()

Rounds the number down to the nearest integer.

For instance, we can write:

Math.floor(1.99999)

and get 1.

Math.log()

Gets the natural logarithm of a number.

For instance, we can write:

Math.log(Math.E)

and get 1.

Math.max()

Gets the maximum number in the set of numbers passed as arguments.

For instance, we can write:

Math.max(1, 2, 3)

and get 3.

Math.min()

Gets the minimum number in the set of numbers passed as arguments.

For example, we can write:

Math.max(1, 2, 3)

and get 1.

Math.pow()

Raised the first argument to the second argument.

For instance, we can write:

Math.pow(2, 3)

and get 8.

Math.random()

Returns a pseudorandom number between 0 and 1.

For instance, we can write:

Math.random()

and get 0.08500663407619236.

Math.round()

Returns the nearest integer.

For instance, we can write:

Math.round(1.3)

and get 1.

Math.sin()

Gets the sine of the angle expressed in radians.

For example, we can write:

Math.sin(0)

and get 0.

Math.sqrt()

Gets the square root of the argument.

For instance, we can write:

Math.sqrt(9)

and get 3.

Math.tan()

Gets the angle of an angle in radians.

For instance, we can write:

Math.tan(Math.PI * 2)

and we get -2.4492935982947064e-16.

Arithmetic Operators

JavaScript has the usual arithmetic operators.

They’re addition, subtraction, multiplication, division, remainder, and exponentiation.

Then we can write:

const three = 1 + 2;

for addition.

But we’ve to make sure that both operands are numbers. Otherwise, it’s used as concatenation.

Subtraction is written as:

const three = 5 - 2;

Division can be written as:

const result = 20 / 10;

If we divide by zero, we get Infinity or -Infinity .

Multiplication can be done by writing:

1 * 2

We can exponentiate by writing:

2 ** 3

and get 8.

We can get the remainder of division by writing:

const result = 20 % 6

and get 2.

Conclusion

There are many operations and math methods we can use.

Also, we can pause execution of functions by using setTimeout .