Are they same?

Are these same ?

var Person = function(firstname,lastname){
this.firstname=firstname;
this.lastname=lastname;
}

function Person(firstname,lastname){
this.firstname=firstname;
this.lastname=lastname;
}

Those are both two different ways to create a function, being the function expression and the function declaration,

Declared functions are initially hoisted to the top, so that they can be available before code execution gets to them. However, because hoisting can make it tricky to understand how the code runs, it’s best practice to place your declared functions before any other code.

Function expressions are more commonly reserved for more specialised situations, such as when you want to assign a function to a scope outside that of the function.

For example:

var inner;
function outer() {
    inner = function () {
        ...
    };
}
...
outer();
// do something with the inner function

your explanation is difficult to understand.

could not understand. … wish there was a simpler reply .

anyway thanks for your time.

thanks for the post.

[quote=“winzip, post:3, topic:211582, full:true”]your explanation is hard to understand.

could not understand. was expecting a simple reply .
[/quote]

Functions can get complex. The simple answer is to just use function declarations and to not use function expressions until you find yourself in a situation where they are required.

Use function declarations

function funcDeclaration() { // a function declaration
    ... // use these types of functions
}

var funcExpression = function () { // a function expression
  // don't use these unless you have to
}
1 Like

Ok…litte better now…

still have some confusion…

Say If I write this …

var funcExpression = function () { // a function expression
// some code
}

Does it execute //some code and assign to funcExpression ?

I am asking because I see there is assign operator ( = )

So far with the way you are using the function, there is only one difference.

A function expression

// variable funcExpression is hoisted to the top as being undefined
var funcExpression = function () { // a function expression
    // some code
}

// variable funcExpression now contains the above anonymous function
// the function has been assigned to the variable, but has not been executed yet

funcExpression();
// the function has now been executed

The function expression starts off as being undefined.

Now for a function declaration

// variable funcDeclaration is a function, and is hoisted to the top of everything
function funcDeclaration() { // a function declaration
    // some code
}

// the function has not been executed yet

funcDeclaration();
// the function has now been executed

The function declaration means that its name always contains a function at all times.

So to summarise, the function expression starts off as being undefined. There are other things that a function expression can do, but that’s more complex and is something that is currently of no benefit to you.

Stay with function declarations and you’ll find it easier to read and understand the code.

2 Likes

Just for my own understanding @Paul_Wilkins, does declaring a function expression like this, mean that you ‘could’ assign some other value to it (a string for example), later in your code, and effectively render the function useless?

Like this

    // some code
}
funcExpression = "This is no longer a function and won't behave as one";```

I'm not sure why you'd want to do that, but it appears to be possible given the JS is not strongly typed

Yes indeed - and you can reassign variables to use different functions.

function add(num1, num2) {
    return num1 + num2;
}
function product(num1, num2) {
    return num1 * num2;
}

if (button.name === 'add') {
    oper = add;
}
if (button.name === 'mult') {
    oper = product;
}
return oper(num1, num2);

Function expressions tend to be used for special situation, such as:

  • arguments
  • modules
  • closures

##Arguments
Function expressions don’t have to be assigned to a variable. They can be passed as arguments to a function.
You’ll see them used frequently in jQuery in the form of an anonymous function, for example:

$(function () { // an anonymous function
    ...
});

or when using forEach and declaring a function expression to handle the array items. They don’t have to be unnamed either. Naming the function expression can help to express what it’s supposed to do.

var someArray = ['foo', 'bar', 'baz'];
someArray.forEach(function showProduct(item, index) {
    ...
});

##Modules
Modules are a handy technique to group and organise your code in to easy to maintain sections.

var myModule = (function () {

    function privateMethod() {
        // private
    }
    function someMethod() {
        // public
    }
    function anotherMethod() {
        // public
    }
  
    return {
        someMethod: someMethod,
        anotherMethod: anotherMethod
    };
}());

##Closure
Closure is where a function retains knowledge and can access variables from the scope of its its parent.

[bad example removed]

See fret burner’s next post for a good example of closure.

So in summary - function expressions are for special circumstances, and are best reserved for those special circumstances. The function expression is a good indicator to pay attention to the code, for something extra is usually being done there instead.

4 Likes

That last example doesn’t actually demonstrate a closure, because the fullname method is referring to properties of this. The value of this changes dependent of the context in which the function is called:

// this === ford
var ford = new Person('Ford', 'Prefect');
ford.fullname();
// <-- "Ford Prefect"

// this === window
var fullname = ford.fullname;
fullname();
// <-- "undefined undefined"

Once the function is executed in the global context, the this reference within fullname() now points to the global scope (the window object, when run in a browser). This behaviour often catches people out when they try to use object methods as event callbacks:

document.addEventListener("DOMContentLoaded", ford.fullname, false);
// value of 'this' will be set to window

A closure occurs when you return a function from a function. The returned function retains access to the variables from the parent function:

function closureFactory(firstname, lastname) {
    return function() {
        return firstname + ' ' + lastname;
    };
}

var firstname = 'Arthur',
    lastname = 'Dent';

var fullname = closureFactory(firstname, lastname);

fullname();
// <-- "Arthur Dent"

firstname = 'Zaphod';
lastname = 'Beeblebrox';

fullname();
// <-- "Arthur Dent"

Here, the returned function retains access to the values of firstname and lastname as they were when the parent function was called. As you can see, changing the value of those variables in the global scope doesn’t affect the value returned by fullname().

1 Like

[quote=“fretburner, post:9, topic:211582, full:true”]
That last example doesn’t actually demonstrate a closure[/quote]

Thanks fretburner, all I can say is it was very late for me.

Closure is used when you want to retain information that would otherwise not be available at some later time.

A common example of this being used to solve a problem is in a for loop, where attaching a function as an event handler results in the function not having the expected information about the loop index value.

// the following is bad code, demonstrating why you might need a closure

for (i = 0; i < list.length; i += 1) {
    document.querySelector('#item' + i).onclick = function doSomething(evt) {
        // Do something with item i.
        // But, by the time this function executes, the value of i is not the same.
    }
}

The reason for this problem is that the loop fully executes, and later on when the onclick event triggers the function, the value of the i variable is different from when the function was being assigned.

It’s easier to understand why the problem occurs, by extracting the doSomething function out from within the for loop.

// the following is bad code, demonstrating why the above code is bad

function doSomething(evt) {
    // Do something with item i.
    // But, by the time this function executes, the value of i is not the same.
}

for (i = 0; i < list.length; i += 1) {
    document.querySelector('#item' + i).onclick = doSomething;
}

The doSomething function being used as an event handler is not allowed to have any other parameters passed to it. The solution to this is to return it as an inner function from an outer function, allowing you to retain other information too. This is where you’ll commonly see handler functions used, that organise the information that the returning function will need.

// the following is good code, demonstrating the use of closure

function doSomethingHandler(itemIndex) {
    var otherVariable = ...;
    return function doSomething(evt) {
        // now this doSomething function can retain knowledge of the index variable,
        // via the itemIndex parameter and other variables that may be available too.
    }
}

for (i = 0; i < list.length; i += 1) {
    document.querySelector('#item' + i).onclick = doSomethingHandler(i);
}

Some good examples of what can be done with closures can be found at http://jibbering.com/faq/faq_notes/closures.html#clClDo

1 Like

An even simpler solution is to ALWAYS use function expressions. Then you don’t need to worry about using function declarations at all as everything you can do with functions declarations can be done with function expressions. That avoids the need to consider what can be done with expressions that can’t be done with declarations…

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.