Categories
JavaScript Tips

Useful JavaScript Tips — Query Strings Rounding, and URLs

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.

Getting Query String Values

JavaScript’s standard library has the URLSearchParams constructor that can be used to extract the query parameters and let us search for them.

For instance, we can write:

const urlParams = new URLSearchParams(window.location.search);
const val  = urlParams.get('key');

window.location.search returns the query string portion of the URL.

The get method gets the value by the key of the query parameter.

Round a Number to at Most 2 Decimal Places

We can use Math.round to let us round to 2 decimal places.

For instance, we can write:

Math.round(num * 100) / 100

We multiplied num by 100, round it, and then divide by 100 to return a number that has at most 2 decimal places.

If there are decimal digits that are less than the hundredth digit, then we add Number.EPSILON to before we multiply by 100.

So we write:

Math.round((num + Number.EPSILON) * 100) / 100

Also, we can use parseFloat and toFixed to format a number into a string of the number with 2 decimal places.

We can write:

parseFloat("575.393").toFixed(2);

Convert a String to Boolean

We can convert the string 'true' and 'false' to their corresponding boolean value by writing:

val === 'true'

Assuming that val can be set to 'true' or 'false' , we can just compare against 'true' to do that.

Storing Objects in Local Storage

To store an object in local storage, we’ve to convert it to a string first.

For instance, we can write:

const obj = { 'foo': 1, 'bar': 2, 'baz': 3 };
localStorage.setItem('data', JSON.stringify(obj));

We called JSON.stringify before calling setItem to store the stringified object with the key data in local storage.

JSON.stringify won’t keep undefined , functions, Infinity, and regex, so we’ve to be careful about that.

Merge 2 or More Objects

We can use the spread operator or Object.assign to merge the properties of 2 or more objects together.

For instance, we can write:

const merged = {...obj1, ...obj2, ...obj3};

or:

const merged = Object.assign({}, obj1, obj2, obj3, etc);

Both pieces of code populate the properties of obj1 , obj2 , and obj3 into an empty object.

Detect a Click Outside an Element

We can call stopPropagation to prevent the click event from the element that we’re checking the click from the outside of.

So we can write:

window.addEventListener('click', () => {
  // do something when clicked outside
});

document.querySelector('#menucontainer').click((event) => {
  event.stopPropagation();
});

The window ‘s click event handler lets us run code when the user clicks outside.

Refresh a Page

There are many ways to refresh a page with JavaScript,

We can do:

  • location.reload();
  • history.go(0)
  • location.href = location.href
  • location.href = location.pathname
  • location.replace(location.pathname)
  • location.reload(false)

location.pathname is the relative URL.

history.go also refreshes by reloading the same page.

Pretty Print JSON

We can pretty-print JSON with the JSON.stringify method.

For example, we can write:

const str = JSON.stringify(obj, null, 2);

The 2 indicates that we indent by 2 spaces.

Passing Command Lines Arguments to a Node.js Program

Node programs have access to the process.argv property to get all the command line arguments of a program.

For instance, we can write:

for (const a of process.argv){
  console.log(a)
}

The first argument is always 'node' . The 2nd is always the path of the file we run.

The rest are the other command-line arguments.

Check for Decimal Numbers

We can check for decimal numbers by using the isNaN function and the isFinite function.

To do the check, we write:

!isNaN(parseFloat(n)) && isFinite(n);

parseFloat parses the string into a floating-point number.

isNaN checks whether the returned value is NaN or not.

isFinite checks whether the number or numeric string represents a finite number.

Modify the URL Without Reloading the Page

The URL can be modified without reloading the page with JavaScript.

The window.history.pushState lets us add a new URL to the browsing history.

We can write:

window.history.pushState('foo', 'title', '/foo.html');

The first argument is the state object.

We can take get the value of the argument with popstate .

'title' is the title, which is ignored in most browsers.

'/foo.html' is the URL to write to the browsing history.

Conclusion

The URLSearchParams constructor lets us parse query strings into a useful object that we can look up.

We can use Math.round to round a number to 2 decimal places.

Also, we can change the URL and add it to the browsing history without reloading the page.

Categories
JavaScript Tips

JavaScript Tips— Textbox Values, Timezones, and Loops

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 Textbox has Changed

We can check if a textbox has changed by listening to the input event.

For instance, we can write:

$('#text-box').on('input', () => {
  // ...
});

We call on to listen to the input event.

Then we run the code in the callback to do what we want.

Detect a Touch Screen Device Using JavaScript

We can use the Modernizr library to detect whether a device is a touch screen device or not.

It provides us with the touch and no-touch classes which are added to the html element.

Therefore, we can use that to do whatever we want depending on whether the device is touch screen or not.

The Correct Way to Modify State Arrays in React

There is a correct way to modify state arrays in React.

If we’re using class components, we use setState by passing in a callback that takes the previous value.

Then we return a new value based on that.

For instance, we can write:

