0

When i executed following JavaScript code, i got undefined

var ns=new String('hello world');
String.prototype.capitalAll=function(){
                                 this.toUpperCase()
                                       };
alert(ns.capitalAll()); // undefined

But, when i add return, it returns a value

var ns=new String('hello world');
String.prototype.capitalAll=function(){
                                 return this.toUpperCase() // added return
                                       };
alert(ns.capitalAll()); // HELLO WORLD

Why return is required here and in end of every function. I have seen use of return in many javascript frameworks.

blue ghhgdtt
  • 907
  • 4
  • 11
  • 16
  • Should be obvious, but unless you're returning a value from the function, the default `undefined` is returned! – adeneo Mar 01 '13 at 18:00
  • I think you summed it in your own question: when you use `return`, it returns a value. – zneak Mar 01 '13 at 18:00
  • 3
    @adeneo please don't say that something should be obvious. the op is asking because he/she doesn't know. we all had/have to start somewhere. – henry bemis Mar 01 '13 at 18:05
  • @henrybemis - based on the code above with prototyping etc. it's not the OP's first rodeo (hopefully), and what "return" does should be obvious, it is in fact so obvious that the OP has already answered his own question. – adeneo Mar 01 '13 at 18:15

3 Answers3

1

How else would you return data from a function call?

Functions like Array.prototype.shift() are transformative, in that they modify the array. Internally, they do something like this[this.length] = newvalue and actually modify this in some way.

But most functions are not transformative, they return the result.

Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
1

return allows you to define what a function passes back when its called.

Its not required to have a return value, you can have a function that returns nothing, it just modifies other variables or prints something and then continues.

undefined is returned when you don't specifically specify another value to be returned

Ben McCormick
  • 25,260
  • 12
  • 52
  • 71
0

What toUpperCase does:

The thing is that toUpperCase doesn't modify "this" in the first place. That is a function that returns a value.

Some methods modify the object they are called on (they modify "this").. and in those cases you could write the function like you had it. In this case though, you need to use the "return" value.

Iwan
  • 181
  • 3