Categories
JavaScript JavaScript Basics

JavaScript Events Handlers — onblur and onerror

In JavaScript, events are actions that happen in an app. They are triggered by various things like inputs being entered, forms being submitted, changes in an element like resizing, or errors that happen when an app is running, etc.

We can assign event handlers to respond to these events. Events that happen to DOM elements can be handled by assigning an event handler to properties of the DOM object for the corresponding events.

In this article, we will look the onblur and the onerror property.

window.document.onblur

The onblur property let’s set an event handler function to it to handle the blur event, where the object that represents the element that can lose focus has lost focus. For example, we can attach a onblur event listener function by writing the following code:

document.onblur = () => {  
  console.log('Document lost focus.');  
};

After adding the code above, when we click outside the page then ‘ Document lost focus.’ should be logged.

window.document.onerror

The onerror property lets us attach an event handler to handle situations when the error event is triggered.

The error event is triggered when a JavaScript run time error occurs, such as when syntax errors or exceptions are being thrown within handlers occurs. The error event handler can take a parameter that has the ErrorEvent object in this case.

These errors get bubbled up to the window object by default. It’s also fired when a resource, like an image or script element, fails to load. An error event using the Event interface will be passed into the error event handler in this case. These errors do not get bubbled up to the window object, but it can be handled in window.addEventListener with useCapture is set to true which is the third argument of the addEventListener method.

For historical reasons, the arguments that are passed into window.onerror are different from the ones that are passed into element.onerror as well as on error-type window.addEventListener handlers. window.onerror’s error handler function has the following function signature:

window.onerror = function(message, source, lineno, colno, error) { ... }

Where message is the error message, the source is the string of the URL of the script that threw the error. The lineno parameter is a number that has the line number where the error was raised. The colno parameter is a number that has the column number for the line where the error occurred. The error parameter has the Error object. The Error object has the following standard properties:

  • constructor — the function that created the instance’s prototype
  • message — the error message
  • name — the error name

It also has vendor-specific properties. For Microsoft browsers, the Error object has the following additional properties:

  • description — the error description, which is similar to message
  • number — the error number

For Mozilla browsers, the following additional properties are added to the error object:

  • fileName — the path to the file that raised the error
  • lineNumber — the line number that raised the error
  • columnNumber — the column number of the line that raise the error
  • stack — the stack trace of the error

If an error event handler is passed into the second argument of the window.addEventListener method, then the function signature of the event handler is significantly different. It should have one event parameter which is the ErrorEvent, so the function signature should be the one below:

window.addEventListener('error', function(event) { ... })

The ErrorEvent inherits all the properties from the Event object plus the following properties are included:

  • message — a read-only property that as the string of the human-readable error message which describes the error
  • filename — a read-only string property that has the name of the script of the file in which the error occurred
  • lineno — a read-only integer that has the line number of the script of the file on which the error occurred
  • colno — a read-only integer that has the column number of the script where the error occurred
  • error — a read-only JavaScript object that has the data about the event

If the onerror is a property of anything other than window, then the event handler that we assign to it should have the same signature as we have above, which is only the event parameter which will have the ErrorEvent passed in when an event occurs.

So with the onerror event handler we can handle any error that occurs when loading the page and running the scripts that are loaded on the page. For example, we can use it to handle the situation when an image fails to load by providing an alternative image which we can load.

For example, if we want to load an image that might exist, then we can add an onerror attribute to the img element to load the fallback image like in the following code:

<img src="invalid.gif" onerror="this.src='[https://images.unsplash.com/photo-1556742521-9713bf272865?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1534&q=80'](https://images.unsplash.com/photo-1556742521-9713bf272865?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1534&q=80');" />

To handle errors during script loading, we can write the following code:

<!DOCTYPE html>  
<html>  
  <head>  
    <title>Error</title>  
  </head>  
  <body>  
    <script src="main.js"></script>  
    <script src="error.js"></script>  
  </body>  
</html>

Then in main.js we add our onerror event handler:

window.onerror = (message, source, lineno, colno, error) => {  
  console.log(message);  
  console.log(source);  
  console.log(lineno);  
  console.log(colno);  
  console.log(error.toString());  
};

Then we put some expressions or statements that throws an error in error.js like the following code:

xyz

Then we should get the error logged in our console.log statements inside the onerror event handler in main.js . We should get something like the following output from the console.log statements:

