JavaScript - Call method and log into console

Viewed 38

I've created a method inside of an object constructor that is meant to switch the boolean value of one of the variables to the opposite when called. I cannot seem to get it to work when I display it in the console. This is my first time trying something like this, and although I know it is a simple fix I cannot seem to figure out what/where I went wrong.

function obj(string1, string2, bool) {
  this.string1 = string1;
  this.string2 = string2;
  this.bool = bool;
  
  this.toggleBool = function() {
    this.bool != this.bool; 
  }
}


var obj1 = new obj("text", "text", true);

console.log(obj1);
obj1.toggleBool();
console.log(obj1);

It is meant to print the original values in the console, then when I print it the second time it is meant to change true to false. Instead, it just keeps it as the original.

Thanks in advance.

1 Answers
  • You do not need extra function here all you need is just reverse the current passed boolean value in argument. this.bool = !bool; this statement will reverse the argument from true to false and false to true.

function obj(string1, string2, bool) {
  this.string1 = string1;
  this.string2 = string2;
  this.bool = !bool;
}

var obj1 = new obj("text", "text", true);

console.log(obj1);

Related