Categories
JavaScript Tips

JavaScript Tips — Disabling Divs, Dynamic Script Elements, 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.

How to Disable all div Content

We can use the pointer-events: none style to disable mouse interaction on a div element.

Therefore, we can write the following code to disable interaction on a div with JavaScript:

$("div").addClass("disabled");

Then the disabled class would have the following styles:

.disabled {  
  pointer-events: none;  
  opacity: 0.5;  
}

We disable mouse interaction and also make the div content translucent.

Reject the Promise with the async-await syntax

If we want to reject the promise returned by an async function, we can throw an error or use Promise.reject .

For instance, we can write:

const asyncFn = async () => {  
  try {  
    const val = await foo();  
    //...  
  }  
  catch(error) {  
    throw new Error('error');  
  }  
}

Then the returned promise is rejected with the reason 'error' .

Likewise, we can use Promise.reject by writing:

const asyncFn = async () => {  
  try {  
    const val = await foo();  
    //...  
  }  
  catch(error) {  
    return Promise.reject(new Error('error'));  
  }  
}

In the catch block we return a promise that’s rejected with the Promise.reject method.

We still pass in the Error instance with the reason 'error' .

Calculate Yesterday’s Date in JavaScript

We can calculate yesterday’s date with the getDate method to return the day of the month

Then we subtract 1 from it and pass it into the setDate method.

To do that, we write:

const date = new Date();  
date.setDate(date.getDate() - 1);

Append <script> Element

To append a script element dynamically to the DOM, we can call createElement to create an element.

Then we can call appendChild to append the newly created script element.

For example, we can write:

const script = document.createElement("script");  
script.type = "text/javascript";   
script.text = "console.log('hello');"  
document.body.appendChild(script);

We created a script with inline code.

Then we called appendChild to append the script.

Also, we can write the following to append a linked script:

const script = document.createElement("script");  
script.type = "text/javascript";   
script.src   = "/script.js";  
document.body.appendChild(script);

We append script.js to set the path of the script.

Everything else is the same.

Get the Coordinates of a Mouse Click on a canvas Element

To get the coordinate of a mouse click on a canvas element, we can use the clientX and clientY properties.

For instance, we can write:

const getCursorPosition = (canvas, event) => {  
  const rect = canvas.getBoundingClientRect();  
  const x = event.clientX - rect.left;  
  const y = event.clientY - rect.top;  
  console.log(x, y);  
}

We can use the getBoundingClientRect method to get the left and top offsets of the canvas.

We subtract them from clientX and clientY respectively to get the coordinate of the mouse in the canvas.

Then we can use this function by writing:

const canvas = document.querySelector('canvas')  
canvas.addEventListener('mousedown', (e) => {  
  getCursorPosition(canvas, e)  
})

Check if a JavaScript String is a URL

We can use the URL constructor to check if a JavaScript string is a valid URL.

For instance, we can write:

const isValidUrl = (string) => {  
  try {  
    new URL(string);  
  } catch(e) {  
    return false;    
  }  
  return true;  
}

We try to create a URL instance to see if it’s a URL.

If it is, then no exception would be thrown and we return true .

Otherwise, we return false in the catch block since an exception would be thrown when the URL constructor tries to parse an invalid URL string.

Use encodeURI or encodeURIComponent for Encoding URLs

encodeURI assumes that the input is a complete URI that we’re passing in as the argument.

encodeURIComponent encoded everything with a special meaning.

For instance, we can write:

encodeURIComponent('&');

and returns “%26” .

And we can write:

encodeURI('http://example.com/?foo= bar')

and get “http://example.com/?foo=%20bar" .

Conclusion

We can disable div interactivity with some CSS.

There are 2 ways to return a rejected promises in an async function.

The URL constructor takes the hard work out of parsing URL strings.

Script tags can be dynamically inserted.

We can check a mouse position on a canvas with some properties.

Calculating yesterday’s date can be done with the Date instance methods.

Categories
JavaScript Tips

Useful JavaScript Tips — String, Removing Item, and Timers

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.

Make the First Letter of a String Uppercase

We can make the first character of a string uppercase by getting the first letter and making that uppercase.

Then we append the rest of the string to the first letter.

For instance, we can write the following:

const name = 'joe'
const capitalized = name[0].toUpperCase() + name.slice(1)

Then we get “Joe” as the value of capitalized .

Remove an Item from an Array

We can remove an item from an array with the index.

Remove a Single Item

For instance, we can use slice as follows given the index of the array.

We write:

const items = ['foo', 'bar', 'baz'];
const i = 1;
const filteredItems = items.slice(0, i).concat(items.slice(i + 1, items.length));

We used slice to get parts of an array excluding the index i .

