Categories
JavaScript Answers

How to Get the Name of a JavaScript Object’s Type?

Getting the name of the constructor that an object is created from is something that we’ve to sometimes.

In this article, we’ll look at how to get the name of the constructor that the JavaScript object is created from.

The constructor Property

We can use the constructor property of an object to get the constructor that it’s created from.

For instance, we can write:

const arr = [1, 2, 3];
console.log(arr.constructor === Array);

Then the console log logs true since the arr is created with the Array constructor.

This can also be used with constructors we create ourselves:

class A {}
const a = new A()
console.log(a.constructor === A);

The console log will also log true .

Inheritance

If we create an object from a subclass, then we can check if an object created from the current subclass.

For instance, we can write:

class A {}
class B extends A {}
const b = new B()
console.log(b.constructor === B);

Then the console log also logs true since b is created from the B constructor.

constructor has the name property to get the constructor name as a string.

For instance, we can write:

class A {}
const a = new A()
console.log(a.constructor.name === 'A');

to compare against the name of the constructor.

The instanceof Operator

The instanceof operator also lets us check if an object is created from a constructor.

For instance, we can write:

const arr = [1, 2, 3];
console.log(arr instanceof Array);

Then the console log should log true since arr is an array.

However, the Array.isArray is more reliable for checking if a variable is an array since it works across all frames.

Also, we can write:

class A {}
const a = new A()
console.log(a instanceof A);

to check if a is an instance of A .

instanceof also works with subclasses.

So we can write:

class A {}
class B extends A {}
const b = new B()
console.log(b instanceof B);

And it’ll log true .

Conclusion

We can use the instanceof operator and the constructor property to check if an object is created from the given constructor.

Categories
JavaScript Answers

How to Check if an Element is Visible After Scrolling?

Checking if an element is visible after scrolling is something that we may have to do sometimes.

In this article, we’ll look at how to check if an element is visible after scrolling with JavaScript.

Create Our Own Function

We can create our own function to check if an element is visible after scrolling.

For instance, we can write the following HTML:

<div>
</div>

And the following JavaScript:

const div = document.querySelector('div')
for (let i = 1; i <= 100; i++) {
  const p = document.createElement('p')
  p.id = `el-${i}`
  p.textContent = 'hello'
  div.appendChild(p)
}

const isScrolledIntoView = (el) => {
  const {
    top,
    bottom
  } = el.getBoundingClientRect();
  const elemTop = top;
  const elemBottom = bottom;
  const isVisible = (elemTop >= 0) && (elemBottom <= window.innerHeight);
  return isVisible;
}

const el = document.querySelector('#el-50')
document.addEventListener('scroll', (e) => {
  console.log(isScrolledIntoView(el))
})

We get the div element with querySelector .

Then we have a for loop to insert p elements into the div.

We set the id property so that we can get the inserted element later.

Next, we create the isScrolledIntoView function to check if the element is in the browser screen.

To do this, we call el.getBoundingClientRect to get the top and bottom coordinates of the element.

These are top and bottom y coordinates respectively.

Then we return the isVisible variable, which we create by checking if top is bigger than or equal to 0 and the bottom is less than or equal to the innerHeight of window.

If both conditions are true, then we know the element is in the window.

Then we get the element we want to watch with another querySelector call.

And finally, we call addEventListener to add the scroll event to the document and call the isScrolledIntoView function with the el element to see when el is in the browser window.

As we scroll down, we should see the logged value goes from false to true and back to false .

Using the IntersectionObserver API

The IntersectionObserver API is an API available in recent browsers to let us check whether an element is visible on the screen.

For instance, we can write:

const div = document.querySelector('div')
for (let i = 1; i <= 100; i++) {
  const p = document.createElement('p')
  p.id = `el-${i}`
  p.textContent = 'hello'
  div.appendChild(p)
}

const onIntersection = (entries, opts) => {
  entries.forEach(entry => {
    const visible = entry.intersectionRatio >= opts.thresholds[0]
    console.log(entry.intersectionRatio.toFixed(2), visible)
  })
}

