-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
  • 50,400
  • 22
  • 92
  • 131
HarshSharma
  • 612
  • 3
  • 8
  • 31

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
  • 525
  • 6
  • 14