0

Should I add a ; after putting a function into a variable? is this code right?

pj.RemoveProjectTask = function (e, scope) {
    e.preventDefault();
    scope.remove();
};

pj.ToggleProjectTask = function (e, scope) {
    e.preventDefault();
    scope.toggle();
};

or this code:

pj.RemoveProjectTask = function (e, scope) {
    e.preventDefault();
    scope.remove();
}

pj.ToggleProjectTask = function (e, scope) {
    e.preventDefault();
    scope.toggle();
}
Mohamad Shiralizadeh
  • 8,329
  • 6
  • 58
  • 93

4 Answers4

5

You should add a semicolon to guard against this edge case:

var foo = function(){
  // your code here
}

(x=42);

In this case JavaScript actually invokes the function and passes in 42 as an argument, and sets foo to the return value of the function.

This has bitten me in the past when a build process concatenates and minifies multiple JavaScript files together, and one file ends with a function assignment like var foo = function(){ ... } without a semicolon, and the next file starts with closure-based code like (function(){ ... })(window);

Phrogz
  • 296,393
  • 112
  • 651
  • 745
1

In javascript, adding a semicolon after each valid (function call, variable modification, etc) line is optional unless you want to have multiple instructions on the same line, in which case the semicolon is required:

function something()
{
    do_a_thing(); do_another_thing(); ...
}

But this could be written just as easily like so:

function something();
{
    do_a_thing() // Can opt not to have a semicolon
    do_another_thing(); // Can opt to have a semicolon
}

In most cases, it is up to you and your preferred style

Levi
  • 1,921
  • 1
  • 14
  • 18
  • are you kidding? it's **optional**? – Mohamad Shiralizadeh May 18 '15 at 05:08
  • 2
    @Mohamadshiralizadeh It's called Automatic Semicolon Insertion, and it is one of the horrible features of Javascript [that can get you in trouble if you rely on it](http://bonsaiden.github.io/JavaScript-Garden/#core.semicolon). Best to always explicitly add them. – GregL May 18 '15 at 05:11
  • 1
    Not at the end of each line. In fact, putting it after each line in your own code would result in syntax error: `function something(); {; do_a_thing(); do_another_thing(); };` is not grammatical. – Amadan May 18 '15 at 05:18
  • @Amadan: Good point. Let me fix that... – Levi May 18 '15 at 05:19
1

Semicolon is optional in javascript function...anyway if add in the sense it wont create any problems.See the standard code convention http://javascript.crockford.com/code.html

Anand
  • 99
  • 10
0

; is optional in javascript but if you are going to follow jslint or jshint standards you should put ; at the end of each statement.

Super Hornet
  • 2,839
  • 5
  • 27
  • 55
  • Not at the end of each line. At the end of each *statement*. And even that is not correct, because, e.g., standalone `function foo() { ... }` is a complete statement that does not need a semicolon. – Amadan May 18 '15 at 05:12