0

Are there any benefits of combining the below functions?

window.onload = function() {
  if (localStorage.getItem("txt")) {
    textarea.value = localStorage.getItem("txt");
    changeDocTitle(localStorage.getItem("filename"));
    isModified = true;
  } else {
    changeDocTitle(untitled);
  }
};

function newNote() {
  if (!isModified || dontSave()) {
    textarea.value = "";
    changeDocTitle(untitled);
  }
  textarea.focus();
}

After combining it will look like this:

window.onload = function() {
  if (localStorage.getItem("txt")) {
    newNote(localStorage.getItem("txt"), localStorage.getItem("filename"));
  } else {
    newNote();
  }
};

function newNote(txt, filename) {
  if (!isModified || dontSave()) {
    textarea.value = txt || "";
    changeDocTitle(filename || untitled);
    if (textarea.value) {
      isModified = true;
    }
  }
  textarea.focus();
}
  • I'll call the newNote() function with keyboard shortcuts too..

What is the difference between the two, and is there any reason to prefer one over the other?

2 Answers 2

2

The second one.

If the scope of newNote is limited to the onload function, then there is no reason to dirty the global scope.


EDIT

Frankly, it doesn't matter much. If you binding the keyboard event, then the function will remain in scope throughout the document scope. So either would be good.

Besides, questions in SO, are more problem oriented. Try https://codereview.stackexchange.com/, instead.

Sign up to request clarification or add additional context in comments.

Comments

1

This may be primarily opinion-based, but I would go with the second one.
Reasons:

Increased Readability and Easier Maintainance

It's obviously easier to read and maintain one function instead of two, and you keep your code in one place altogether.

No waste of resources

You create the variables you need in your function and they go away when you are done with it.

Warning, though.

You should know that there are certain things to avoid. For example, if your newNote function will require more and more arguments over time, you may consider changing the scope, and possibly maintain it out of the function to avoid having a function with (let's say) a dozen arguments, because you just lose the benefits listed above.

P.S.: I think the second code you described has some errors. Unless you just wrote it like that to explain what you intend to do. (I'm talking about textarea.value = txt || "";)

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.