L
L
LittleFatNinja2015-09-21 10:53:11
JavaScript
LittleFatNinja, 2015-09-21 10:53:11

What is the difference between js function declarations?

var foo = function() {

}

function foo() {

}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vitaly Inchin ☢, 2015-09-21
@In4in

All comparisons are here .

// Function Declaration
sum(1,2) //3
function sum(a, b) {
  return a + b;
}

// Function Expression
summer(1,2) //Ошибка, summer не определена 
var summer = function(a, b) {
  return a + b;
}

Ps And there is also the Function constructor that stands out from the crowd . It allows you to create functions from a string, but its offspring, infections, do not remember the environment in which they are created.
var 
     abs = "Я переменная",
     func = (function(abs){
         return new Function("", "return abs;");
     })("Я аргумент")
;

//Вызовем созданную функцию
alert(func()); //"Я переменная"

A
Arthur, 2015-09-21
@TheSunwave

In the first case, the function is called Function Expression, in the second Function Declaration, they differ in that the Function Declaration is created by the interpreter before the code is executed, which means that the function will be executed at the time of initialization, and not at the time of its explicit call.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question