Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between these two particular JavaScript functions? [duplicate]

Tags:

javascript

Possible Duplicate:
The difference between the two functions? (“function x” vs “var x = function”)
JavaScript: var functionName = function() {} vs function functionName() {}

var test = function() {
    var a = 20;
    var b = 30;

    return a + b;
};

function Add() {
    var a = 20;
    var b = 30;

    return a + b;
}

What is the difference between these two functions? If I call add() or test() they both give me the same result. What exactly does the var do?

like image 281
Frankie Avatar asked Jun 12 '26 03:06

Frankie


1 Answers

The function declaration syntax cannot be used within a block statement.

Legal:

function a() {
    function b() {

    }
}

Illegal:

function a() {
    if (c) {
        function b() {

        }
    }
}

You can do this though:

function a() {
    var b;
    if (c) {
        b = function() {

        };
    }
}

For the language nerds among us you'll want to reference sections 12.1, 13.1, and 14 of the specification. You will find the following syntax descriptions.

12.1 Block

Syntax

Block :
    { StatementListopt }

StatementList :
    Statement
    StatementList Statement

13 Function Definition

Syntax

FunctionDeclaration :
    function Identifier ( FormalParameterListopt ) { FunctionBody }

FunctionExpression :
    function Identifieropt ( FormalParameterListopt ) { FunctionBody }

FormalParameterList :
    Identifier
    FormalParameterList , Identifier

FunctionBody :
    SourceElements

14 Program

Syntax

Program :
    SourceElementsopt

SourceElements :
    SourceElement
    SourceElements SourceElement

SourceElement :
    Statement
    FunctionDeclaration

like image 158
ChaosPandion Avatar answered Jun 13 '26 20:06

ChaosPandion



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!