JavaScript's window.location vs form.submit()

Viewed 29

In JavaScript, what is the difference between window.location and form.submit() (GET with no parameters)?

I have seen people using form.submit() (GET method with no parameters) over window.location for just a simple redirection of page. Why? and what are the benefits of that? Is that some kind of hack to achieve something?

AFAIK, form.submit() leaves a trailing ? behind the URL even where there is no parameters and that bugs me a little.

2 Answers

You should always prefer using window.location. Unless you want to need parameters, using form.submit() is completely illogical, as it has more overhead. If one just thinks about it, form.submit() is a function call, while window.location is just changing a variable. Although it is a microscopic performance difference, calling the function will be less efficient than assigning a variable.

If the form doesn't have any parameters, assigning to window.location is the equivalent and would be the usual way to do it.

But most forms do have parameters. form.submit() is a general way to submit the form and get the parameters sent automatically, rather than having to construct the URL in your own code. It will also send a POST request if that's the form's method. So it's useful in general purpose libraries.

Related