0

I am a begginer in javascript, so i just need theoretical explanation. What's mean ; behind } and why I must put it there? When i work in PHP I don't need to put ; after function {} like in this case.

var orangeCost = function(price)
{
    var quantity = 5;
    console.log(quantity * price);
};
orangeCost(5);

I just want to know is this code good or not because I can't get a desired result in this case:

var orangeCost = function(price)
{
    var quantity = 5;
    console.log(quantity * price);
}
orangeCost(5);
  • In PHP you must add a semi colon right at the same place... – PeeHaa Mar 16 '15 at 22:32
  • 1
    http://3v4l.org/A9JoB – PeeHaa Mar 16 '15 at 22:33
  • Declare your functions like this: `function orangeCost(price) { ... }` and you won't think twice about needing a semi-colon at the end because it's a function declaration, not a statement. I never understand why people do `var orangeCost = function(price) { ...}`. This just makes your code order dependent when it doesn't need to be. – jfriend00 Mar 16 '15 at 22:53
  • I have been found var xxx = function(xxx) in the schoolbook, but thank You for answer and explanation! –  Mar 18 '15 at 18:01
  • actually Your explanation is very helpful, I didn't recognize the way I wrote the function! Very helpful answer. –  Mar 18 '15 at 18:06

2 Answers2

0

When you assign a function to a variable, it's just like any other assignment.

var aMethod = function() { /*...*/ };
var aNumber = 123;

In both cases, semicolons at the end are optional. It's recommended to add them to avoid statements accidentally being combined if a newline is removed (say, during the process of concatenating your source code).

bvaughn
  • 13,300
  • 45
  • 46
0

You add a semicolon ; to mark the end of a statement. However, this isn't always enforced, and several js parsers will accept using just the line break as the end of the statement. This is currently seen as a bad practice, because in certain scenarios the parser has no way of discriminating coding linebreaks from literal linebreaks. For example, if you tried to declare a string containing a line break, you gonna have a bad time.

There are certain constructs that do not have a closing semicolon. Funcion declarations (as opposed to function expression as in your example) do not carry a trailing semicolon:

function orangeCost(price) {
    var quantity=5;
    console.log(price*quantity);
}

You don't use trailing semicolons after loops such as if/else, for or switch either.

This isn't different from PHP, not at all. In PHP the same applies to procedural functions and lambda functions:

<?php
function orangeCost($price) {
   $quantity=5;
   echo $quantity*$price;
}

$orangeCost=function($price) {
   $quantity=5;
   echo $quantity*$price;
};

the only difference would be that in PHP the lambda function would have to be invoked using $orangeCost(5) instead of orangeCost(5).

ffflabs
  • 17,166
  • 5
  • 51
  • 77