Categories
JavaScript Tips

JavaScript Tips — Secure HTTP Server, Decoding URIs, and More

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.

The Difference Between decodeURIComponent and decodeURI

decodeURI is intended for decoding the whole URI.

decodeURIComponent is used for decoding the parts between separators.

We can pass in the parts and convert it back to the original URL.

For instance, we can write:

decodeURIComponent('%26')

and get '&' ,

However, when we write:

decodeURIComponent('%26')

We get back the original string.

However, if we write:

decodeURI('%41')

or:

decodeURIComponent('%41')

'A' is returned.

This means that decodeURIomponent can decode alphanumeric values and symbols.

But decodeURI can only decode alphanumeric values.

Open URL in the Same Window and in the Same Tab

We can open URLs in the same window and tab with if we use window.open with the argument '_self' .

For example, we can write:

window.open("https://www.example.com","_self");

Then the https://example.com URL will open in the same window.

Also, we can set the URL as the value of the location.href property to do the same thing:

location.href = "https://www.example.com";

Redirecting to a Relative URL

We can redirect to a relative URL if we set location.href to a relative path.

For instance, we can write:

window.location.href = '../';

to redirect one level up.

If we want to go to a path, we can write:

window.location.href = '/path';

to go to the path relative to the current domain.

Listen to change Events in a content editable Element

If we add a contenteditable attribute to an element, we can listen to the input event to watch for inputs.

For instance, if we have:

<div contenteditable="true" `id="editor"`>enter text</div>

Then to get the data that we typed into the div, we can listen to the input event:

document.getElementById("editor").addEventListener("input", () => {
  console.log("text inputted");
}, false)

We get the editor div and attach the input listener to it.

Then we should see the console log.

Process Each Letter of Text

We can loop through each letter of text using a loop and use the charAt method.

For instance, we can write:

for (const i = 0; i < str.length; i++) {
  console.log(str.charAt(i));
}

We can also use a while loop to do the same thing:

while (i--) {
  console.log(str.charAt(i));
}

Also, we can spread it into an array and use forEach to loop through each character:

[...`str`].forEach(c => console.log(c))

We can also use a for-of loop to loop through a string directly:

for (const c of str) {
  console.log(c)
}

And we can also use the split method to split it into an array of characters and loop through it:

str.split('').forEach((c) => console.log(c));

Remove a Character from a String

To remove a character from a string, we can use the replace method to do it.

For instance, we can write:

const str = "foo";
const newStr = str.replace('f', '');

Then we remove the 'f' character from the string.

We can also do the same thing with split and join :

const newStr = str.split('f').join('');

We split the string using 'f' as the separator and return an array of the parts separated by it.

Then we use join to join the parts back together.

Difference Between console.dir and console.log

There are differences between console.dir and console.log , even though they do the same thing.

log prints out the toString representation of an object, but dir prints out the whole object tree in Firefox.

In Chrome, console.log prints out the tree most of the time.

But it still prints the stringified version in some of the cases even if it has properties.

For instance, it’ll print out the stringified form of an HTML element.

console.dir always prints the object tree.

Create an HTTPS Server in Node.js

To create an HTTPS server with Node.js, we can read the certificate and private key into the server program.

Then we set the credentials when loading the server to make it use the certificate.

For instance, we can write:

const crypto = require('crypto');
const fs = require("fs");
const http = require("http");

const options = {
  key: fs.readFileSync('key.pem'),
  cert: fs.readFileSync('cert.pem')
};

https.createServer(options, (req, res) => {
  res.writeHead(200);
  res.end("hello worldn");
}).listen(8000);

We read the private key and certificate with the readFileSync calls.

Then we put the key and certificate in the options object.

When we call createServer , we pass in the key and certificate through the object.

Conclusion

We can iterate through each letter of the text in various ways. To create a secure HTTP server, we can read in the private key and certificate. decodeURI and decodeURIComponent are different.console.dir always print the object tree.

Categories
JavaScript Tips

