javascript

Element.scrollIntoView()

scrollIntoView() is a function that exists on Document Elements. It provides the ability to scroll to the provided element’s parent container.

let elem = document.getElementById('title');

elem.scrollIntoView();

It takes in a few optional parameters that you can use to configure the scroll alignment and transition.

elem.scrollIntoView({ behavior: 'smooth' });

MDN Reference

Array.prototype.unshift()

The unshift method on JavaScript arrays lets you append items to the beginning of the list.

Let’s say you are creating a dropdown list of items but the first item in the list should be a placeholder value to show the user before they select an actual value.

const renderOptions = () => {
  const dropdownOptions = [
    { label: 'Apple', value: 'apple' },
    { label: 'Banana', value: 'banana' },
    { label: 'Cherry', value: 'cherry' }
  ];

  dropdownOptions.unshift({ label: 'Select a fruit', value: '' });

  return dropdownOptions;
}

This renders the following array:

[
  { label: 'Select a fruit', value: '' },
  { label: 'Apple', value: 'apple' },
  { label: 'Banana', value: 'banana' },
  { label: 'Cherry', value: 'cherry' },
]

This is a short way to add items to the beginning of an array. However, I don’t prefer to use this method because the method unshift doesn’t immediately tell me what’s happening if I have never come across it before. I prefer to write code that is more readable. For example:

const renderOptions = () => {
  const dropdownOptions = [
    { label: 'Apple', value: 'apple' },
    { label: 'Banana', value: 'banana' },
    { label: 'Cherry', value: 'cherry' }
  ];

  const placeholderOption = { label: 'Select a fruit', value: '' };

  return [placeholderOption, ...dropdownOptions];
}

Using the spread operator I can easily return an array that puts the placeholder option first followed by the rest of the list. The code is much easier to reason about now.

Zero Delays

const zeroDelayExample = () => {
  console.log('This will come first');
  
  setTimeout(() => {
    console.log('Zero delay will come third');
  }, 0);

  console.log('This will come second');
}  

In the above example, a setTimeout doesn’t function the way it normally does. That is, it won’t execute after 0 milliseconds (or immediately).

The 0 parameter tells setTimeout to only execute after all of the messages in the event loop’s queue are finished.

In this case when zeroDelayExample gets called, the first console.log will be called, the setTimeout will wait for all other events to finish, then the third console.log will be called. Finally, the setTimeout callback gets fired.