Uncaught ReferenceError: xyz is not defined  
[http://localhost:3000/error.js](http://localhost:3000/error.js)  
1  
1  
ReferenceError: xyz is not defined

The first console.log output has the error message. The second line in the output has the path to the script that caused the error message. Line 3 has the line number of the script where the error occurred. The fourth line has the column number of the line that caused the error, and the last line has the Error object converted to a string, which returns the error message.

If we instead write use the window.addEventListener method to add the event handler, then we can write the following code to log the ErrorEvent object:

window.addEventListener("error", event => {  
  console.log(event);  
});

Then we should get something like the following output from the console.log statement in the event handler above:

bubbles: false  
cancelBubble: false  
cancelable: true  
colno: 1  
composed: false  
currentTarget: Window {parent: Window, postMessage: ƒ, blur: ƒ, focus: ƒ, close: ƒ, …}  
defaultPrevented: false  
error: ReferenceError: xyz is not defined at [http://localhost:3000/error.js:1:1](http://localhost:3000/error.js:1:1)  
eventPhase: 0  
filename: "[http://localhost:3000/error.js](http://localhost:3000/error.js)"  
isTrusted: true  
lineno: 1  
message: "Uncaught ReferenceError: xyz is not defined"  
path: [Window]  
returnValue: true  
srcElement: Window {parent: Window, postMessage: ƒ, blur: ƒ, focus: ƒ, close: ƒ, …}  
target: Window {parent: Window, postMessage: ƒ, blur: ƒ, focus: ƒ, close: ƒ, …}  
timeStamp: 68.510000128299  
type: "error"

In the output above, we get everything from the Event object plus the additional properties from the ErrorEvent object that we listed above like the error property, message property and the filename property.

Conclusion

With the onblur property, we can set an event handler that can handle the blur event. The onerror property lets us set the event handler for when the error event occurs, which happens when something fails to load like an image or a script that fails to run because of some error.

These are handy event handlers that let us handle user interaction and unexpected errors when resource load respectively.

Categories
JavaScript JavaScript Basics

Formatting Dates with Moment Date Format

With moment.js, we can format dates easily with moment.js.

The list of formatting code that we can use with moment.js are below:

Year, Month, and Day Tokens

  • YYYY – 4 or 2 digit year
  • YY – 2 digit year
  • Y – year with any number of digits and sign
  • Q – quarter of year from 1 to 4
  • M MM – month number
  • MMM MMMM – month name according to the locale
  • D DD – day of the month
  • Do – day of the year
  • X – UNIX timestamp
  • x – UNIX mx timestamp

Week Year, Week, and Weekday Tokens

  • gggg – locale 4 digit week year
  • gg – locale 2 digit week year
  • w ww – locale week of year
  • e – locale day of week
  • ddd dddd – day name
  • GGGG – ISO 4 digit week year
  • GG – ISO 2 digit week year
  • W WW – ISO week of year
  • E – ISO day of week

Locale Aware Formats

  • L – date (in locale format)
  • LL – month name, day of month, year
  • LLL – month name, day of month, year, time
  • LLLL – day of week, month name, day of month, year, time
  • LT – time without seconds
  • LTS – time with seconds

Hour, Minute, Second, Millisecond, and Offset Tokens

  • H HH – hours in 24-hour format from 0 to 23
  • h hh – hours in 12 hours format
  • k kk – hours in 24 hour time from 1 to 24
  • a A – am or pm
  • m mm – minutes
  • s ss – seconds
  • S SS SSS – fractional seconds
  • Z ZZ – offset from UTC

For instance, we can call the format method as follows:

import moment from "moment";
const formattedTime = moment("2010-10-20 4:30").format("YYYY-MM-DD HH:mm");
console.log(formattedTime);

In the code above, we created a moment object with the moment factory function, and then call the format with the format string.

The formatting string is the combination of the parts that are listed above.

It’s very powerful and we can use it to format dates however we like.

Categories
JavaScript JavaScript Basics

How to Add Property to an Object in Javascript

There’re a few ways to add properties to an object in JavaScript.

One way is to add a property using the dot notation as follows:

obj.foo = 1;

We added the foo property to the obj object above with value 1.

We can also add a property by using the bracket notation as follows:

obj['foo'] = 1;

It does the same thing as the first example, but we can have invalid property identifiers in the string.

So we can write something like:

obj['foo-bar'] = 1;

'foo-bar' isn’t a valid identifier, but we can add it as a property.

We can also use the Object.defineProperty function as follows:

Object.defineProperty(obj, 'foo', {
  value: 1
})

We can have more control of how property will act with this method. In addition to setting the value with the value property, we can also set it to be writable or not with the writable property, and set it to be enumerable or not with the enumerable property.

Enumerable means that whether it’ll be retrieved or looped through with Object.keys or the for-in loop.

Writable means whether we can set a new value for the property.

Setting the property to an object with JavaScript is an easy task if we use these 3 ways to do it.

Categories
JavaScript JavaScript Basics

Lodash Features that are Available in Plain JavaScript

In recent years, new features in JavaScript have been rolling out at a rapid pace. The deficiencies that are filled in by other libraries before have become built-in features of plain JavaScript.

In this article, we’ll look at the methods in Lodash that are now available in plain JavaScript.

Map

Lodash has a map method to map each array entry to another by a function that we specify. It takes in an array and a function to transform the entries as arguments.

For example, we can call Lodash’s map method by writing:

const arr = _.map([1, 2, 3], n => n ** 2);

Then we get back:

[1, 4, 9]

JavaScript’s arrays now have the map method. We can use it as follows:

const arr = [1, 2, 3].map(n => n ** 2);

It also returns a new array but takes one less argument since it’s a method in an array.

Filter

The filter method in Lodash returns a new array that has the filtered entries of the original array. It takes an array and a function that returns the condition for the filter as arguments.

For example, we can write:

const arr = _.filter([1, 2, 3], n => n % 2 === 0);

to return an array with only even numbers.

With JavaScript array’s filter method, we can simplify the code a bit since it’s called on the array itself. We can rewrite it as:

const arr = [1, 2, 3].filter(n => n % 2 === 0);

In both cases, we get [2] back.

Reduce

Like the other 2 array methods, Lodash’s reduce method now has a plain JavaScript equivalent with the same name. Both of them let us combine our array entries into one thing.

For example, to get the sum of all the entries in an array, we can use the Lodash reduce method as follows:

const arr = _.reduce([1, 2, 3], (total, n) => total + n, 0);

The Lodash version took 3 arguments, which is the array to combine, the function used to combine the values, and the initial value for the combined value.

With JavaScript array’s reduce method, it’s similar except that we call it on the array directly as follows:

const arr = [1, 2, 3].reduce((total, n) => total + n, 0);

In both cases, we get 6 as a result.

Head

Lodash’s head method returns the first element of an array. For example:

const first = _.head([3, 4, 5]);

will get us 3 as the value of first .

We can do this with JavaScript by writing the following:

[3, 4, 5][0]

or:

const [first] = [3, 4, 5];

Tail

The Lodash’s tail method will get us everything but the first entry of an array.

For example, we can use it as follows:

const rest = _.tail([3, 4, 5]);

Then we get [4, 5] as the value of rest.

We can write the following to get everything but the first element of an array by writing:

const rest = [3, 4, 5].slice(1);

or:

const [first, ...rest] = [3, 4, 5];

The spread operator will give us the rest of the elements stored in the rest variable as the array, so we get the same thing.

Rest

Lodash’s rest method gets the extra arguments that are passed into the callback function that we pass into it that are in excess of the number of parameters and returns a function that let us do something with those extra arguments.

For example, if we have:

const restFn = _.rest((first, rest) => rest);

Then calling restFn(“foo”, “bar”, “baz”); will return [“bar”, “baz”] .

We have the rest operator to do the same thing in JavaScript’s rest operator:

const restFn = (first, ...rest) => rest

Spread

In Lodash, the spread method will return a function that takes a callback function, and then return a function where we pass in an array which we use as the arguments of the callback function we passed in.

For example, if we have:

const spreadFn = _.spread((foo, bar) => `${foo} ${bar}`);

Then when we call spreadFn as follows:

spreadFn(["foo", "bar", "baz"])

We get back:

'foo bar'

It’ll take each entry of the array passed into spreadFn , and pass it as the arguments of the function that we passed into the spread method.

This is the same as calling a function as is in JavaScript:

const spreadFn = function(foo, bar) {  
  return `${foo} ${bar}`;  
}

Then we can use the apply method on the function to do the same thing:

spreadFn.apply(null, ["foo", "bar", "baz"])

And we get the same result.

As we can see, lots of methods in Lodash have equivalents in plain JavaScript, especially array methods. So to reduce the reliance of libraries, we can use more plain JavaScript replacements here to replace existing uses of Lodash methods when they make code cleaner and lighter.

Categories
JavaScript JavaScript Basics

JavaScript Array Tips — Removing Duplicates and Emptying Arrays

JavaScript, like any other programming languages, have many handy tricks that let us write our programs more easily. In this article, we will look at how to do different things that involve arrays, like removing falsy values, getting random values from an array, and reversing arrays.

Removing Falsy Values

In JavaScript, falsy values include 0, empty string, null , undefined , false and NaN . We often run into these values when we’re processing arrays and they may cause errors.

Values like null , undefined , and NaN often are unexpected and it’s easier if we eliminate them from an array before doing anything else to them.

We can do this with a few ways which involve using the filter method that is available to arrays. The filter method takes in a callback function.

The callback function that has 2 parameters, the first one is an array entry and the second one is the index of the array that’s being iterated to by the filter method. The filter method filter let us defined what we want to keep and return a new array with the entries kept according to the boolean expression we return.

Any function that’s defined that takes at least the value and returns a boolean value can be used as the callback function, so one way we can use the filter method to filter out is to use the Boolean factory function, which takes in any object in its first argument and returns true if it’s truthy and false if it’s falsy. If true is returned from the callback function then the item will be kept.

Otherwise, it will discard the value in the array it returns. For example, we can use the Boolean function by passing in straight into the filter method like we do in the following code:

let arr = [0, 'yellow', '', NaN, 1, true, undefined, 'orange', false];  
arr = arr.filter(Boolean);  
console.log(arr);

Then we get the following output from the console.log :

["yellow", 1, true, "orange"]

We can also use the exclamation mark operator twice to coerce truthy values to true and falsy values to false . We just put the exclamation 2 times in front of value to do this, so we can use the operator like in the following code to filter out falsy values:

let arr = [0, 'yellow', '', NaN, 1, true, undefined, 'orange', false];  
arr = arr.filter(a => !!a);  
console.log(arr);

If we run the code above, we should get the same thing as we did before. Likewise, we can pass in a function that returns the value from the Boolean function instead of passing in Boolean function directly to the filter method to make the expression more clear:

let arr = [0, 'yellow', '', NaN, 1, true, undefined, 'orange', false];  
arr = arr.filter(a => Boolean(a));  
console.log(arr);

We should get the same thing as we did before if we run the code above.

Get a Value Randomly from an Array

To get a random value from an array, we can use the Math.random method to get a random index in addition to some other code.

We more code than just calling the Math.random method because it only returns a random number between 0 and 1, which means that it returns a decimal number between 0 and 1, which we don’t want.

This means that it has to be multiplied by our array’s length to get a value between 0 and the length of our array. Then we need call Math.floor on that result to round it down to the nearest integer.

We can use the Math.random method like in the following code:

let arr = ['yellow', 'orange', 'blue', 'purple', 'green'];  
const chosenValue = arr[(Math.floor(Math.random() * (arr.length)))]  
console.log(chosenValue);

The code above generates the index by running Math.random() * (arr.length) , which will range from 0 to the length of the array. Then we round it down with the Math.floor method which takes a number that we want to round down so that we get the number rounded down to the nearest integer since we don’t want non-integer numbers.

Then we can pass that into the brackets to get the index that was generated.

Reversing an Array

We can reverse an array by using the reverse method that comes with JavaScript array objects. It takes no arguments and reverses an array in place. For example, we can use it as in the following code:

let arr = ['yellow', 'orange', 'blue', 'purple', 'green'];  
arr.reverse();  
console.log(arr);

Then we get:

["green", "purple", "blue", "orange", "yellow"]

from the console.log output above. The reverse method works with any primitive objects in addition to objects. For example, if we have:

let arr = [{  
  a: 1  
}, {  
  b: 2  
}, {  
  c: 3  
}];  
arr.reverse();  
console.log(arr);

Then we get back the following output from the console.log :

[  
  {  
    "c": 3  
  },  
  {  
    "b": 2  
  },  
  {  
    "a": 1  
  }  
]

The reverse method also works with any object that has numerical keys. For example, if we have:

let arrLikeObj = {  
  0: 'a',  
  1: 'b',  
  2: 'c',  
  length: 3  
}  
Array.prototype.reverse.call(arrLikeObj);  
console.log(arrLikeObj);

Then we get back the following output from the console.log :

{  
  "0": "c",  
  "1": "b",  
  "2": "a",  
  "length": 3  
}

As long as the object has numerical keys starting from 0 and increments by 1 from there and a length property, the code above will work. We can also use the apply method to do the same thing like in the following code:

let arrLikeObj = {  
  0: 'a',  
  1: 'b',  
  2: 'c',  
  length: 3  
}  
Array.prototype.reverse.apply(arrLikeObj);  
console.log(JSON.stringify(arrLikeObj, (key, value) => value, 2));

Then once again we get back the following output from the console.log :

{  
  "0": "c",  
  "1": "b",  
  "2": "a",  
  "length": 3  
}

Conclusion

In JavaScript, falsy values include 0, empty string, null , undefined , false and NaN . We often run into these values when we’re processing arrays and they may cause errors. Values like null , undefined , and NaN often are unexpected and it’s easier if we eliminate them from an array before doing anything else to them.

We can do this with a few ways which involve using the filter method that are available to arrays.

We can use the Boolean function or applying the exclamation mark twice to convert an object into a boolean value. To reverse an array, we can use call the reverse method on an array to reverse it.

The reverse method also works with any object that has numerical keys starting from 0 and increments by 1 and a length property. We can get a random entry from an array by using Math.random multiplied by the array’s length and Math.floor methods.