Bikram Kumar
Bikram Kumar

Reputation: 443

Why does setting the condition of an variable to be undefined give an error?

I want the function to run only once on the first click and no more. But I get an error that someVar is not defined, that is what I have included in the condition. Why is it giving the error? How to solve this?

button.onclick = function () {
  if (someVar == undefined) {
    console.log("Hi");
    someVar = 1; 
  }
}

Upvotes: 0

Views: 44

Answers (2)

ulou
ulou

Reputation: 5863

this approach (this references to onClick function):

const button = document.querySelector('button')

button.onclick = function () {
  if (this.someVar == undefined) {
    console.log("Hi");
    this.someVar = 1; 
  }
}
<button>button</button>

Global variable approach:

const button = document.querySelector('button')

let someVar = undefined;

button.onclick = function () {
  if (someVar == undefined) {
    console.log("Hi")
    someVar = 1;
  }
}
<button>button</button>

Upvotes: 2

Michael Kr&#246;schel
Michael Kr&#246;schel

Reputation: 341

Have you defined the someVar as a global Variable? use it like this =>

var someVar = undefined;
button.onclick = function () {
  if (this.someVar == undefined) {
    console.log("Hi");
    this.someVar = 1; 
  }
}

Upvotes: 1

Related Questions