this.setState(prevState => ({
  arr: [...prevState.arr, 'foo']
}))

We added the 'foo' string as the last element of the arr state.

If we’re using hooks, we do the same thing but we pass the callback into the state change function.

For instance, we write:

`setArr(`arr => [...arr, 'foo']`)`

assuming setArr is the state change function returned by useState .

Check if a Number is NaN

To check if a number is NaN , we need to use the isNaN function.

For instance, we can write:

isNaN('foo')

It’ll check by converting the string to a number and then do the check.

So it’ll return true since it’ll be converted to NaN .

Finding the Max Value of a Property in an Array of Objects

We can use the Math.max and the array map methods to find the max value of a property in an array of objects.

For instance, we can write:

Math.max(...array.map(o => o.y))

We get the max value of the y property of the entries by call map to return an array of numbers with the values.

Then we use the spread operator to spread the array entries into the Math.max method as arguments.

How to Toggle a Boolean

We can toggle a boolean by using the ! operator.

We just write:

bool = !bool;

to change bool to the value opposite of the current one.

Create a Date with a Set Timezone Without Using a String Representation

We can create a Date object with a set timezone without using a string by using the setUTCHours method to set the UTC hour of a Date instance.

For instance, we can write:

new Date().setUTCHours(2)

Then we get the timestamp of the date with the hour set to the given UTC hour.

We can also set the minutes, seconds, and milliseconds values.

Also, we can write:

const date = `new Date(Date.UTC(year, month, day, hour, minute, second))`

Date.UTC returns a timestamp with the UTC date set with the given year, month, day, hour, minute, and seconds.

When we pass that into the Date constructor, we get the date with the same value.

Looping Through Key-Value Pairs

To loop through key-value pairs, we can use Object.entries with the for-of loop.

For instance, we can write:

for (const [key, value] of Object.entries(obj)) {
  console.log(key, value);
}

to do that.

obj is an object.

Scroll Automatically to the Bottom of the Page

To scroll automatically to the bottom of the page, we can use the window.scrollTo method.

For example, we can write:

window.scrollTo(0, document.body.scrollHeight);

We scroll to the x and y coordinates given in the argument.

document.body.scrollHeight is the bottom of the page.

Conclusion

window.scrollTo lets us scroll to anywhere on our page.

The right way to modify an array state in React is to pass in a callback and return a new array derived from the old one.

We can watch the input event of a text area to watch the value as we type.

We can use Math.max to find the max value of an array of numbers.

Categories
JavaScript Tips

JavaScript Tips — Sets to Arrays, Console Log, Size of Text, 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.

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.

Categories
JavaScript Tips

JavaScript Tips — Parsing URLs, Reading Files, 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.

Parse a URL into Hostname and Path

To parse a URL string into its hostname and path, we can use the URL constructor.

For instance, we can write:

new URL("http://example.com/foo/bar")

Then that returns an object with the hostname and pathname properties.

hostname is the hostname.

pathname is the pathname.

Format JavaScript Date as yyyy-mm-dd

We can format a date as a string in yyyy-mm-dd format with a few date methods.

For instance, we can write:

const d = new Date(date);
let month = (d.getMonth() + 1).toString();
let day = (d.getDate()).toString();
const year = d.getFullYear();

if (month.length < 2) {
  month = `0${month}`;
}

if (day.length < 2)  {
  day = `0${day}`;
}

const formattedDate = [year, month, day].join('-');

We create a date object from the Date constructor.

Then we call getMonth to get the month.

We’ve to add 1 because the month is zero-based.

We get the day of the month with getDate .

Also, we get the 4 digit year with getFullTear .

If the month or day is a single digit, then we put a zero before it.

Then we join the year, month, and day together with '-' .

A simpler solution would be to use the toISOString method.

For example, we can write:

const formattedDate = new Date().toISOString().slice(0, 10);

We convert the date to a string and extract the year, month, and day parts.

Check if Element is Visible in DOM

We can check if an element is visible in the DOM in a few ways.

One way is to use the offsetParent property to check for visibility.

The property will return null whenever it or its parents are hidden via the display style property.

This will be true if there are no fixed elements on the page.

If there are no fixed elements on the page, then we write:

el.offsetParent === null

where el is the element to check for visibility, to check for it.

We can also call getComputedStyle with an element as its argument to get its computed display style.

So we can write:

cpnst style = window.getComputedStyle(el);
const isInvisibie = style.display === 'none';

We check that the style.display property is 'none' .

Convert a String to a Character Array

We can split a string to a character array with the split method.

For example, we can write:

const output = "foo bar".split('');

Then we get:

["f", "o", "o", " ", "b", "a", "r"]

as the value of output .

Get Array of Object’s Keys

To get an array of an object’s keys, we can use the Object.keys method.

For example, we can write:

const obj = {
  foo: 1,
  bar: 2
};

const keys = Object.keys(obj);

Then we keys is ['foo', 'bar'] .

