Categories
JavaScript Answers

How to fix the ESLint Warning “Function declared in a loop contains unsafe references to variable(s)…no-loop-func” with JavaScript?

To fix the ESLint Warning "Function declared in a loop contains unsafe references to variable(s)…no-loop-func" with JavaScript, we shoyuld replace loops with forEach.

For instance, we write

const showHelp = (help) => {
  document.getElementById("help").textContent = help;
};

const setupHelp = () => {
  const helpText = [
    { id: "email", help: "Your e-mail address" },
    { id: "name", help: "Your full name" },
    { id: "age", help: "Your age (you must be over 16)" },
  ];

  helpText.forEach((text) => {
    document.getElementById(text.id).onfocus = () => {
      showHelp(text.help);
    };
  });
};

to call helpText.foreach with a callback to set the document.getElementById(text.id).onfocus to a function that calls showHelp.

Using forEach confines toe scope of the functions within the block so we won’t get unexpect results when the onfocus callback runs.

Categories
JavaScript Answers

How to Insert a Row in an HTML Table Body in JavaScript?

Sometimes, we want to insert a row in an HTML table body with JavaScript.

In this article, we’ll look at how to insert a row in an HTML table body with JavaScript.

Call the insertRow and insertCell Methods

JavaScript DOM API has the insertRow method built into the tbody element.

And it also has the insertCell method built into the tr element.

insertRow lets us insert a new table row.

And insertCell method lets us insert a new cell into a table row.

For instance, if we have the following HTML:

<table id="myTable">
  <thead>
    <tr>
      <th>My Header</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>aaaaa</td>
    </tr>
  </tbody>
  <tfoot>
    <tr>
      <td>My footer</td>
    </tr>
  </tfoot>
</table>

We can write:

const tbodyRef = document.getElementById('myTable').getElementsByTagName('tbody')[0];

const newRow = tbodyRef.insertRow();
const newCell = newRow.insertCell();
const newText = document.createTextNode('new row');
newCell.appendChild(newText);

We have a table, with the tbody element inside.

Then to get the tbody , we call getElementId to get the table.

Then we call getElementsByTagName to get the tbody element.

Next, we call insertRow on the tbody element to create a new tr.

And then we call insertRow on the newly created tr .

Next, we call document.createTextNode to create a new text node for the table cell content.

And then we call newCell.appendChild to append the newText text node.

Now we should see ‘new row’ before the footer.

Conclusion

We can use methods built into tbody and tr DOM objects to insert new table rows and cells with JavaScript.

Categories
JavaScript Answers

How to Remove a Leading Comma from a JavaScript String?

Sometimes, we want to remove a leading comma from a JavaScript string.

In this article, we’ll look at how to remove a leading comma from a JavaScript string.

Using the String.prototype.substring Method

We can use the JavaScript string substring method to get the part of a string.

Therefore, we can use it to return a string without the leading comma.

For instance, we can write:

const myOriginalString = ",'first string','more','even more'";
const newString = myOriginalString.substring(1);
console.log(newString)

We call substring with 1 to return a string the part of myOriginalString from index 1 to the end.

Therefore, newString is "’first string’,’more’,’even more’” .

Using the String.prototype.split Method

We can use the JavaScript string split method to split a string by a separator string.

For instance, we can write:

const myOriginalString = ",'first string','more','even more'";
const [_, ...rest] = myOriginalString.split(',');
const newString = rest.join(',')
console.log(newString)

We call split with ',' to split myOriginalString by the comma.

Then we use the rest operator to get a string array with anything but the first comma.

And then we call join with ',' to join the strings in rest with the comma.

And so newString has the same value as before.

Using the String.prototype.replace Method

Another way to remove the leading commas from a string is to use the JavaScript string’s replace method.

For example, we can write:

const myOriginalString = ",'first string','more','even more'";
const newString = myOriginalString.replace(/^,/, '');
console.log(newString)

We call replace with /^,/ to replace the leading comma with an empty string.

And so newString is the same as before.

Conclusion

We can use various string methods to get rid of the leading comma from a string.

Categories
JavaScript Answers

How to Clear an HTML File Input with JavaScript?

Sometimes, we want to let users clear an HTML file input with JavaScript.

In this article, we’ll look at how to clear an HTML file input with JavaScript.

Setting the value Property of the File Input to an Empty String

We can set the value property of the file input to an empty string.

For instance, if we have the following HTML code:

<input type='file'>  
<button>  
  clear  
</button>

Then we can write:

const input = document.querySelector('input')  
const button = document.querySelector('button')  
button.addEventListener('click', () => {  
  input.value = '';  
})

to clear the file input when we click on the clear button.

We get the input and the button with document.querySelector .

Then we call addEventListener on the button with the 'click' string as the first argument to listen for clicks on the button.

In the event handler, we just set input.value to an empty string.

Then when we select a file for the input and click clear, we see that the selected file is gone.

We can also set value to null to do the same thing.

Conclusion

We can clear the file input with JavaScript by setting the value property of the file input to an empty string or null .

Categories
JavaScript Answers

How to Convert a JavaScript Array to a Set?

Sometimes, we want to convert a JavaScript array into a set.

In this article, we’ll look at how to convert a JavaScript array to a set.

Create a Set with the JavaScript Set Constructor

We can use the JavaScript Set constructor to create a JavaScript set from an array.

For instance, we can write:

const array = [{
    name: "malcom",
    dogType: "golden retriever"
  },
  {
    name: "peabody",
    dogType: "bulldog"
  },
  {
    name: "pablo",
    dogType: "chihuahua"
  }
];
const namesSet = new Set(array.map(d => d.name));
console.log(namesSet)

We have an array array with an array of objects.

We want to create a set with the name value from each object.

To do this, we call array.map with a callback to return the name property of each object.

We then pass the returned names string array into the Set constructor to create the set.

Therefore namesSet is a set with “malcom”, “peabody”, and “pablo” in it.

Passing the array into the Set constructor will remove the duplicate values if there are any in the set.

Conclusion

We can use the JavaScript Set constructor to create a set from an array.