Two ways to write functions in javascript. Which is better?


#1

Which of these two ways to write a function in javascript is better, and why

1 -- function myFunction(param){

2 -- var myFunction = function(param){


#2

Function declarations, (#1 above) are less versatile than anonymous function expressions, and the fact they can be written anywhere in their scope leads some developers to write them based on their forgiveness (they can be invoked from anywhere, above or below the statement). Function expressions force us to write the function before the point where they are invoked.

Should we concern ourselves with which is 'better'? At this point, no. We should focus on understanding how they work, and on scope, where they can be invoked and which variables are accessible to them. For the most part we should not look for the author's reasoning in how they are defined in these courses. They are effectively the same thing so long as they CAN be invoked.

Function declarations are fixed objects that cannot be renamed or removed. This can have a bearing on resource usage. Function expressions can be written inside a function which when exited gives up the memory it used. The expressions only exist as long as the outer function is running. Garbage collection is able to recover the memory.

Bottom line, at this stage it is a minor concern so don't be fostering the belief that one should pick and choose given the situation. Either form is just fine.


#3

Thanks for your help.


#4

Supplemental

The following example is rather convoluted but it demonstrates the use of anonymous functions in what is called a closure. Don’t let this distract you, at present, since closures are not even discussed in this track so it is outside of the scope of this course.

The outer function takes two parameters, a and b then asks the user to choose an operator. The values of a and b are preserved in the function that is returned to the caller. The caller then invokes the returned function.


var simple_calculator = function (a,b) {
    var operator;
    while (true) {
        operator = prompt(a + "__" + b + " => Operator: + - * /");
        if ('+-*/'.indexOf(operator) > -1) break;
    }
    switch (operator) {
    case "+": 
        console.log(a + " + " + b);
        return function() {return a + b;};
    case "-": 
        console.log(a + " - " + b);
        return function() {return a - b;};
    case "*": 
        console.log(a + " * " + b);
        return function() {return a * b;};
    case "/": 
        console.log(a + " / " + b);
        return function() {return a / b;};
    }
};
console.log(simple_calculator(6,7)());

Now we would never write a program this complex for the basic operations being performed. I only wrote this as a demonstration. If you do not understand it that should not bother you. Most people have trouble wrapping their head around the concept. Bookmark and return when you have completed the track.

Code
// Simple calculator factory
// study by Roy as supplement to
// https://discuss.codecademy.com/t/two-ways-to-write-functions-in-javascript-which-is-better/59726

var simple_calculator = function(a,b) {
    var operator;
    while (true) {
        operator = prompt(a + "__" + b + " => Operator: + - * /");
        if ('+-*/'.indexOf(operator) > -1) break;
    }
    switch (operator) {
    case "+": 
        console.log(a + " + " + b);
        return function() {return a + b;};
    case "-": 
        console.log(a + " - " + b);
        return function() {return a - b;};
    case "*": 
        console.log(a + " * " + b);
        return function() {return a * b;};
    case "/": 
        console.log(a + " / " + b);
        return function() {return a / b;};
    }
};
console.log(simple_calculator(6,7)());
/*
var f = simple_calculator(6,7);
console.log(f());
*/


#5

Thanks again. I do understand it.

I'm a retired programmer learning a few new things here as a hobby, so lot's of this is pretty familiar.


#6

Just for clarification, I edited the above post to read closure and not enclosure since there is a difference and my usage of the word was not accurate. A closure is as we demonstrated, a function that has preserved states that are protected from the outside.

An enclosure is somewhat the same but it implies self execution, and iife, immediately invoked function expression.

(function () {})()

The above is the trivial representation of an enclosure. Please pardon my misnomer in the pre-edited post. Thank you.


#7

ES6 changes the landscape considerably.

XO = (str) => !(str.split(/[oO]/).length - str.split(/[xX]/).length);

Functional programming, as compared to my procedural approach, as a first draft, to solve the same problem.

function XO(str) {
    var s,x,o,i;
    s = str.toLowerCase();
    x = s.indexOf('x');
    o = s.indexOf('o');
    if (x < 0 && o < 0) return true;
    if (x < 0 || o < 0) return false;
    for (i = 0, x = 0, o = 0; i < s.length; i++) {
        x += s[i] === 'x' ? 1 : 0;
        o += s[i] === 'o' ? 1 : 0;
    }
    return x === o;
}

Of all the posted solutions, mine is more elementary but it passes all tests, so is ready for refactoring.


#8

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