Arindam Das
Arindam Das

Reputation: 699

What is the difference between function calls in javascript?

I was asked this question in an interview a JavaScript function like this :

function a(){
 /// ----  Some Code ---
}

Now in a html button click

<button click= "a()">
<button click= "return a()">
<button click= "javascript a()">

What are the difference between these 3 calls?

Upvotes: 1

Views: 134

Answers (3)

Guffa
Guffa

Reputation: 700152

The difference between the first and the second, is that the second passes along the return value from the function and makes it the return value of the event handler. That makes it possible for the function to return false to stop the default action of the event. For a button that doesn't make a difference, as there is no default action, but if it was a link it would be useful. Example:

function handleClick() {
  // do something here
  return false;
}

<a href="fallback.html" onclick="return handleClick();">click me</a>

The script will keep the link from navigating to fallback.html.

The third code is incorrect in two ways. As it stands, it causes a syntax error. The example should probably be:

<button onclick="javascript:a()">

Sometimes people put javascript: (not javascript) first in an event handler out of habit, or because they think that it should be there. It comes from using Javascript in an URL in a link:

<a href="javascript:alert('hello')">click me</a>

When used like that, it tells the browser that it's a piece of script to run, not an URL to navigate to. If you use it incorrectly in an event handler, it will instead be interpreted as a label. It won't stop the script from working, because it happens to be valid syntax, but it's useless.

Upvotes: 0

Chris Dixon
Chris Dixon

Reputation: 9167

<button onclick= "a()">

Simply runs the function a().

<button onclick= "return a()">

This will run and then evalulate the response from the function a(). If this response is false then then no other further conditions will be run.

<button onclick= "javascript a()">

This will not work. <button click= "javascript: a()"> will be the same result as example 1.

Upvotes: 4

Quentin
Quentin

Reputation: 943100

The HTML is invalid, but if you had onclick then:

  1. just a function call.
  2. returns the value of the function call (which, if it is false, would cancel the default action of clicking on the element)
  3. throws a syntax error because you can't have an identifier (javascript) followed by a space, followed by a function call

If the last was javascript:a() then you would have an entirely useless label.

That said, all three are poor examples of HTML. You should avoid onclick in favour of addEventListener.

Upvotes: 4

Related Questions