Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between functions in C# and Javascript?

Tags:

javascript

c#

I am learning Javascript and I have read functions are first class objects and most authors mention that functions can return functions (which are objects) and pass them as parameters to other functions.

I am sure there is a lot more to it so what are the differences between functions in C# and functions in javascript?

In C# am I right to say functions are not objects (don't have methods, properties etc) even though with closures (with lambda expressions and delegates) they seem to behave like function objects as in javascript?

I feel that with lambda expressions in C# the distinction becomes a bit blurry for someone just coming to the language.

like image 781
JD. Avatar asked Jun 16 '12 06:06

JD.


1 Answers

What most authors say is that "functions are first class citizens" in javascript. They are not first class in C#, in that they are merely methods there, attached to a class. Method delegates (and lambdas) are specific classes for the purpose of making methods like first class citizens.

So here's the thing, as best I can explain it, without telling you to go back and read Crockford's "Javascript: The Good Parts" and something by like Skeet or someone:

Javascript has a lot less parts than C#. Don't compare something you can do in C# directly with something you can (or can't) do in Javascript (and vice-verse).

So why don't all languages (or at least C#) have "first class functions"? The answer is usually the simplest: Because that wasn't a language design requirement. That's sort of a cop-out on my part, however, because obviously they've added it in now. But if nobody told you to include it in your future-language, would you?

So the key thing to remember is: in C# functions (methods) have to be attached to a class. In Javascript they don't. The why is in the language definition (spec).

Also, I should follow this up with a statement on object creation:

You can create a new object in javascript in one of two ways:

//using object syntax
var ob1 = { name: value, nestedFunction: function(){} };

or

//using a function
function MyFunc(){
  var name = value;
  function nestedFunction(){}
}
var ob2 = new MyFunc();

And in the second case we're using a function to declare the object, in the first case we're just declaring it using literal syntax.

To do the same thing in C# we have to create a new object as a class:

MyClass ob1 = new MyClass(); //constructor is a member function of the class
public class MyClass {
  public MyClass() {
  }
  public void nestedFunction(){
  }
}

Notice how in the Javascript one I still had to define the method that was being returned.

Ok, I think that's enough for tonight.

like image 91
jcolebrand Avatar answered Sep 30 '22 15:09

jcolebrand