blue ghhgdtt
blue ghhgdtt

Reputation: 921

Why return is required in javascript function?

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

Answers (3)

Iwan
Iwan

Reputation: 181

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.

Upvotes: 0

Ben McCormick
Ben McCormick

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

Niet the Dark Absol
Niet the Dark Absol

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

Related Questions