0

So I got these two functions with an if statement which does the same thing.

Which is to check if the value of the input field is empty. if(newTask.value === '')

var newTask = document.getElementById("new-task");

newTask.addEventListener("keyup", function(event) {
    event.preventDefault();
    if(event.keyCode == 13){
        if(newTask.value === ''){
            alert('Fill in a task.');
        } else{
            addTask(newTask.value);
        }
    }
});

newTaskBtn.onclick = function() {
    if(newTask.value === ''){
        alert('Fill in a task.');
    } else{
        addTask(newTask.value);
    }
};

What is the recommended way to make my code more efficient?

  • Writing another function which does only the checking.
  • Writing a function within a function?

Any other ideas are most welcome offcourse.

1
  • You could move the check for an empty value inside the "addTask" function Commented May 18, 2017 at 8:54

2 Answers 2

1

You can write a function that does the task checking. For example:

var newTask = document.getElementById("new-task");
function checkTask(taskValue) {
 if(taskValue === ''){
    alert('Fill in a task.');
  } else{
    addTask(taskValue);
  }
}
newTask.addEventListener("keyup", function(event) {
    event.preventDefault();
    if(event.keyCode == 13){
       checkTask(newTask.value);
    }
});

newTaskBtn.onclick = function() {
   checkTask(newTask.value);
};
Sign up to request clarification or add additional context in comments.

Comments

0

Your code is fine. There is some duplication, but both functions have different preconditions because the keyup has to check the keycode. Adding another level of function calls will make the code less readable imho. I'd just change the structure to use early returns, like this:

var newTask = document.getElementById("new-task");

newTask.addEventListener("keyup", function(event) {
    event.preventDefault();
    if (event.keyCode !== 13) {
        return;
    }
    if (newTask.value === '') {
        alert('Fill in a task.');
        return;
    }
    addTask(newTask.value);
});

newTaskBtn.onclick = function() {
    if (newTask.value === '') {
        alert('Fill in a task.');
        return;
    }
    addTask(newTask.value);
};

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.