Categories
JavaScript Tips

JavaScript Tips — Sets to Arrays, Console Log, Size of Text, and More

Spread the love

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.

Convert a Set to an Array

There are a few ways to convert a set to an array.

One way is to use the Array.from method.

For instance, we can write:

const array = Array.from(set);

We can also use the spread operator to do the same thing:

const array = [...set];

Call a Method from a Child Component from a Parent

We can call a method from a child component in the parent by assigning a ref to the child component.

Then we can access the child with the current property.

For instance, we can write:

const { forwardRef, useRef, useImperativeHandle } = React;

const Child = forwardRef((props, ref) => {
  useImperativeHandle(ref, () => ({
    getAlert() {
      console.log("alert from child");
    }
  }));
  return <h1>hello</h1>;
});

const Parent = () => {
  const childRef = useRef();
  return (
    <div>
      <Child ref={childRef} />
      <button onClick={() => childRef.current.getAlert()}>Click</button>
    </div>
  );
};

We use the forwardRef function to pass the ref to the child component.

useImperativeHandle lets us expose a selected method of the child to the parent.

Now we assign the ref to the Child and then we can call the getAlert method from the Parent via the current property.

How to Fix Error: listen EADDRINUSE Error

EADDRINUSE means that the port number is already in use.

This means that we have to listen to a different port in whatever app we’re using.

Or we can end the program that’s using the port we want to use.

For instance, if we change the port of an HTTP server, we can write:

const http = require('http');

const server = http.createServer((req, res) => {
  res.end('test');
});

server.on('listening', () => {
  console.log('ok, server is running');
});

server.listen(80);

The last line is listening to port 80.

We can change that to something else.

To terminate a program, we can write:

killall -9 node

Print Debug Messages in the Google Chrome JavaScript Console

We can run JavaScript in the browser address bar with the javascript: prefix.

For instance, we can type in:

javascript: console.log('foo');

to log 'foo' in the console.

Other console methods include console.error to log things as errors.

console.info logs informational messages.

console.warn logs warnings.

We can format strings with some tags.

For instance, we can write:

console.log("this is %o, event is %o, host is %s", this, e, location.host);

%o means we interpolate an object, and %s means string.

Firefox has the console.trace(); method to log stack traces.

Better Way of Writing v = (v === 0 ? 1 : 0)

We can rewrite v = (v === 0 ? 1 : 0) to:

v = (v ? 0 : 1);

since 0 is falsy.

If v is 0 or another falsy value, then we assign 1 to it. Otherwise, we assign 0.

Return Value from an Asynchronous Callback Function

There’s no way to return a value from an async callback function.

This is because we get the value in an indeterminate amount of time.

Instead, we just use the value inside the function.

So if we have:

asyncCode({ address }, (results, status) => {
  fn(results[0].geometry.location);
});

Then we just use results and status within the function.

Calculate Text Width

We can calculate the text width by putting our text in a div.

Then we can use the clientWidth and clientHeight properties to get the width and height respectively.

For instance, we can write:

const fontSize = 12;
const text= document.getElementById("text");
text.style.fontSize = fontSize;
const height = `${text.clientHeight}px`;
const width = `${text.clientWidth}px`;

With just get the text, change the font size to what we want, and get those properties.

Check Whether Variable is a Number or a String

To check whether a variable is a number or a string, we can use the typeof operator.

For instance, we can write:

typeof "hello"

and get 'string'

And if we write:

typeof 123

we get 'number'.

Conclusion

There are a few ways to convert a set to an array.

We can call a method from a React child component from a parent component by using forward refs.

There are many ways to log items in JavaScript.

There’s no way to return a value from an async callback function.

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 *