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.
Extract the Hostname Portion of a URL
We can extract the hostname portion of the URL with the hostname
property of window.location
.
For instance, if we go to http://example.com/, then window.location.hostname
returns “example.com”
.
Get the First N Number of Elements from an Array
To get the first n
number of elements from an array, we can use the slice
method.
For instance, we can write:
arr.slice(0, n)
to get the first n
elements of an array.
It doesn’t include the item with index n
.
We can also set the length
property of the array.
So arr.length = n
will truncate arr
into length n
.
Find a Value in an Array of Objects in Javascript
To find a value in an array of objects with the given value, we can use the find
method.
For instance, if we have the given array:
const arr = [
{ name: "james", value:"foo", other: "that" },
{ name: "mary", value:"bar", other: "that" }
];
Then we can write:
const obj = arr.find(o => o.name === 'james');
to find the entry with the name
property set to
‘james’and assign it to
obj` .
Conditionally add a Property to an Object
We can add a property to an object conditionally with the ternary operator.
For instance, we can write:
const obj = {
b: addB ? 5 : undefined,
c: addC ? 5 : undefined,
}
where addB
and addC
are boolean expressions to determine if b
and c
should have a value respectively.
Round to 1 Decimal Place in Javascript
To round a number to one decimal place, we can use the toFixed
method to do it.
For instance, we can write:
number.toFixed(1)
to round it to 1 decimal place.
Why does Node.js’ fs.readFile() Return a Buffer Instead of a String?
If no encoding is specified, then fs.readFile
returns a buffer.
To make it return a string, we pass in the encoding.
For instance, we can write:
fs.readFile("foo.txt", "utf8", (err, data) => {...});
We read the content of foo.txt
and specifies the encoding is 'utf8'
to make sure it’s read as text.
Is Node.js Array.forEach Asynchronous?
Node.js’s array forEach
method is the same as the regular forEach
method.
Therefore, it’s a synchronous function.
If we want to iterate asynchronously, we can use the for-of loop with promises or async.each
from the async
library:
async.each(files, saveFile, (err) => {
//...
});
We pass in the array to iterate as the first argument.
The function to run on each entry as the 2nd argument.
The last argument is the callback to call when iteration is done.
er
us the error object that’s defined when an error is encountered.
Generate Formatted Easy-to-Read JSON Straight from an Object
JSON.stringify
can be used to format JSON that’s stringified.
For instance, we can write:
JSON.stringify(obj, null, 2);
to indent the stringified JSON with 2 spaces.
We can also pass in an indentation character:
JSON.stringify(obj, null, 't');
Then we indent with tabs.
Difference Between ‘throw new Error’ and ‘throw obj’
There are differences between throwing errors and throwing any other kind of object.
Error
objects have a name, message, and the stack trace.
Throwing any other kinds of objects will expose the message to the user.
For instance, we can write:
try {
throw "error";
} catch (e) {
console.log(e);
}
Then the console log would log 'error'
.
There won’t be a name
and message
properties.
On the other hand, if we have:
try {
throw new Error("error")
} catch (e) {
console.log(e.name, e.message);
}
Then e.name
would be 'Error'
and e.message
would be 'error'
.
Conclusion
We can extract the hostname portion of the URL with the window.location.hostname
property.
We can use slice
to get the first n
entries from an array.
To find an object with the given property value from an array of objects, we can use find
.
There’s a difference between throwing Error
instances and any other kinds of objects or values.