JavaScript Tips — Objects, Circular JSON, and Converting Strings to Dates

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.

Print a Circular Structure in a JSON-like Format

We can use the util library to print circular structures.

It has an inspect method that lets us print these structures.

So we can write:

console.log(util.inspect(obj));

to do that.

There’s also the circular-json package that does the same thing.

We install it by running:

npm i --save circular-json

and write:

const CircularJSON = require('circular-json');
const json = CircularJSON.stringify(obj);

There’s also the flatted package.

We install it by running:

npm i flatted

Then we can write:

import {parse, stringify} from 'flatted';

const foo = [{}];
foo[0].foo = foo;
foo.push(foo);

stringify(foo);

Check if Object Property Exists with a Variable Holding the Property

We can use the hasOwnProperty method or in operator to check if a property exists.

For example, we can write:

const prop = 'prop';
if (obj.hasOwnProperty(prop)) {
  //...
}

or we can write:

const prop = 'prop';
if (prop in obj) {
  //...
}

Check if a User has Scrolled to the Bottom

We can check with plain JavaScript.

We write:

el.onscroll = () => {
  if(el.scrollTop + el.clientHeight === el.scrollHeight) {
    // ...
  }
}

We run an event handler on scroll.

To check that the user scrolled to the bottom, we check that the sum of scrollTop and clientHeight is the same as the scrollHeight .

scrollTop is the number of pixels that the element is scrolled vertically.

clientHeight is the height of the element in pixels.

Padding is included, but borders, margins, and horizontal scrollbars are excluded.

Determine Equality for Two JavaScript Objects

We use the LodashisEqual method to check for deep equality.

For instance, we can write:

_.isEqual(object, other);

Enumerate the properties of a JavaScript Object

To enumerate the properties of a JavaScript object, we can use the for-in loop or Object.keys .

For instance, we can write:

for (const p in obj) {
  if (obj.hasOwnProperty(p)){
    //...
  }
}

We call hasOwnProperty to check if a property is in an object.

This is because for-in enumerates all properties in the prototype chain.

Likewise, we can use Object.keys:

for (const p of Object.keys(obj)) {
  //...
}

We use the for-of loop instead of the for-in loop since Object.keys returns an array of the own keys.

Converting a String to a Date in JavaScript

We can use the Date constructor to parse a date string into a Date instance:

const parts = '2014-04-03'.split('-');
const date = new Date(parts[0], parts[1] - 1, parts[2]);
console.log(date.toDateString());

We extract the date string’s year, month, and date.

Then we put them in the Date constructor.

We’ve to subtract 1 from the month because month 0 is January, 1 is February, etc.

Then we get the correct date.

Detect if a Browser Window is not Currently Active

To check if a browser window is active or not, we can watch the visibilitychange event in our code.

For instance, we can write:

document.addEventListener("visibilitychange", onchange);

Where onchange is:

const `onchange =` () => {
  if (document.hidden) {
    //...
  } else {
    //...
  }
}

We check the document.hidden property to check if a page is hidden.

Read a File One Line at a Time in Node.js

We can use the readline module to read a file one line at a time.

For instance, we cabn write:

const lineReader = require('readline').createInterface({
  input: require('fs').createReadStream('file')
});

lineReader.on('line', (line) => {
  console.log(line);
});

We use the readline module and pass in an object with the read stream for the file.

Then listen to the line event to get the lines.

JavaScript Equivalent to PHP isset()

PHP’s isset function has several equivalents in JavaScript.

We can use the typeof operator, hasOwnProperty , or the in operator.

For instance, we can write:

if (typeof obj.foo !== 'undefined') {
  // ...
}

to check if obj.foo is defined or not.

We can also write:

if (obj.hasOwnProperty('foo')) {
  // ...
}

or:

if ('foo' in obj) {
  // ...
}

Then in operator checks if the property exists in obj ‘s prototypes, so we should be aware of that.

Conclusion

There many ways to check if a property exists.

