Categories
JavaScript Answers

How to check if a key exists in a JavaScript object?

To check if a key exists in a JavaScript object, we use the hasOwnProperty method.

For instance, we write

const obj = { key: undefined };
console.log(obj.hasOwnProperty("key"));

to call obj.hasOwnProperty to check if the 'key' property is in the obj object itself.

Categories
JavaScript Answers

How to insert an item into an array at a specific index with JavaScript?

To insert an item into an array at a specific index with JavaScript, we can assign the value directly.

For instance, we write

const arr = [];
arr[0] = "Jane";
arr[1] = "Alex";
arr[2] = "Bob";

to set the entry at index 0 to 'Jane'.

We set the entry at index 1 to 'Alex'.

And we set the entry at index 2 to 'Bob'.

Categories
JavaScript Answers

How to check if an array includes a value in JavaScript?

To check if an array includes a value in JavaScript, we use the includes method.

For instance, we write

console.log(["joe", "jane", "mary"].includes("jane"));

to call includes to check if 'jane' is in the ["joe", "jane", "mary"] array.

Since 'jane' is in the array, true is returned.

Categories
JavaScript Answers

How to For-each over an array in JavaScript?

To For-each over an array in JavaScript, we use a for-of loop.

For instance, we write

const a = ["a", "b", "c"];
for (const element of a) {
  console.log(element);
}

to loop through the a array with the for-of loop.

We get the element being looped through from element.

Categories
JavaScript Answers

How to remove a specific item from an array with JavaScript?

To remove a specific item from an array with JavaScript, we call the array splice method.

For instance, we write

const array = [2, 5, 9];
const index = array.indexOf(5);
if (index > -1) {
  array.splice(index, 1);
}

console.log(array);

to get the index of 5 in array with indexOf.

Then we call splice with index and 1 to remove 5 from the array.