1

Consider the following examples of Javascript attributes in HTML elements:

<input type="button" onclick="somceFunc()" />
<input type="button" onclick="somceFunc();" />
<input type="button" onclick="somceFunc(); return false;" />

When should one end the someFunc() call with a semi-colon, and when should the semi-colon be eliminated? Also, when should one end the attribute with a call to return false;?

Thanks.

dotancohen
  • 30,064
  • 36
  • 138
  • 197
  • 1
    Well, you should never end with `false` - it doesn't do anything. (You might be thinking of `return false;`) – JJJ Jun 05 '12 at 17:02
  • 2
    that's not a colon. It's a semicolon. – DA. Jun 05 '12 at 17:03
  • 1
    I am pretty sure it is best practice to end all the function calls with a semicolon. And like Juhana said you should use return false; This will disable whatever the default action is (ie return false for onsubmit would disable the form from performing its default action) – Josh Frankel Jun 05 '12 at 17:03
  • See also http://stackoverflow.com/questions/128923/whats-the-effect-of-adding-return-false-to-an-onclick-event – JJJ Jun 05 '12 at 17:04

3 Answers3

5

When should one end the someFunc() call with a colon, and when should the colon be eliminated?

That's a semi-colon. Always end expressions with one. Automatic semi-colon insertion has enough gotchas that you are better off just avoiding it.

Also, when should one end the attribute with a call to false?

false is a literal, not a function, you can't call it.

The usage in that example does absolutely nothing.

If you were to return false from an intrinsic event attribute (like onclick) then you would stop the default action of the control from firing. e.g. a link would not be followed. A button has no default action though.

Intrinsic event attributes should be avoided in favour of unobtrusive JavaScript.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
2

SEMI-colons are optional in JavaScript, but it's always a good idea to include them to avoid nasty surprises, such as what happens if you try to do this:

return
  {
    a:1,
    b:2
  };

As for the false, it alone does nothing. You want to returnfalse when you want to stop the default click action from happening (usually only matters on links or form buttons).

Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
1

Semicolons serve to separate statements from each other,

It is good practice to use semicolon after a function call or any JavaScript statement.

For 'false' statement :

<input type="button" onclick="somceFunc(); false;" />

This is wrong approach. Either you should call return false
Well, return false is call to prevent the action to be called.

BenMorel
  • 34,448
  • 50
  • 182
  • 322
Nishu Tayal
  • 20,106
  • 8
  • 49
  • 101