We can use libraries to print circular JSON.

Deep equality of objects can be checked with Lodash.

Categories
JavaScript Tips

JavaScript Tips — ESLint Rules, Canvas, Cleaning Local Storage

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.

Turn JavaScript Array into a Comma-Separated List

We can use the array instance’s join method to join the strings together with a comma.

For instance, we can write:

const arr = ["foo", "bar", "baz"];
console.log(arr.join(", "));

Constructors in JavaScript Objects

JavaScript objects can be created from constructors.

To create it. we write:

function Box(color) {
  this.color = color;
}

Box.prototype.getColor = function(){
  return this.color;
};

We created the Box constructor with the color instance variable.

Also, we attach the getColor method with the prototype property to return the color .

Then we can use the new operator to create a Box instance:

const box = new Box("brown");
console.log(box.getColor());

Equivalent, we can use the class syntax:

class Box {
  constructor(color) {
    this.color = color;
  }

  getColor(){
    return this.color;
  }
}

We put everything in the Box class instead of using prototypes.

However, they’re the same.

Disable ESLint Rule for a Specific File

We can disable ESLint rules for a specific file with comments.

For instance, we can write:

/* eslint no-use-before-define: 0 */

to turn off the a no-use-before-define rule.

Or we can write:

/* eslint-disable no-use-before-define */

to do the same thing.

And we can write:

/* eslint no-use-before-define: 2 */

to turn it on.

We can also tell ESLint to ignore specific files by putting the file paths in .eslintignore :

build/*.js
node_modules/**/*.js

Add a JavaScript / jQuery DOM Change Listener

To listen for DOM changes, we can listen to the DOMSubtreeModified event.

For instance, we can write:

$("#div").bind("DOMSubtreeModified", () => {
  console.log("tree changed");
});

We use jQuery’s bind method to listen to the event.

Early Exit from Function

To end a function early, we can use the return keyword.

It can be placed anywhere to end a function early.

For example, we can write:

const myfunction = () => {
  if (shouldStop) {
    return;
  }
}

Removing Items from Local Storage When the Tab or Window is Closed

To remove the item from local storage when the tab or window is closed, we can listen to the beforeunload event.

In the listener function, we can call removeItem to remove the item.

For instance, we can write:

window.onbeforeunload = () => {
  localStorage.removeItem(key);
  return '';
};

The listener should return a string.

Selecting “selected” on Selected <select> Option in a React Component

We can set the value prop of the select element to set the selected option.

For instance, we can write:

<select value={chosenItem}>
  <option value="A">apple</option>
  <option value="B">banana</option>
  <option value="O">orange</option>
</select>

We set the chosenItem state with setState in a class component.

Or we can use the state change function returned from the useState method to set it.

Resize HTML5 Canvas to Fit Window

To resize the HTML5 canvas to fit the window, we can change the width and height of the canvas with JavaScript.

For instance, we can write:

`const resizeCanvas = () => {
  const canvas =` document.getElementById('canvas'),
  `const ctx = canvas.getContext('2d');
  ctx.canvas.width  = window.innerWidth;
  ctx.canvas.height = window.innerHeight;
}`

window.addEventListener('resize', resizeCanvas, false);

innerWidth sets the width to the window width and innerHeight sets the height to the window height.

We watch the resize event to set the dimensions.

Adding Hours to JavaScript Date Object

We can add hours to the JavaScript date object with the getTime method to get the timestamp.

Then we add the milliseconds to the timestamp to add the number of hours we want.

For example, we can write:

date.setTime(date.getTime() + (hours * 60 * 60 * 1000));

We use setTime to set the timestamp of the new date.

Check if the Array is Empty or does not Exist

To check if an array is empty or doesn’t exist, we can use the Array.isArray method and check 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 check if the length is 0 or not with !array.length .

If both are true then we know it’s not an array

If only !array.length is true then we know that array is an empty array.

Conclusion

We can disable ESLint rules with comments or .eslintignore.

