-1

I'm starting to study javascript, I implemented this little snippet of code. I spent a long time trying to run the browser until I realized that the problem was calling functions with and without parentheses, note the commented lines.

var buttonElement = document.querySelector('#app button');
var tarefaDigitada = document.querySelector('#app input');
var listElement = document.querySelector('#app ul');

var todos = ['Cofee', 'Beer', 'Water'];

function renderTodos() {

    listElement.innerHTML = '';

    for (todo of todos) {
        var todoElement = document.createElement('li');
        var todoText = document.createTextNode(todo); 

        todoElement.appendChild(todoText);
        listElement.appendChild(todoElement);

    }
}

function addTodo() {
    var text = tarefaDigitada.value;
    console.log(tarefaDigitada.value);
    todos.push(text);
    tarefaDigitada.value = '';
    renderTodos();//No parentheses doesn't work

}
renderTodos();
buttonElement.onclick = addTodo;//With parentheses does not work

Even without parameters is necessary to put parentheses? Why on the call to onclick I can not put?

Manzini
  • 117
  • 1
  • 10
  • 1
    Any decent tutorial should explain this. If you read one that did not, find another, because the one you read was either too compact/short, or bad. – ASDFGerte Dec 01 '19 at 18:02
  • 1
    Parenthesis execute a function. `renderTodos()` causes `renderTodos` to run right then. `buttonElement.onclick = addTodo` is passing a reference to a function. It will be executed later (like when a user clicks). In this case you *don't* want it to run right now. – Mark Dec 01 '19 at 18:03

2 Answers2

1

When you want to call a function in that line itself you add parenthesis whereas in the other case you are telling JS to call the function internally whenever the button is clicked not right then.

kooskoos
  • 4,622
  • 1
  • 12
  • 29
1

There must be dupes of this question around SO. When you do onclick = addTodo() you're calling the function and setting onclick to whatever the function returns. You don't want that; you want to set onclick to the function itself, hence no parentheses.

Mark Reed
  • 91,912
  • 16
  • 138
  • 175