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.

6
  • 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. Commented Jun 16, 2012 at 6: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... Commented Jun 16, 2012 at 7:09
  • @BoltClock: And lol, nice response time! Commented Jun 16, 2012 at 7: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.) Commented Jun 16, 2012 at 7:14
  • 2
    And then there's also delegates vs. lambdas vs. inline functions vs. closures vs. God knows what... the fun never ends :) Commented Jun 16, 2012 at 7:22

5 Answers 5

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.

Sign up to request clarification or add additional context in comments.

7 Comments

I'd beg to differ... Predicate<int> 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...
It's still a Predicate<T> 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.
You can't do a closure in C#? Pardon me, but... wtf?
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.
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.
|
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.

2 Comments

In C# the compiler doesn't quite do that. You need the delegate type mentioned too. :-)
It will use the delegate type inferred from the context when one is available. Which comes back down to syntactic sugar.
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.

6 Comments

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.
@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.
Thanks, really interesting...wasn't even aware of dynamic scoping.
@JD. that doesn't hurt my feelings, btw :p ~ Choose the answer you thought was most appropriate, you only get one checkmark.
Thanks, I always worry about hurting feelings :)
|
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 Comment

The question is about the difference in semantics between C# and Javascript functions -- not a list of differences of the two as a language.
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.