The DOMSubtreeModified is emitted when the DOM structure changed.

JavaScript objects can be created from constructors or classes.

Categories
JavaScript Tips

Useful JavaScript Tips — Numbers, Strings, and Strict Mode

As with any kind of app, JavaScript apps have to be written well otherwise we will 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.

Tip #1: Trim the Leading Zero in a Number String

We can trim the leading zero in a number by parsing the number string to a number.

To parse it into an integer, we can use the parseInt function.

For instance, we can write:

parseInt('010', 10)

Then we’ll parse the number string into a decimal.

If we want to parse a string into a number.

Then we can use the + operator. For instance, we can write:

+'010'

Then we get 10.

Also, we can string the leading 0 with regex and the replace method.

For instance, we can write:

number.replace(/^0+/, '')

^ means the start of the string.

Tip # 2: Replace All Occurrences of a String

We can replace all occurrences of a string with the replace method, a regex and the g flag for global replace.

For instance, we can write:

const phrase = 'I love dogs, dogs are great';  
const stripped = phrase.replace(/dog/g, 'cat');

Then we get “I love cats, cats are great” .

/dog/g is the regex. And 'cat' is what we replaced 'dog' with.

To perform a case insensitive search, we can add the i flag.

For instance, we can write:

const phrase = 'I love dogs. Dogs are great';  
const stripped = phrase.replace(/dog/gi, 'cat');

Then we get “I love cats. cats are great” .

We can also replace all substrings by using the split and join methods.

For instance, we can write:

const phrase = 'I love dogs, dogs are great';  
const stripped = `phrase.split('dog').join('cat')`;

We split the phrase string with 'dog' as the separator.

Then we call join with 'cat' so 'cat' replaces dog.

Therefore, stripped is “I love cats, cats are great” .

Tip # 3: Check if a Property is Undefined

If want to check if a property is undefined, then we can use the typeof operator.

For instance, we can write:

typeof color

Then if color is undefined, then it should return 'undefined' .

If we want to check an object property for undefined , then we can write:

typeof dog.color === 'undefined'

given that dog is an object.

Tip #4: Remove a Property from a JavaScript Object

We can remove a property from a JavaScript object by using the the delete operator.

To use it, we put delete in front of the property that we want to delete.

For instance, if we have the following object:

const dog = {  
  color: 'brown'  
}

Then we can write:

delete dog.color

Then we removed the color property from dog .

Tip #5: Redirect to Another Page

We can redirect to another page by setting a URL to the window.location object.

For instance, we can write:

window.location = 'https://example.com'

Then we go to https://example.com.

If we want to go to a relative path, then we can set the pathname property.

For instance, we can write:

window.location.pathname = '/foo'

Then we go to /foo .

We can also set the href property to go to a URL:

`window.location.href = 'https://`example`.com'`

Also, we can call the window.location.assign method to do the same thing:

window.location.assign('https://example.com')

Likewise, we can use the replace method. This rewrites the current page in history with the new URL.

We can write:

window.location.replace('https://example.com')

The browser also hs the self and top objects, which are the same as the window object.

So we can replace window with those objects.

Tip #6: Use Strict Mode

Strict mode disallows the use of some bad features in JavaScript.

To use it, we use the 'use strict' directive to enable it.

With strict mode, we can’t accidentally declare global variables.

For instance, we can’t write:

foo = 'bar';

with JavaScript strict mode on. It also disallows assignment to reserved keywords.

For example, we can’t write:

undefined = 1

Also, we can’t override object properties that are marked to be not writable.

For instance, if we have:

const dog = {}  
Object.defineProperty(dog, 'color', { value: 'brown', writable: false })

Then we can’t override the value by reassigning it.

Getter properties also can’t ve overridden with new values.

With strict mode on, we can’t add properties that we disallowed from adding properties with Object.preventExtensions .

Also, we can’t delete built-in objects with it.

Function arguments with the same name also can’t be in the same signature.

So we can’t write:

function(a, a, b) {  
  console.log(a, b)  
}

