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.

Categories
JavaScript Answers

How to fix Node.js socket.io.js not found?

To fix Node.js socket.io.js not found, we expose the folder with socket.io.js as the static folder.

For instance, we write

app.use(express.static(path.join(__dirname, "/")));

to call express.static to expose the root folder as the static folder.

And then we can put socket.io.js there and use it in a script tag like

<script src="//socket.io.js"></script>
Categories
JavaScript Answers

How to map over an object and change one properties value using JavaScript?

To map over an object and change one properties value using JavaScript, we use the spread operator.

For instance, we write

const original = { a: 1, b: 2 };
const copy = { ...original, c: 3 };

to spread the properties of the original object into the copy object.

And we add the c property to copy to set ites c property to 3.

Categories
JavaScript Answers

How to fix not being able to get CSS file with Node Express?

To fix not being able to get CSS file with Node Express, we expose the folder with the CSS file as a static folder.

Then we write

app.use(express.static(path.join(__dirname, "public")));

to call express.static with the path to expose as the static folder.

Therefore, when we put our CSS file in the public folder, we can get it by using the file name as the URL.