Create an Empty Object with {} or new Object()

There are no benefits with using new Object() .

And using {} is more compact and readable.

Therefore, we should use the object literal syntax rather than the Object constructor.

Read a Local Text File

We can read a local text file with client-side JavaScript.

To do this, we can use the FileReader constructor to do it.

We can let users select a file and read the selected text file.

For instance, we can add a file input:

<input type='file' accept='text/plain' onchange='openFile(event)'>

Then we can write:

const openFile = (event) => {
  const input = event.target;
  const reader = new FileReader();
  reader.onload = () => {
    const text = reader.result;
    consr node = document.getElementById('output');
    node.innerText = text;
    console.log(reader.result);
  };
  reader.readAsText(input.files[0]);
};

We created the openFile function which takes a event parameter.

We get the input element with event.target .

Then we get the selected file with files[0] .

Next, we create a FileReader instance and call readAsText on it with the file as the argument.

Then the onload callback will run and we get the result with reader.result .

Conclusion

We can use the URL constructor to parse a URL into its parts.

The FileReader lets us read text files.

To format dates without a library, we can use toISOString or methods to get the date parts.

There are several ways to check if an element is visible.

Categories
JavaScript Tips

Useful JavaScript Tips — Object Freezing

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.

Check the Prototype of an Object

We can use the isPrototypeOf method of an object to check if another object is a prototype of an object.

For instance, if we have:

const animal = {
  name: 'james'
}

const dog = Object.create(animal);

Then we can call isPrototypeOf by writing:

`animal`.isPrototypeOf(dog)

That expression would return true since we passed animal into Object.create .

On the other hand, if we have:

const cat = {};

Then:

animal.isPrototypeOf(cat)

returns false .

Check if an Object has a Given Property

We can check if an object has a given property by using the hasOwnProperty method.

It checks if a property is a non-inherited property of an object.

For instance, we can write:

const person = { name: 'james' };
const hasName = person.hasOwnProperty('name');

Then we can check if the name property is in the person object with hasOwnProperty .

The has hasName would be true since name is a property of person .

Get All the Property Values from an Object

We can get all the property values of an object with the Object.values() method.

For instance, we can write:

const person = { name: 'james', age: 7 };
const values = Object.values(person);

Then values would be [“james”, 7] .

Set the Prototype of an Object

The prototype of an object can be set after the object is created.

We can do that with the setPrototypeOf method.

For instance, we can write:

const dog = {
  breed: 'poodle'
};

const animal = {
  name: 'james',
  age: 7
};

Object.setPrototypeOf(dog, animal);

setPrototypeOf is a static method of Object .

dog is the object that we want to set the prototype of.

animal is the prototype that we want to set dog to.

Therefore, we can write:

console.log(dog.name);

Then we have 'james' as the value of dog.name since dog inherits properties from animal .

Sealing the Object

Sealing an object means that we prevent an object from accepting new properties.

Also, we prevent properties from being removed.

We can use the Object.seal method to prevent properties from changing.

For instance, we can write:

const dog = {
  breed: 'poodle'
};

Object.seal(dog);

dog is sealed so we can’t add or remove properties from it.

There’s also the Object.freeze method that does less than seal .

It doesn’t make properties non-writable in addition to what seal does.

For example, we can write:

const dog = {
  breed: 'poodle'
};

Object.freeze(dog);

There’s also the preventExtensions method to disallow adding properties.

We call it the same way as seal and freeze .

Getting Non-inherited String Keys with the Object.keys Method

We can get non-inherited string keys from an object with the Object.keys method.

For instance, we can use it by writing:

const dog = {
  breed: 'poodle'
};
const keys = Object.keys(dog);

Then the value of keys is [“breed”] .

It’s an array so we can do whatever we want with them like other arrays.

Check if an Object is Sealed

The Object.isSealed method lets us check if an object is sealed.

For instance, we can write:

const dog = {
  breed: 'poodle'
};
const isSealed = Object.`isSealed`(dog);

Then we get isSealed is false since we didn’t call Object.seal on dog .

Once an object is sealed, it can’t be unsealed.

Check if an Object if Frozen

We can use the Object.isFrozen method to check if an object is frozen.

For instance, we can write:

const dog = {
  breed: 'poodle'
};
const isFrozen = Object.isFrozen(dog);

Now we can check if an object is frozen.

isFrozen should be false since dog isn’t frozen.

Check if we can add a Property to an Object

The Object.isExtensible method lets us check if we can add a property to an object.

Unless an object is passed into the Object.freeze , Object.seal , or Object.preventExtensions methods, we can add properties to it.

For instance, we can call isExtensible by writing:

const dog = {
  breed: 'poodle'
};
const isExtensible = Object.isExtensible(dog);

Then isExtensible is true since we didn’t seal or freeze dog .

Conclusion

There are many things we can do with objects that we may have missed.

We can prevent objects from changing or adding/removing properties.

Also, we can check if objects can be changed.