Conclusion

We can remove leading zero a number string by parsing it. There are various ways to replace all instances of a string. Strict mode is great for preventing us from adding bad code.

Categories
JavaScript Tips

JavaScript Tips — Listeners, Sorting, and Nested Objects

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.

addEventListener vs onclick

addEventListener and onclick are equivalent.

However, we can use addEventListener to listen to events from more than one DOM element.

For instance, if we have:

element.addEventListener('click', () => {
  //...
}, false);

Then we can listen to the click event of element .

We can also write:

element.onclick = () =>
  //...
}

which does the same thing.

We can use the event object to listen to multiple events.

For example, we can write:

element.addEventListener('click', (event) => {
  //...
}, false);

Then we can use the event object to get the event data from elements that’s a child of element and check for actions.

Strip all Non-Numeric Characters from String

We can strip all non-numeric characters from a string with the replace method.

For example, we can write:

const s = "123 abc".replace(/[^\d.-]/g, '');

We use the ^\d to look for all non-numeric characters.

Then we add the g tag to search for all instances of the pattern in the string.

How to Sort an Array by a Date Property

To sort an array by a Date property, we can use the sort method.

For instance, we can write:

array.sort((a, b) => {
  return new Date(b.date) - new Date(a.date);
});

We turn the date strings into Date instances, then we can subtract them to get the sort order.

We can do that since the subtraction operator will convert the Date instances into timestamps, which are integers.

Sorting Object Property by Values

To sort object properties by values, we can sort the keys by their values with the sort method.

For instance, we can write:

const list = {"baz": 200, "me": 75, "foo": 116, "bar": 15};
keysSorted = Object.keys(list).sort((a, b) => {
  return list[a] - list[b];
})
console.log(keysSorted);

We have the list object.

And we get the keys as an array with Object.keys .

Then we can call sort on the returned array.

Moment.js Transform to Date Object

We can use the toDate method to transform a moment object into a Date object.

For instance, we can write:

moment().toDate();

Test for Existence of Nested JavaScript Object Key

We can check for a key with the recursive function.

For instance, we can write:

const checkNested = (obj, level,  ...rest) => {
  if (obj === undefined) {
     return false;
  }

  if (rest.length === 0 && obj.hasOwnProperty(level)) {
    return true;
  }
  return checkNested(obj[level], ...rest)
}

We check if obj is undefined and return false if it is since it’s undefined before we got to the end of the path.

Otherwise, we check that there are no arguments left and check if the property with the key level exists.

If that exists, then we return true .

Otherwise, we call the checkNested function again by moving on to the lower level.

So we can call it by writing:

checkNested(foo, 'level1', 'level2', 'bar');

to check if foo.level1.level2.bar exists.

To make our lives easier, we can also use the ?. optional chaining operator:

const value = obj?.level1?.level2?.level3

It’ll just return undefined if any intermediate level doesn’t exist.

Playing Audio with Javascript

We can use the play method of an audio element to play audio with JavaScript.

For instance, we can write:

const audio = new Audio('audio.mp3');
audio.play();

or:

document.getElementById('audioPlayer').play();

Defining a Class in JavaScript

We can define a class in 2 ways.

We can create a constructor function or use a class syntax.

For instance, we can write:

function Person(name) {
  this.name = name;
}

to create a Person constructor.

Then to add methods, we write:

Person.prototype.greet = function() {
  console.log(`hello ${this.name}`);
}

We can use the class syntax to do the same thing:

class Person {
  constructor(name) {
    this.name = name;
  }

  greet``() {
    console.log(`hello ${ this.name }`);
  }
}``

We define instance methods in the class instead of adding a property to prototype .

It’s cleaner and static analysis can check its syntax.

It’s also easier to understand for people coming from class-based languages.

Both ways are the same.

Conclusion

We can define classes in multiple ways.

Also, we can test for the existence of nested object keys by using the optional chaining operator or our own function.

There are various ways to sort things.