Home > Net >  variable value is not changing after going through the function which changes the value?
variable value is not changing after going through the function which changes the value?

Time:01-31

I want to change the value of the variable after going through the function but it's not changing, I check there is no solution given on internet for this, down there was the code and I was expecting it to change the value of filterName but it doesn't change, it works if I not use if statement but they are important for checking the condition. and one more thing that text parameter is important in the showFilter function this was my react code but I was getting problem in JavaScript so I am asking it as JavaScript question please help me.


let show = false;
let text = "Color";

  let filterName;
  let filterName =''; // I tried this way too but it doesn't work.
  const showFilter = (text) => {
    if (show === true) {
      show = false;
    } else {
      show = true;
      if (text == 'Color') {
        filterName = 'color'; // the value should change here
      } else if (text === 'Price') {
        filterName = 'price';
      } else if (text === 'Brand') {
        filterName = 'brand';
      } else if (text === 'All Filters') {
        filterName = 'All Filters';
      }
    }
  }


alert(filterName); // it should have to be 'color' but it's undefined.


CodePudding user response:

let show = false;
let text = "Color";

let filterName;
const showFilter = (text) => {
    if (show === true) {
        show = false;
        return;
    }
    show = true;
    switch (text) {
        case 'Color':
            filterName = 'color'; // the value should change here
            break;
        case 'Price':
            filterName = 'price';
            break;
        case 'Brand':
            filterName = 'brand';
            break;
        case 'All filters':
            filterName = 'All filters';
            break;
        default:
            break;
    }
}
showFilter(text);

alert(filterName);

Your code works just fine. You just need to call your method before calling the alert.

CodePudding user response:

First you declared filterName variable twice, other thing you should call your function showFilter(..), Here the result:

let show = false;
let text = "Color";

  let filterName  '';
  const showFilter = (text) => {
    if (show === true) {
      show = false;
    } else {
      show = true;
      if (text == 'Color') {
        filterName = 'color'; // the value should change here
      } else if (text === 'Price') {
        filterName = 'price';
      } else if (text === 'Brand') {
        filterName = 'brand';
      } else if (text === 'All Filters') {
        filterName = 'All Filters';
      }
    }
  }

showFilter(text);
alert(filterName); // It shows 'color'

  • Related