-1
function returnName() {
    var name = 'Stack Overflow'
    console.log(this.name)
}

When I call this function, instead of printing the name 'Stack Overflow' Google Chrome console is returning 'undefined'.

Why is this behaviour? As I have read this keyword always refer to the current execution context then why it is not returning the name?

luk2302
  • 46,204
  • 19
  • 86
  • 119
HarshSharma
  • 590
  • 3
  • 6
  • 30

1 Answers1

1

You didn't add name to this object:

function returnName() {
    this.name = 'Stack Overflow'
    console.log(this.name)
}

If you want to create a variable and log it in returnName, you don't need this:

function returnName() {
    var name = 'Stack Overflow'
    console.log(name)
}
matrixersp
  • 460
  • 5
  • 13