Then we used concat to join the slice with the rest of the array with the item in index i .

Therefore, we start with i + 1 .

Also, we can call filter without the index of the given item or value itself.

For example, we can write:

const items = ['foo', 'bar', 'baz'];
const valueToRemove = 'bar';
const filteredItems = items.filter(item => item !== valueToRemove);

We can also do the same with the index:

const items = ['foo', 'bar', 'baz'];
const i = 1;
const filteredItems = items.filter((_, index) => index !== i);

Remove Multiple Items

We can remove multiple items by their index by writing:

const items = ['foo', 'bar', 'baz', 'qux'];
const indexes = [1, 2];
const filteredItems = items.filter((_, index) => !indexes.includes(index));

Likewise, we can use the includes method on the value itself.

For example, we can write:

const items = ['foo', 'bar', 'baz', 'qux'];
const valuesToRemove = ['foo', 'qux'];
const filteredItems = items.filter(item => !valuesToRemove.includes(item));

slice and filter don’t mutate the original array, so it’s better than mutating the array.

Checking if a String has a Substring

We can check if a string has a substring with the includes method.

For instance, we can write:

'I like dogs'.includes('dogs')

Then that would return true since 'dogs' is in the string.

includes also takes a 2nd argument with the index to start searching.

For instance, we can write:

'I like dogs'.includes('dogs', 11)

Then includes starts searching at 11, so we get false since it’s not in the substring starting with index 11.

We can also use the indexOf method.

It takes the same arguments except that we have compared the index that’s returned.

For instance, we can write:

'I like dogs'.indexOf('dogs') !== -1

1 is returned if indexOf can’t find the given substring. Otherwise, it’ll return the index of the substring.

We can also pass in the index to start searching:

'I like dogs'.indexOf('dogs', 11) !== -1

Timer

JavaScript provides us with the setTimeout function to delay the execution of JavaScript code:

setTimeout(() => {
  // ...
}, 2000)

Then the code runs after 2 seconds.

We can pass arguments into the callback by writing:

const callback = (firstParam, secondParam) => {
  // ...
}

setTimeout(callback, 2000, firstParam, secondParam)

Then firstParam and secondParam are passed into the callback function.

setTimeout returns a timer ID.

Then we can call clearTimeout to remove the timer from memory.

For instance, we can write:

const timer = setTimeout(() => {
  // ...
}, 2000)

clearTimeout(timer)

We called clearTimeout to remove the timer.

We can set the delay to zero. Then the callback is queued and run without delay after the synchronous code is run.

So we can write:

setTimeout(() => {
  //...
}, 0)

The setInterval function is like setTimeout , but the callback is run in an interval.

For instance, we can write:

setInterval(() => {
  // ...
}, 2000)

Then the callback runs every 2 seconds.

Like setTimeout , we can stop the callback from running with clearInterval .

For example, we can write:

const id = setInterval(() => {
  // ...
}, 2000)

clearInterval(id)

We cleared the timer by using clearInterval with the return ID.

Conclusion

We can capitalize the first letter of a string with the toUpperCase method.

There are many ways to remove an item from an array.

Also, we can use timers to run code at an interval or after a delay.

Categories
JavaScript Tips

JavaScript Tips — Semicolons, Download Files, Escaping Strings, 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.

Rules for JavaScript’s Automatic Semicolon Insertion (ASI)

JavaScript inserts semicolons automatically if they’re not included.

It follows some rules for inserting items.

It’s added after the following pieces of code:

  • empty statement
  • var statement
  • do-while
  • continue
  • break
  • return
  • throw

Therefore, we should make sure that we add them or JavaScript do it for us.

The location may be unexpected.

The Best Way to Break from Nested Loops

We can use the break statement to break nested loops.

For instance, we can write:

for (const i of a) {
  for (const j of b) {
    breakCheck = true;
    break;
  }
  if (breakCheck) {
    break
  };
}

We set the breakCheck flag in the inner loop.

Then we use break to break the inner loop.

Then we check the breakCheck flag and end the outer loop.

Print a Selected Element

We can make an element printable by using some CSS.

If we have:

<div id=“printarea”>
  hello world
</div>

Then we can use the following CSS to make the div printable:

@media print {
  body * {
    visibility: hidden;
  }
  #printarea, #printarea * {
    visibility: visible;
  }
  #printarea {
    position: absolute;
    left: 0;
    top: 0;
  }
}

We use the print media query to hide the body when it’s printed and only show the div with the ID printarea .

Random Color Generator

We can generate a random color by creating a hex string with 6 characters to create a color code.

For instance, we can write:

const getRandomColor = () => {
  const letters = '0123456789ABCDEF';
  const color = '#';
  for (let i = 0; i < 6; i++) {
    color += letters[Math.floor(Math.random() * 16)];
  }
  return color;
}

