Categories
JavaScript Answers

How to check in JavaScript if a value exists at a certain array index?

To check in JavaScript if a value exists at a certain array index, we use check if the array item at the index is undefined or not.

For instance, we write

if (arrayName[index]) {
  //...
}

to get the item in arrayName at index.

If it’s not undefined, then the value exists.

Categories
JavaScript Answers

How to create an array with same element repeated multiple times with JavaScript?

To create an array with same element repeated multiple times with JavaScript, we call the fill method.

For instance, we write

const arr = Array(15).fill(2);

to create an empty array with 15 slots with Array.

And then we call fill to fill all the slots with 2’s.

Categories
JavaScript Answers

How to convert an HTMLCollection to an array with JavaScript?

To convert an HTMLCollection to an array with JavaScript, we use the spread operator.

For instance, we write

const array = [...htmlCollection];

to use the spread operator to spread the items in htmlCollection to an array.

Categories
JavaScript Answers

How to remove last item from array with JavaScript?

To remove last item from array with JavaScript, we use the pop method.

For instance, we write

const fruit = ["apple", "orange", "banana", "tomato"];
const popped = fruit.pop();

to call fruit.pop to remove the last element in fruit and return it.

Categories
JavaScript Answers

How to remove objects from a JavaScript associative array?

To remove objects from a JavaScript associative array, we use the delete operator.

For instance, we write

delete myObj.someProperty;

to remove the myObj.someProperty property from the myObj object.