Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Function Definition Syntax [duplicate]

Possible Duplicate:
JavaScript: var functionName = function() {} vs function functionName() {}
Declaring functions in JavaScript

I've seen 2 different syntaxes for defining functions in javascript:

function f() {    ... } 

As well as

var f = function() {     ... }; 

What's the difference between these? Is one of them deprecated?

like image 356
CaptainCodeman Avatar asked Feb 24 '12 00:02

CaptainCodeman


People also ask

Can you define a function twice in JavaScript?

functions are data in memory stack, so when you define another function with the same name, it overrides the previous one. Show activity on this post. Well obviously you're not meant to define the same function twice. However, when you do, the latter definition is the only 1 that applies.

How do you define a function in JavaScript?

A JavaScript function is defined with the function keyword, followed by a name, followed by parentheses (). Function names can contain letters, digits, underscores, and dollar signs (same rules as variables). The parentheses may include parameter names separated by commas: (parameter1, parameter2, ...)

Can you call a function before it has been defined JavaScript?

Is hoisting actually "calling the function before it is defined"? Raising the scope of a declared name so that it will be defined for other code under that scope -- that's roughly what JavaScript does to allow you to call the function before it's declared, and that's hoisting.


1 Answers

Neither are deprecated, and both will work. The difference here is that one is a named function ( function f() ) while the other is a variable equal to a function ( var f = function() ).

You have to be careful when setting variables equal to functions. This will work:

var f = function(n) { console.log(n); }; f(3); // logs 3 

But this will break, since the variable is defined after the call to it.

f(3); // what is f? breaks. var f = function(n) { console.log(n); }; 

But normal functions work fine.

function abc(n) { console.log(n); }  abc(3); // logs 3 xyz(5); // logs 5  function xyz(n) { console.log(n); } 

This is because the code is analysed before execution, and all functions are available to call. But setting a var equal to a function is like setting a var to anything else. The order of when it happens is important.

Now for some more confusing stuff...

There are also 'self-executing' anonymous functions. They go by a variety of names. The most common way to do it looks something like this:

(function() {     // code in here will execute right away     // since the () at the end executes this (function(){}) })(); 

There is also an arguably better version.

!function() {     // again, the tailing () will execute this }(); 

Check out this Stack Overflow post for more on anonymous functions.

like image 108
Marshall Avatar answered Sep 23 '22 02:09

Marshall