5

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.

JD.
  • 15,171
  • 21
  • 86
  • 159
  • 5
    C# doesn't even have functions *per se* - it only has methods (and delegates/lambdas, which are method references). That said, you could call delegates C#'s analog to JavaScript anonymous function objects. – BoltClock Jun 16 '12 at 06:48
  • 1
    @BoltClock: Function vs. Method vs. Procedure vs. Subroutine vs. whatever... I honestly don't see the difference between half of them, if not more... – user541686 Jun 16 '12 at 07:09
  • @BoltClock: And lol, nice response time! – user541686 Jun 16 '12 at 07:10
  • @Mehrdad there isn't really a difference, other than name, at least when comparing from like VB to C# to Javascript. – jcolebrand Jun 16 '12 at 07:10
  • 2
    @jcolebrand: Yea that's what I mean. I mean you could really start getting picky and saying things like, "functions are just pointers", "procedures are just a generic name for all of them", "methods also have context pointers", "subroutines are procedures that aren't coroutines", yada yada, but that's really not a useful distinction. (Only mentioned it since it kinda annoys me whenever I ask a C++ question and say "the method std::find" and people say "C++ doesn't have methods", since it's just nomenclature... they obviously know what you mean haha.) – user541686 Jun 16 '12 at 07:14
  • 2
    And then there's also delegates vs. lambdas vs. inline functions vs. closures vs. God knows what... the fun never ends :) – user541686 Jun 16 '12 at 07:22

5 Answers5

7

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.

jcolebrand
  • 15,889
  • 12
  • 75
  • 121
  • 3
    I'd beg to differ... `Predicate pred = i => i % 2 == 0;` certainly looks like first-class functions to me... it's just that the type isn't inferred for you. Which doesn't make any difference anyway... – user541686 Jun 16 '12 at 07:11
  • It's still a `Predicate` and not a raw function. It wasn't a design requirement for C# to have first class functions, but they are currently a part of the language, but not in the same way that javascript has them. Can't do a closure in C# (_yet_) (according to wikipedia you can, but I disagree semantically). Note that the wiki page I linked to shows that they are currently a feature. – jcolebrand Jun 16 '12 at 07:13
  • 3
    You can't do a closure in C#? Pardon me, but... wtf? – user541686 Jun 16 '12 at 07:15
  • 1
    Oh so apparently a delegate is sufficient to qualify as a closure. I prefer my closures to look like `function(){ ... }` :p and note that you can do things like nested functions in javascript because they're first class citizens. – jcolebrand Jun 16 '12 at 07:16
  • 1
    Have you actually used C# before? (Or maybe Scheme? Or maybe D? Or Haskell or C++11 or whatever...) Because your idea of a closure certainly seems tightly coupled with that of Javascript... and furthermore, what you mentioned isn't really a closure -- it's just executing a normal block of code, plain and simple. The only difference is that it prevents corruption of the global namespace, but that idea itself is **not** related to closures at all -- it's just a JS thing. Namespaces are completely orthogonal to closures. – user541686 Jun 16 '12 at 07:16
  • I stuck my tongue out on purpose. I haven't used D, actually, and probably should. I do still have a hard time wrapping my mind around closures in C#, probably because I'm used to javascript style closures. But I do know that I can nest data into a Func just like I would a `function(){}` in Javascript. – jcolebrand Jun 16 '12 at 07:19
  • Yes, I get that ()() isn't a closure, I can tell I'm getting tired and should goto bed soon. I meant function(){nested-operation-here} – jcolebrand Jun 16 '12 at 07:20
3

Javascript functions can be created and assigned to a variable, they're first class citizens in the language and have some more flexibility over the syntactical sugar that C# has applied.

In C#, when you write the code

x => x * x

The compiler creates a real named method and wraps that method in a delegate that can be executed.

Delegates, along with the syntactic sugar that C# applies gives a very similar feel to JavaScript, but it's doing very different things internally.

In JavaScript you can create a function and assign it directly to a variable and execute it without wrapping it in any other structures to enable the action. Functions are first class citizens in JavaScript.

