2. Introducing Functions


#1

I'm here and I have some questions.

Code from task (comments deleted):

var divideByThree = function (number) {
    var val = number / 3;
    console.log(val);
};

divideByThree(6);

First block of questions:
Is this means that we make variable as function?
Or is this just specific way to give it a name?

We can define it like this:

function fun(number) {
    console.log(number / 3);
}

So... what's the difference between them?


Some function:

String.format = function(format) {
    var args = Array.prototype.slice.call(arguments, 1);
    return format.replace(/{(\d+)}/g, function(match, number) {
        return typeof args[number] != 'undefined'
            ? args[number]
            : match
            ;
    });
};

Second block of questions:
Is this means that we can create functions for all allready existed classes?
Does it work like "wrapper"?


#2

Hi there.

The first example of a function you gave is known as a function expression. The second, a function declaration.

A function declaration is special because no matter where it is declared, it'll be brought to the top of the scope it resides in upon interpretation. So you can call a function before you even declare it.

e.g.

apples();

function apples(){
  console.log('apples');
}

Will work just fine. Because it will be interpreted as...

function apples(){
  console.log('apples');

apples();
}

.. anyway.

The first function works as you expect. A good example of what is happening can be shown as...

var apples = function(){};
var pears = function(){};

// Upon interpretation will look like this 
var A, B; 

apples = function(){};
pears = function(){};

The function's variable names are "hoisted" to the top, only. Not the actual function declaration itself. So calling the function before it is declared will not work in this case like it does with the first example.

There are actually a few other ways to define functions in javascript. I recommend checking out this article on the matter if you'd like a more in depth explanation.

As for your second lot of questions. I'm going to leave that for someone else :slight_smile:


#3

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