Categories
JavaScript Tips

JavaScript Tips — Prepend Array Values, Checking Existence, and More

Spread the love

As with any kind of app, there are difficult issues to solve when we write apps for JavaScript. In this article, we’ll look at some solutions to common JavaScript problems.

Most Efficient Way to Prepend a Value to an Array

We can prepend a value to an array by using the unshift method.

For instance, we can write:

const a = ['foo', 'bar', 'baz'];
a.unshift('qux');

Then a is now [“qux”, “foo”, “bar”, “baz”] .

Also, we can use the spread operator do to the same thing.

For instance, we can write:

const a = ['foo', 'bar', 'baz'];
const b = ['qux', ...a];

Then b is [“qux”, “foo”, “bar”, “baz”] .

How do I Check Whether an Array Contains a String

We can check if an array contains a string with the includes or indexOf methods.

For example, we can write:

arr.indexOf('foo') > -1

or:

arr.includes('foo')

to check if arr has the string 'foo' .

indexOf returns -1 if the element isn’t in the array and the index otherwise.

includes returns true if the element is in the array and false otherwise.

If we have an array of objects, then we can use find , some , or filter .

For instance, if we have:

const arr = [{ name: 'foo' }, { name : 'bar' }, { name: 'baz' }];

Then we can write:

arr.find(a => a.name === 'bar')

to find the first element in arr that has the name property equal to 'bar' .

It’ll return the element if it’s there and undefined otherwise.

Also, we can call some to do the same check:

arr.some(a => a.name === 'bar')

some returns true if the condition is met and false otherwise.

We can also use filter :

arr.filter(a => a.name === 'bar')

It returns an array with the entries that meet the condition if those elements exist and an empty array otherwise.

Display “Are you sure you want to navigate away from this page?” Message When Changes Committed

To show a message before the user navigates away from a page, we can listen to the beforeunload event.

For instance, we can write:

window.onbeforeunload = () => {
  return `true;
}`

Then we should see a confirmation box asking the user if they want to navigate away from the page.

We return true since any custom messages are ignored and the browser’s own message is displayed.

For instance in Chrome, it would display ‘Changes you made may not be saved’.

Find the Width of a div using Vanilla JavaScript

To find the width of a div using plain JavaScript, we can use the offsetWidth property to do that.

For instance, we can write:

document.getElementById("div").offsetWidth

The width includes the borders.

If we don’t want to include the width of the border, we can write:

document.getElementById("div").clientWidth;

And we can get the assigned width with:

getComputedStyle(document.getElementById("div")).width;

Display a Confirmation Dialog when Clicking on an <a> Link

To display a confirmation box with we click on a link, we can get the a element, then we can attach a click listener to it.

For instance, given the following HTML code:

<a class="confirmation">Link</a>

Then we can write:

const confirmation = document.querySelector('.confirmation');
const onClick = (e) => {
  if (!confirm('Are you sure?')){
    e.preventDefault();
  }
};

confirmation.addEventListener('click', onClick, false);

We called addEventListener to attach the onClick listener to our anchor element.

In the listener function, we display a confirm dialog box with confirm .

Then the user clicks cancel, then we call preventDefault() to stop whatever the default action is.

Check if Type is Boolean

We can check if a variable is a boolean with the typeof operator.

For instance, we can write:

typeof variable === "boolean"

Now we check if variable is a boolean with that.

Disabled Clicks on a Tag

To disable clicks on the tag with JavaScript, we can set the href with JavaScript code disable clicks.

For instance, we can write:

<a href="javascript:() => { return false; }">disabled link</a>

or:

<a href="/" onclick="return false;">disabled link</a>

or:

<a href="javascript:void(0)">disabled link</a>

void always returns undefined .

All 3 pieces of code do the same thing.

Conclusion

There are a few ways to disable the link. We can get an element width with various properties. Adding items in arrays can be done with the spread operator and unshift . There are many ways to check for the existence of elements in an array.

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 *