I have a piece of code, that is just vanilla javascript. When I use arrow functions I get this error:
Uncaught ReferenceError: loadEventListeners is not defined
When I use regular function, syntax, it works fine.
Here is my code:
const form = document.querySelector('#task-form');
const taskList = document.querySelector('.collection');
const clearBtn = document.querySelector('.clear-tasks');
const filter = document.querySelector('#filter');
const taskInput = document.querySelector('#task');
// Load all event listeners
loadEventListeners();
// Load all event listeners
const loadEventListeners = () => {
// Add task event
form.addEventListener('submit', addTask);
}
// Add Task
const addTask = (e) => {
if(taskInput.value === '') {
alert('Add a task');
}
// Create li element
const li = document.createElement('li');
// Add class
li.className = 'collection-item';
// Create text node and append to li
li.appendChild(document.createTextNode(taskInput.value));
// Create new link element
const link = document.createElement('a');
// Add class
link.className = 'delete-item secondary-content';
// Add icon html
link.innerHTML = '<i class="fa fa-remove"></i>';
// Append the link to li
li.appendChild(link);
// Append li to ul
taskList.appendChild(li);
// Clear input
taskInput.value = '';
e.preventDefault();
}
My question is this. Do I need to do something that enables arrow functions, in my code? Maybe I need to setup Webpack or Parcel for this? I do not know why this is. Just replace the const <functionName> = () => {}
with function <functionName>() {}
and it works. Would really like a more thorough explanation why this is happening, if it is possible.
Thanks for your time..