const intersectionObserverOptions = {
  root: null,
  threshold: .5
}

const observer = new IntersectionObserver(onIntersection, intersectionObserverOptions)
const target = document.querySelector('#el-50')
observer.observe(target)

The first querySelector call and the for loop is the same as before.

Then we define the onIntersection function that takes the entries and opts parameters.

entries is the elements we’re watching for visibility with.

And opts is an options object that has the thresholds property to get the threshold of intersection with the screen.

In the forEach callback, we have the the visible variable, which we create by comparing the intersectionRatio of entry with the first threasholds value in opts ,

We know it’s visible if the intersectionRatio is bigger than the threshold.

Then we log the visible value and the intersectionRatio .

Next, we have the interswedtiobnObserverOptions to set the threshold of the intersection in order for it to be visible.

Then we pass them both to the IntersectionObserver constructor.

Then we call observer.observe with the target element to watch whether it’s visible or not.

Conclusion

We can compare the position of the element or use the IntersectionObserver API to check whether an element is visible or not after scrolling.

Categories
JavaScript Answers

How to Use JavaScript Array Map Method with Objects Instead of Arrays?

Sometimes, we want to map object property values of an object to new values instead of mapping array values.

In this article, we’ll look at how to use JavaScript array’s map method with object instead of arrays.

Object.keys

The object.keys method returns an array of a JavaScript object’s string keys.

Therefore, we can loop through the keys to map the property values to their new values.

For instance, we can write:

const obj = {
  a: 1,
  b: 2,
  c: 3
};
for (const key of Object.keys(obj)) {
  obj[key] *= 2
}
console.log(obj)

We have the obj object that has 3 properties in it.

Then we use Object.keys with obj to return the keys.

And then we use the for-of loop to loop through the keys.

Then we can use that to do what we want.

In this example, we multiple each property value by 2.

Therefore, obj is now:

{a: 2, b: 4, c: 6}

Object.keys and reduce

We can also combine the Object.keys method with the reduce method to map the values of properties if an object to new values.

For instance, we can write:

const obj = {
  a: 1,
  b: 2,
  c: 3
};

const newObj = Object.keys(obj).reduce((result, key) => {
  result[key] = obj[key] * 2
  return result
}, {})
console.log(newObj)

We call reduce on the string keys array returned by Object.keys .

The reduce callback has the result object which is the object that we have so far.

key has the string key value.

Then we get result[key] with the value we want.

We get the obj[key] value and multiply it by 2.

Then we return the result value.

The 2nd argument is set to an object so that the initial value of result is an object.

This way, we can put property values in them.

Therefore, newObj has the same value as the previous example.

Object.fromEntries and Object.entries

We can use the Object.fromEntries method to create an object from an array of arrays of key-value pairs.

And we can use Object.entries to return an array of arrays of key-value pairs of an object.

For example, we can write:

const obj = {
  a: 1,
  b: 2,
  c: 3
};

const newObj = Object.fromEntries(
  Object.entries(obj).map(
    ([key, value]) => ([key, value * 2])
  )
)
console.log(newObj)

We call Object.entries with obj to get the key-value pairs in an array.

Then we call map with a callback that destructures the key-value pairs.

And we return an array of key-value pairs.

We changed the value by multiplying it by 2.

Then we use Object.fromEntries to create an object from the new array of key-value pairs.

Therefore newObj is:

{a: 2, b: 4, c: 6}

as we have before.

Conclusion

We can map object properties to new values by using some handy object methods that are available in JavaScript’s standard library.

Categories
JavaScript Answers

How to Merge or Flatten an Array of JavaScript Arrays?

Sometimes, we want to merge or flatten an array of JavaScript arrays.

In this article, we’ll look at how to merge or flatten an array of JavaScript arrays.

Array.prototype.concat

The concat method lets us add the items from arrays passed in as arguments into the array it’s called on.

For instance, we can write:

const arrays = [
  ["1"],
  ["2"],
  ["3"],
  ["4"],
  ["5"],
  ["6"],
];
const merged = [].concat(...arrays);
console.log(merged);

We spread the entries in arrays to the concat method.

The all the entries from the arrays in arrays will be added to the empty array it’s called on and returned.

Therefore, we get [“1”, “2”, “3”, “4”, “5”, “6”] as the result of merged .

Array.prototype.flat

ES2019 comes with the flat method that lets us flatten an array with any level we want.

For instance, we can write:

const arrays = [
  ["1"],
  ["2"],
  ["3"],
  ["4"],
  ["5"],
  ["6"],
];
const merged = arrays.flat(1);
console.log(merged);

Then we get the same result as before.

We pass in 1 to flat to flatten the array one level.

If we don’t pass in an argument, then it’ll flatten recursively until there’re no more arrays left to flatten.

Write Our Own Function

Also, we can write our own function to flatten an array recursively.

For instance, we can write:

const arrays = [["1"], ["2"], ["3"], ["4"], ["5"], ["6"]];

const flatten = (arr) => {
  return arr.reduce((flat, toFlatten) => {
    if (Array.isArray(toFlatten)) {
      return flat.concat(...flatten(toFlatten));
    }
    return flat.concat(toFlatten);
  }, []);
};
const merged = flatten(arrays);
console.log(merged);

to create the flatten function.

We check if toFlatten is an array in the callback of reduce .

reduce lets us combine items from multiple arrays into one array.

If it is, then we return the return value flat.concat called with the flatten(toFlatten) spread into concat as arguments.

Otherwise, we just return the result of flat.concat(toFlatten) since toFlatten isn’t an array.

This means we can put it straight into the flat array.

The 2nd argument of reduce is the initial return value of reduce before anything is put into it.

Conclusion

The easiest way to flatten or merge nested arrays is to use the flat method that comes with arrays.

We can also use the concat method to flatten one level of a nested array.

Another choice is to create our own function to flatten an array.

Categories
JavaScript Answers

How to Add Days to JavaScript Date?

Adding days to a JavaScript date is an operation that sometimes we have to do.

In this article, we’ll look at how to add days to a JavaScript date object.

The setDate Method

We can use the setDate method to add days to a date easily.

For instance, we can write:

const addDays = (date, days) => {
  const result = new Date(date);
  result.setDate(result.getDate() + days);
  return result;
}

const result = addDays(new Date(2021, 1, 1), 2)
console.log(result)

We have the addDays function to add days.

In the function, we pass in the date to the Date constructor.

Then we call setDate with the getDate method to get the day of the month.

And then we add the days to it.

And finally, we return the result , which has the new date with the days added to it.

Therefore, when we call it in the 2nd last line, we get:

'Wed Feb 03 2021 00:00:00 GMT-0800 (Pacific Standard Time)'

as the value of result .

setDate will compute the new date value no matter what number we pass into it.

For instance, if we write:

const addDays = (date, days) => {
  const result = new Date(date);
  result.setDate(result.getDate() + days);
  return result;
}

const result = addDays(new Date(2021, 1, 1), 100)
console.log(result)

Then result is 'Wed May 12 2021 00:00:00 GMT-0700 (Pacific Daylight Time)’ , which is still what we expect.

The setTime Method

Likewise, we can also call the setTime to set the timestamp of the date instead of days.

This lets us add a time more precisely.

For instance, we can write:

const date = new Date(2021, 1, 1)
const duration = 2;
date.setTime(date.getTime() + (duration * 24 * 60 * 60 * 1000));

date.getTime returns the timestamp in milliseconds.

Then we add the duration in days, converted to milliseconds by multiplying it by 24 * 60 * 60 * 1000 .

Then we get 'Wed Feb 03 2021 00:00:00 GMT-0800 (Pacific Standard Time)’ as the new value of date .

Conclusion

We can use native JavaScript date methods to add days to a JavaScript date.