Since you are trying to do an incermenting field please let me say that you are doing it wrong.
Server-side evaulation has serious problems as @jmikola states including the fact that it is near on incompatible with everything including sharding. In fact I recommend not even learning about server side execution so much that I will not even show you an example of how to do it.
I would recommend you move away from server-side execution of JS, it is not like stored procedures or triggers in SQL and really does not run the same. The JS console is just another driver much like the MySQL console and I think this is where you are getting the confusion, you some how think that the console is like server-side execution (stored procedures etc) but it is not, it is just another client.
A Map Reduce is the only real "server-side" execution that is truely supported. You can of course store scripts within system.js for future use but this is more designed to store cumbersome MR scripts within the DB so your not constantly having to write them out or send huge files over the network repeatedly.
This function that I'm writing should retrieve the last used value of incremental field
This function most definitely would not work the same way as you expect since concurrency would make that new ID invalid because it may have already been used by another insert. Of course this depends upon the frequency of inserts but even under a slight load your IDs will not increment correctly.
To achieve an auto-incrementing ID you can actually use findandmodify as shown here: http://www.mongodb.org/display/DOCS/How+to+Make+an+Auto+Incrementing+Field and within @MrKurts answer.