Exact meaning of Function literal in JavaScript

dublintech picture dublintech · Sep 7, 2012 · Viewed 13.4k times · Source

In JavaScript there are both Object literals and function literals.

Object literal:

myObject = {myprop:"myValue"}

Function literal:

myFunction = function() {
   alert("hello world");
}

What is the significance of the word literal? Can we say Java has method literals?

public void myMethod() {
    System.out.println("are my literal");
}

Answer

Salketer picture Salketer · Sep 7, 2012

The biggest difference is how/when it is parsed and used. Take your exemple,

myFunction = function() {
   alert("hello world");
}

You can only run myFunction() after the code got to there, since you declare a variable with an anonymous function.

If you use the other way,

function myFunction(){
   alert("hello world");
}

This function is declared at compile time and can be used anytime in the scope.

Please refer to this question also.