Categories
JavaScript Answers

How to Create an Array of Functions with JavaScript?

We can put functions in an array as we do with any other values.

For instance, we can write:

const firstFunction = () => {
  //...
}

const secondFunction = () => {
  //...
}

const thirdFunction = () => {
  //...
}

const forthFunction = () => {
  //...
}

const arr = [
  firstFunction,
  secondFunction,
  thirdFunction,
  forthFunction
]

arr[0]()
arr[1]()
arr[2]()
arr[3]()

We have 4 functions, firstFunction , secondFunction , thirdFunction , and forthFunction .

And then we put them all in the arr array, separating them with commas.

Finally, we can call them by getting the function by their index from arr and call them as we do with any other function.

Categories
JavaScript Answers

How to Capitalize the First Letter of Each Word in a String Using JavaScript?

We can use the string toUpperCase and substring methods to convert each word in a string to have their first letter in uppercase.

For instance, we can write:

const titleCase = (str) => {
  const splitStr = str.toLowerCase().split(' ');
  for (const [i, str] of splitStr.entries()) {
    splitStr[i] = str[0].toUpperCase() + str.substring(1);
  }
  return splitStr.join(' ');
}

console.log(titleCase("I'm a little tea pot"));

We create the titleCase function with the str string parameter.

We split the string by the space character with the split method.

Then we loop through each string in the split string array with the for-of loop.

We get the index i and string str from each entry by destructuring the entries returned by entries .

After that, we get the first character of str and convert that to uppercase. Then we concatenate that with the rest of the str string that we get from substring .

Finally, we join the string back together with a space character in between each word with join .

Therefore, the console log should log 'I’m A Little Tea Pot’ .

Categories
JavaScript Answers

How to Get the Element at the Specified Position with JavaScript?

We can use the document.elementFromPoint method to get the element at the given x-y coordinates.

Each coordinates is in pixels.

For instance, if we have the following div element:

<div>  
  hello world  
</div>

Then we can use the document.elementFromPoint method to get the div by writing:

const el = document.elementFromPoint(10, 10);  
console.log(el)

The coordinates are relative to the top left corner.

The first argument is the x coordinate and the 2nd argument is the y coordinate.

So the first argument is 10 pixels to the right of the top left corner.

And the 2nd argument is 10 pixels below the top left corner.

Categories
JavaScript Answers

How to Define a JavaScript Array with Conditional Elements?

We can use the spread operator to conditionally spread arrays into another array.

For instance, we can write:

const items = [
  'foo',
  ...true ? ['bar'] : [],
  ...false ? ['falsy'] : [],
]

console.log(items)

Then items is [“foo”, “bar”] since we have a ternary express that has false as the value of the conditional part of the ternary expression.

If it’s true , then the left array is spread into items .

Otherwise, an empty array is spread into items .

Call Array.prototype.push Conditionally

Another way to conditionally add items conditionally to a JavaScript array is to use the push method.

For instance, we can write:

const items = [
  'foo',
]

if (true) {
  items.push("bar");
}

if (false) {
  items.push("false");
}

console.log(items)

Then 'bar' is appended to items but 'false' isn’t .

This is because the first conditionally has true as the conditional and the 2nd one has false as the condition.

Therefore items is [“foo”, “bar”] again.

Categories
JavaScript Answers

How to Run JavaScript Code When an Element Loses Focus?

Listen to the blur Event

We can listen to the blur event to run code when an element loses focus.

For instance, if we have the following input element:

<input type="text" name="name" />

Then we can watch when the blur event is triggered on the input by writing:

const input = document.querySelector('input')  
input.addEventListener('blur', () => {  
  console.log('focus lost')  
})

We get the input element with document.querySelector .

Then we call addEventListener on it with 'blur' as the first argument.

The 2nd argument is a callback that runs when the blur event is triggered.

When we move our cursor away from the input element, we’ll see the 'focus lost' string logged.