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.
Check if a Value Exists at a Certain Array Index
We can check if a value exists at a certain array index.
To do that, we can write:
if (typeof array[index] !== 'undefined') {
//...
}
or:
if (typeof array[index] !== 'undefined' && array[index] !== null) {
//...
}
This way, we check if the array entry exists by checking that it’s not undefined
or null
.
How to Iterate over a JSON structure?
We can loop through an array with the for-of loop.
For instance, we can write:
const cars = [{ name: 'Suzuki' }, { name: 'BMW' }];
for (const car of cars) {
console.log(car.name);
}
We also can write:
const cars = [{ name: 'Suzuki' }, { name: 'BMW' }];
for (const { name } of cars) {
console.log(name);
}
We restructured the car
object by getting its name
property directly.
Pushing Element at the Beginning of an Array
To add an element at the beginning of an array, we can use the unshift
method to do this.
For instance, we can write:
array.unshift('foo');
Now we have 'foo'
as the first entry of array
.
The Best way to Convert a Number to a String
There are a few ways to convert a number to a string.
We can write:
String(n)
n.toString()
“”+n
n+””
According to tests like this one http://jsben.ch/#/ghQYR, toString
is the fastest in Firefox.
It can be done 1 million times in 0.1 seconds.
However in Chrome num + ''
is faster according to http://jsben.ch/#/ghQYR
Split Array into Chunks
We can split an array into chunks by using a for loop:
const chunk = 10;
let tempArray = [];
for (let i = 0; i < array.length; i += chunk) {
tempArray = array.slice(i, i + chunk);
}
We loop through the array, then we get the chunks by incrementing i
with chunk
.
Then in the loop body, we call slice
to get the chunk of the array.
The slice is from index i
to i + chunk — 1
.
Convert Array to Object
We can use Object.assign
to convert an object to an array.
For instance, we can write:
Object.assign({}, ['a', 'b', 'c']);
We put the array entries into the empty object.
We can also use the spread operator:
{ ...['a', 'b', 'c'] }
Difference Between npx and npm
npx lets us run a package directly from the NPM repository without installing it.
It’s useful for packages that we don’t use often.
npx always runs the latest version of a package.
npm is used for managing packages, including installation.
We can use npm to install package with npm install
.
Or we can use it to run scripts with npm run
.
What do Multiple Arrow Functions Mean?
Multiple arrow functions means that it’s nested.
For instance, if we have:
handleChange = field => e => {
e.preventDefault();
// ...
}
Then we have a function that takes the field
parameter, then it returns a function with the e
parameter.
This is also known as a curried function.
We return a function that applies one parameter at a time instead of applying them all at once.
This is handy for sharing functions that have some arguments applied to it.
If we write:
const add = x => y => x + y
then we can apply one argument to it by writing:
const add2 = add(2)
Then we can call that by writing:
add2(3)
and get 5 or:
add2(6)
and get 8 for example.
Filter Object Array Based on Attributes
We can use the filter
method to filter an object array based on attributes.
For instance, we can write:
const homesIWant = homes.filter((el) => {
return el.price <= 2000 &&
el.sqft >= 500 &&
el.numBeds >= 2 &&
el.numBaths >= 2.5;
});
We return an array that has all the homes
entries with price
less than or equal to 2000, sqft
bigger than or equal to 500, numBeds
bigger than or equal to 2, and numBaths
bigger than 2.5.
Conclusion
We can iterate over arrays with the for-of loop.
We can get chunks of an array by incrementing by the chunk length.
filter
lets us filter arrays by whatever condition we want.
npx and npm are different.