Reputation: 921
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.
Upvotes: 0
Views: 189
Reputation: 181
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.
Upvotes: 0
Reputation: 25728
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
Upvotes: 1
Reputation: 324630
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.
Upvotes: 1