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.

Categories
JavaScript Tips

JavaScript Tips — Base64 to Blob, JSON, Dates, and Input

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.

Difference between JSON.stringify and JSON.parse

JSON.strignify and JSON.parse do different things.

JSON.stringify converts an object into a JSON string.

JSON.parse parse a JSON string into an object.

For instance, we can use JSON.stringify by writing;

const obj = { foo: 1, bar: 2 };
const str = JSON.stringify(obj);

str is the stringified version of obj .

We can use JSON.parse by writing:

const obj = JSON.parse(str);

If str is a valid JSON string, then it’ll be parsed into an object.

Remove Accents or Diacritics in a String

If our string have accents or diacritics in a string, we can remove it by using the normalize method.

For instance, we can write:

const str = "garçon"
const newStr = str.normalize("NFD").replace(/[u0300-u036f]/g, "")

Then newStr is “garcon” .

NFD means the Unicode normal form.

It decomposes the combined graphemes into the combination of simpler ones.

Therefore the ç is decomposed into the letter and the diacritic.

Then we used replace to remove all the accent characters.

Parsing JSON Giving “unexpected token o” Error

We’ll get the ‘unexpected token o’ error if the thing that we’re trying to parse is already an object.

Therefore, we should make sure that we aren’t parsing a JSON object.

Detecting Browser Language Preference

We can detect the browser language preference by using the window.navigator.userLanguage or window.navigator.language .

window.navigator.userLanguage is only available in IE.

window.navigator.language is available in other browsers.

It returns the language that’s set in Windows Regional Settings.

window.navigator.language returns the browser language and not the preferred language.

Creating a Blob from a Base64 String in JavaScript

To create a blob from a base64 string, we can use the atob function.

Then we’ve to create an array of byte values from each character of the string.

Then we convert the byte numbers array to an Uint8Array .

Then we can pass that into the Blob constructor.

Therefore, we write:

const byteCharacters = atob(b64Data);
const byteNumbers = new Array(byteCharacters.length);
for (let i = 0; i < byteCharacters.length; i++) {
    byteNumbers[i] = byteCharacters.charCodeAt(i);
}
const byteArray = new Uint8Array(byteNumbers);
const blob = new Blob([byteArray], {type: contentType});

to do all that.

Getting Current Date and Time

We can get the current date and time in JavaScript with various methods of the Date instance.

getDate gets the day of the month.

getDay gets the day of the week, with 0 being Sunday, 1 being Monday, etc.

getFullYear returns the full year umber.

getHours get the hours of the day.

getMinutes returns the minutes of the hour.

getSeconds get the seconds.

We can use it by writing:

const newDate = new Date();
const day = newDate.getDay();

We can also use the toLocaleString method to format our date string in a locale-sensitive manner:

new Date().toLocaleString();

Best Way to Track Change as we Type in an Input

To track changes as we type in the input box, we can listen to the input event.

For instance, we can write:

`const input = document.getElementById('input');
`const result = document.getElementById('result');

const inputHandler = (e) => {
  result.innerHTML = e.target.value;
}

source.addEventListener('input', inputHandler);

We get the input’s value in the inputHandler with e.target.input .

Also, we set the input value in the result element.

Then we call addEventListener to listen to the input event.

The Meaning of “=>” in JavaScript

=> lets us create an arrow function, which is a shorter function that doesn’t bind to this .

We can’t use arrow functions as constructor functions because of that.

It takes the value of this from whatever it is outside.

It also doesn’t bind to the arguments object, so we can’t use it to get arguments passed into a function.

Conclusion

JSON.stringify and JSON.parse are the opposite of each other.

=> lets us create arrow functions.

We can listen to the input event to get the value as user types into an input box.

Getting the current date and time can be done with date methods.

We can convert a base64 string to a blob.