Kevin McKelvin
  • 3,467
  • 1
  • 27
  • 27
1

The one biggest difference I can think of is that in C# functions, variables are lexically scoped, whereas Javascript, variables are lexically scoped except for this, which is dynamically scoped.

For example, in Javascript, you can say something like

var foo = new Object();
foo.x = 0;
var bar = function() { this.x = 2; };  // first-class function... what's "this"?
foo.baz = bar;   // Now foo has a method called 'baz', which is 'bar'.
foo.baz();
alert(foo.x);   // Displays 2 -- 'this' magically refers to 'foo'!

Try writing this in C#.

Or actually, don't bother -- it will not make any sense.

Why? Because this doesn't refer to anything here, lexically! Its meaning changes dynamically, unlike in C#, where its meaning simply depends on the enclosing class, not who the caller actually is.

user541686
  • 205,094
  • 128
  • 528
  • 886
  • 1
    You have got this wrong. Variables used in a function (in any programming language) may be either free (non-local) or bound (local). In a lexically scoped language the free variables of a function are resolved to the variables in the parent scope of the function when __it was defined__. In a dynamically scoped language the free variables of a function are resolved to the variables in the calling scope of the function when __it is called__. The `this` keyword is not a free variable. It has special rules. See the following [question](http://stackoverflow.com/q/10060857/783743 "Dynamic scopes."). – Aadit M Shah Jun 16 '12 at 08:08
  • @AaditMShah: Uh, no, I'm pretty sure this is right... not sure which part exactly you're saying is "wrong", but like I've mentioned, `this` is dynamically scoped in JS, and other variables are statically scoped. I also don't know what you mean by free vs. bound variables here, since I don't see any "free" variables other than `this`, which I already mentioned is dynamic. – user541686 Jun 16 '12 at 08:10
  • Thanks, really interesting...wasn't even aware of dynamic scoping. – JD. Jun 16 '12 at 09:37
  • Going to give the answer to you although Jcolebrand answered part of the question...although you highlighted some areas I need to look at :) – JD. Jun 16 '12 at 09:43
  • 2
    @JD. that doesn't hurt my feelings, btw :p ~ Choose the answer you thought was most appropriate, you only get one checkmark. – jcolebrand Jun 16 '12 at 21:20
  • 1
    Thanks, I always worry about hurting feelings :) – JD. Jun 18 '12 at 14:18
0

I have some rough ideas about the difference between JS and C#:

1, Js is an interpreted language, which means JS needs a browser build-in ECMAScript interpreter to work. Whereas C# is a Compiled language, which means C# codes will be compiled as IL to work.

2,JS is a dynamically typed language, which means you don't need to specify the types of the variables when defining. Whereas C# is statically typed language, which means you need to specify the exact types of the variables.

3, OOP-encapsulation, in JS, a lot of people say function is first class citizen. Normally, function has 2 kinds of usages: a)just a function to manipulate some work b)class&constructor, using which you can instantiate objects. Whereas in C#, function is function, which should belong to class(or interface).

4, OOp-inheritance, in JS, we use prototype to realize inheritance. Whereas in C#, we strictly use class to realize inheritance.

5, OOP-polymorphism, in JS, according to my knowledge, we can use arguments, which is a pseudo-array, to realize functional overload to simulate polymorphism, which is a bruising. Whereas, for C#, polymorphism is so perfectly embodied.

6, In JS, we don't have GC. Whereas, there is a strong GC for C#.

Maybe some ideas are not correct, welcome suggestions.

  • 1
    The question is about the difference in semantics between C# and Javascript *functions* -- not a list of differences of the two as a *language*. – Kirk Woll Aug 05 '14 at 00:16
0

Just to clarify some confusion;

1) JavaScript is a compiled language indeed. The way the code is compiled is right before the execution on the browser, and it is fast! This is why some developers think it's an 'interpreted' language.

2) C# does not have functions in JS sense. It has class methods.

Mike Bahar
  • 26
  • 2