0

kindly enlighten me as I am new to javascript. I have sample 1 and 2 below and I wonder why sample 2 can't display the right expected result when keyword "return" is being used. I know plus(+) sign could solve the issue in question, just wondering when to used comma(,) for concatenation in javascript when it comes to variables.

sample-1
var person = {
  firstName: "John",
  lastName : "Smith",
  fullName : function() {
    console.log("my name is ",this.firstName +" ",this.lastName);
  }
}
person.fullName(); //my name is  John  Smith

sample-2
var person = {
  firstName: "John",
  lastName : "Smith",
  fullName : function() {
    return "my name is ",this.firstName +" ",this.lastName;
  }
}
person.fullName(); //"Smith"
2
  • 1
    The comma operator evaluates each of its operands (from left to right) and returns the value of the last operand. Commented Apr 16, 2019 at 13:28
  • 1
    @kemotoe except in a function call when it separates different arguments... Commented Apr 16, 2019 at 13:29

2 Answers 2

2

With

    console.log("my name is ",this.firstName +" ",this.lastName);

you pass several arguments to the console.log function. It works just like any plain function call. The number of arguments for console.log is more or less arbitrary, the function will know what to do with them (kind of like Math.max).

That

    return "my name is ",this.firstName +" ",this.lastName;

doesn't return several values (looks like it is going to return this.lastName). A function can return a single value, or no value at all. You want to concat the above to a single string, you must do it differently. With +, for example.

Sign up to request clarification or add additional context in comments.

2 Comments

The return is not incorrect, it just won't do what the OP expects. If it were invalid syntax the OP wouldn't have noticed the strange return value because the code would not have run.
it is simply incorrect syntax it is correct syntax. But the computer does what you've told it to do, not what you want it to do.
1

Commas inside the parentheses marking a function call separate the argument expressions. Outside, as in your return statement, they're the "comma operator".

So the magic that console.log() does is just based on code in that function that explicitly looks at all arguments you pass it.

The return is basically equivalent to

"my name is ";
this.firstName + " ";
return this.lastName;

The commas in your sample split the overall expression up into three pieces, and each piece is separately evaluated. The overall value of a, b, c is the value of c alone.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.