We get a random index with Math.floor(Math.random() * 16) .

And we use that to get a random character from the letters array.

Then we return the color code string.

Download a File with Node.js Without Using Third-Party Libraries

We can download a file by creating a write stream.

Then we can pass in the write stream to the http.get method.

The response data is then piped into the write stream.

For instance, we can write:

`const http = require('http');
const fs = require('fs');

const file = fs.createWriteStream("img.jpg");
const request = http.get("`https://placeimg.com/640/480/any`", (response) => {
  response.pipe(file);
});`

We use the http module’s get method to do the download.

And we call pipe with the write stream to save the file.

Auto-Reload Files in Node.js

To restart our app automatically when our code files change, we can use Nodemon.

To use it, we just run:

npm install nodemon -g

to install the package.

Then we run:

nodemon app.js

to run the program with the app.js , where app.js is the entry point of our app.

Private Properties in JavaScript ES6 Classes

Private class members are coming to JavaScript classes.

They’re denoted by the # character.

For example, we can write:

class Foo {
  #property;

  constructor(){
    this.#property = "test";
  }

  #privateMethod() {
    return 'hello world';
  }

  getPrivateMessage() {
    return this.#privateMethod();
  }
}

Anything that’s prefixed with # is a private member.

It can be used with Babel 7 with the stage 3 preset.

Escaping Strings

We can replace all the strings that we want to escape with a backslash.

For instance, we can write:

const escapeRegex = (string) => {
  return string.replace(/[-/^$*+?.()|[]{}]/g, '$&');
}

We call replace with a regex that matches all the characters that we want to escape.

And we replace them by adding a backslash before those characters.

So if we call it:

const escaped = escapeRegex('//');

Then escaped is “//” .

We can also use the Lodash escapeRegExp method to do the same.

If we write:

const escaped = _.`escapeRegExp`('//');

Conclusion

Automatic semicolon insertion is done by the JavaScript interpreter.

Nodemon lets us watch for code file changes and reload our app automatically.

We can break from nested loops with flags to end the outer loop.

We can create a write stream to pipe our response to.

Categories
JavaScript Tips

JavaScript Tips — Removing Array Items, Month Name

As with many kinds 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.

Get Month Name from a Date

We can use the toLocaleString method to get a month name from a Date instance.

For example, we can write:

const date = new Date(2020, 10, 10);
const month = date.toLocaleString('default', { month: 'long' });
console.log(month);

'long' returns the full month name.

'default' is the locale, which is whatever is set on our computers.

Check if a String is a Valid JSON String in JavaScript

To check is a string is a valid JSON string, we can try parsing it with JSON.parse .

For instance, we can write:

const isJsonString = (str) => {
  try {
    JSON.parse(str);
  } catch (e) {
    return false;
  }
  return true;
}

We put JSON.parse in the try block so that it’ll throw an exception if it isn’t valid.

Convert String to Title Case

We can convert a string to title case with the replace method.

For instance, we can write:

str.replace(/wS*/g, (txt) => {
  return `${txt.charAt(0).toUpperCase()}${txt.substr(1).toLowerCase()}`;
});

We use the replace method with a regex to find the first character of each word in a string.

w is the word boundary. S is any non-whitespace character.

Then pass in a callback to get the text and return the word with the first letter changed to uppercase and the rest converted to lower case.

Link and Execute External JavaScript File Hosted on GitHub

We can use the GitHub CDN to get the file from Github and run it.

However, since Github disabled hotlinking, we’ve to download the file from the following locations and run it locally.

To do that, we can access the script by writing:

http://raw.githubusercontent.com/<username>/<repo>/<branch>/script.js

or:

http://cdn.jsdelivr.net/gh/<username>/<repo>/script.js

to get the latest version.

We can also get a file by the commit hash by writing:

http://cdn.jsdelivr.net/gh/<username>/<repo>@<version or hash>/script.js

We replace script.js with our own script file name.

We download from any of those locations and include it ourselves.

Conditionally Add Attributes to React Components

We can conditionally add attributes to React components by writing:

<Button {...(condition ? { bsStyle: 'success' } : {})} />

We return different objects conditionally according to the condition expression.

Then we can spread the props accordingly.

Remove Object from Array Using JavaScript

There are several ways to remove an object from an array.

We can call arr.shift() to remove the first element of an array.

Also, we can call arr.slice(1) to remove the first element of an array.

arr.splice(0, 1) also removes the first element of an array.

arr.pop() to remove the last element.

arr.slice(0, a.length — 1) also removes the last element.

arr.length = arr.length — 1 lets us remove the last element.

arr.splice(index, 1) removes the element with the given index.

arr.slice(0, x).concat(arr.slice(-x)) remove the element with the index x .

We can also use filter to remove items that doesn’t meet the given condition:

const filtered = arr.filter((el) => { return el.name !== "james"; });

Now all items in arr with el.name equal to 'james' is removed and the rest are returned in a new array.

How do I Replace a Character at a Particular Index

Replace a character at the given index.

We can use the substring method to return a string with the character at the given index replaced.

For instance, we can write:

const s = "Hello world";
const index = 3;
s = `${s.substring(0, index)}x${s.substring(index + 1)}`;

We use substring to divide the string according to the index into 2.

The index in the 2nd argument isn’t included.

Max Size of localStorage Values

Local storage can store up to 10MB of data.

However, this can be customized by the user.

How to Initialize an Array’s Length

We can initialize the array’s length with the Array constructor.

For instance, we can write:

new Array(5);

or:

Array(5);

to create an array with length 5.

Conclusion

We can check if a JSON string is valid by parsing it. To get the name, we can use the toLocaleString method. Converting strings to title case can be done with the replace method. There are many ways to remove an item from a JavaScript array.

Categories
JavaScript Tips

JavaScript Tips — Download Files, Performance Test, 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.

Download File Using Javascript

We can download a file with JavaScript.

To do that, we can use the Fetch API.

We can call it as follows:

fetch('https://www.w3.org/TR/PNG/iso_8859-1.txt')
  .then(resp => resp.blob())
  .then(blob => {
    const url = window.URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.style.display = 'none';
    a.href = url;
    a.download = 'sample.txt';
    document.body.appendChild(a);
    a.click();
    window.URL.revokeObjectURL(url);
  })
  .catch(() => alert('oh no!'));

We call fetch to make a GET request to the file.

Then we call blob to turn it into a binary object.

Next, we call createObjectURL to create a URL from the blob.

Then we create an a element to create an invisible link with the object URL as the URL for the a element.

Then we can call click to download the file.

Finally, we call revokeObjectURL to clean up the data URL.

Create an Object Property from a Variable Value

We can create an object from a variable by passing in the variable in between the brackets.

For instance, we can write:

obj[a] = 'foo';

Then we set the value of a as the property’s identifier.

a can be a string or a symbol.

Also, we can use the same notation in object literals.

For instance, we can write:

const obj = { [a]: b };

We pass the variable a in the brackets of the object literal.

JavaScript Hashmap Equivalent

A map is a JavaScript equivalent of a hashmap.

To use it, we create a Map instance:

const map = new Map();
map.set('foo', 'bar');
map.set('baz', 1);

We created a Map instance and call the set method to add or update entries.

Then we can use the size property to get the map’s size.

Extract a Number from a String

To extract a number from a string, we can use the match let to find all substrings that match a given pattern.

For instance, we can write:

const txt = "123 foo 456";
const nums = txt.match(/(d+)/g);

This will match all contiguous digits.

g indicates that we search in the whole string for this pattern.

d is a digit.

Then nums is [“123”, “456”] .

Check if an Array is Empty or Exists

We can check if an array is empty or exist by using the Array.isArray method and the length property.

For instance, we can write:

if (Array.isArray(array) && array.length) {
  // ...
}

We check if array is an array with Array.isArray .

Then we use the length property to get the length of the array.

We don’t have to check the length explicitly because 0 is falsy and all other numbers are truthy.

So array.length will check if the length is nonzero.

Deep Merge Objects Instead of Doing a Shallow Merge

We can deep merge objects using Lodash’s merge method.

For instance, we can write:

_.merge(obj1, obj2, obj3);

We can merge as many objects as we want with it.

The returned object won’t have properties referencing the existing objects.

Create a style Tag with Javascript

We can create a style tag with JavaScriot by using createElement to create a style element.

For instance, we can write:

const css = 'h1 { background: red; }';
const head = document.head;
const style = document.createElement('style');
style.appendChild(document.createTextNode(css));
head.appendChild(style);

We create some CSS styles in a string.

Then we get the head element with document.head .

Next, we created a style element.

And then we put the CSS in the style element.

And finally, we append the style element into the head element.

Test Performance of JavaScript Code

To test the performance of JavaScript code, we can use the console.time and console.timeEnd methods.

For instance, we can write:

console.time('test');
for(let i = 0; i < 1000000; i++){
  //...
};
console.timeEnd('test')

We call console.time with a string identifier to start the performance test timer.

Then we call console.timeEnd with the same identifier to end the timer.

Conclusion

The JavaScript console object has methods to let us measure the timing of the code.

We can download files with the Fetch API.

Map is JavaScript’s hashmap.

Lodash merge lets us deep merge objects.

We can add dynamic properties to objects.