0

I am currently working on javascript Function and Objects but there is a little bit confusion.

I have created an object and called its method in the window like obj.something();, it gives me result but when I write same code in console like console.log(obj.something());, it gives me undefined in the console

So, my question is obviously why & how?

var obj ={
    value: 1,
    increment: function () {
        this.value += 1
        // return this
    },

    add: function (v) {
        this.value += v
        // return this
    },

    shout: function () {
        console.log(this.value);
        // return this
    }
};
obj.shout();
console.log(obj.shout());
n4m31ess_c0d3r
  • 3,028
  • 5
  • 26
  • 35
Haseeb Jumani
  • 65
  • 1
  • 6

3 Answers3

3

undefined is the default return value from a function without return.

From MDN docs of return statement:

When a return statement is called in a function, the execution of this function is stopped. If specified, a given value is returned to the function caller. If the expression is omitted, undefined is returned instead.

Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
  • that's my point why it give undefined in console.log(obj.shout()) although it gives a result while writing the code obj.shout(); only kindly create difference between them so i will understand easily. – Haseeb Jumani Jan 04 '17 at 20:23
  • the point is, a function returns always something, but it is not seen. you see it only if you process the return value from the function, like `console.log` or other use, but not if you just call the function. it is the same if you call `Math.sin(90)`without assigning the result to a value. it became calculated but the result is gone. – Nina Scholz Jan 04 '17 at 22:17
1
You hava to return value from function ,Like this

    var obj ={
    value: 1,
    increment: function () {
        this.value += 1
        // return this
    },

    add: function (v) {
        this.value += v
        // return this
    },

    shout: function () {
         return this;
    }
   };
   obj.shout();
   console.log(obj.shout());
Sanjay
  • 2,481
  • 1
  • 13
  • 28
0

You can remove the display of "undefined" without adding a "return" by using the .call() instead of using () in a function.

var obj ={
    value: 1,
    increment: function () {
        this.value += 1
        // return this
    },

    add: function (v) {
        this.value += v
        // return this
    },

    shout: function () {
        console.info("Line-14");
        console.log(this.value);
        console.info("Line-16");
         //return;
    }
};
var objectShootResult = obj.shout;
console.info("Line-21");
objectShootResult.call(obj);
console.info("Line-22");
Ala Eddine JEBALI
  • 7,033
  • 6
  • 46
  • 65