-2

The question is really simple but i searched everywhere couldn't get an answer.

add();
function add()
{
//function code here
}

The above code works in JavaScript even though function call is before function definition but wouldn't work in language such as C or C++. Could anyone tell me why?

  • 1
    http://stackoverflow.com/questions/7506844/javascript-function-scoping-and-hoisting – Fritz Aug 23 '16 at 04:06
  • Don't feel too bad, this is a common question because it's hard to know what to search for until you've heard of it. – zzzzBov Aug 23 '16 at 04:07

2 Answers2

-1

It's known as hoisting, and it's definitely a trap for beginners!

Basically, if you take this code:

var x = 21;
var y = add10(x);

function add10(n) { return n + 10; }

after hoisting, it is evaluated like this:

function add10(n) { return n + 10; }
var x;
var y;

x = 21;
y = add10(x);

Because the declarations are separated from the definitions, and "hoisted" to the top.

Funnily enough, this would fail:

var x = 21;
var y = add10(x);

var add10 = function (n) { return n + 10; }

because it is evaluated like this:

var x;
var y;
var add10;

x = 21;
y = add10(x); // add10 is not a function (yet...)!
add10 = function (n) { return n + 10; }
Alex McMillan
  • 17,096
  • 12
  • 55
  • 88
-1

It's called hoisting.

The javascript engine first looks for function declarations and 'hoists' them to the top before your actual code starts running.

Here's the documentation: http://www.w3schools.com/js/js_hoisting.asp

MarksCode
  • 8,074
  • 15
  • 64
  • 133