Defining a variable and then calling it (undefined)

undefined javascript
javascript undefined error
global-variable-undefined pylint
javascript object property exists but is undefined
javascript global variable undefined
javascript check undefined
typeof javascript
javascript check undefined or null

I'm defining a const variable called filteredRecipes and I'm trying to use it to setState. The console is reporting that filteredRecipes is undefined,

Uncaught ReferenceError: filteredRecipes is not defined

I can't see what I'm doing wrong? Any help is greatly appreciated.

updateRecipeList () {
    const filteredRecipes = fetch('http://www.***.co.uk/rest/recipes.json')
        .then(res => res.json())
        .then(json => {

            json.results.filter(

                function (recipe) {
                    return (
                        this.state.currentRecipe === "" || recipe.pagetitle.toLowerCase().indexOf(this.state.currentRecipe.toLowerCase()) !== -1
                    )
                }.bind(this)

            );

        });

    this.setState({
        recipes: filteredRecipes
    });
}

The reason why is because your this.setState is outside of the Promise, meaning that I will not wait for the Promise to finish before trying to execute that code. Which means that the variable will be undefined.

You can solve this by putting it inside the promise like so:

updateRecipeList() {
  const filteredRecipes = fetch('http://www.***.co.uk/rest/recipes.json')
    .then(res => res.json())
    .then(json => {
      json.results.filter(
        function(recipe) {
          return (
            this.state.currentRecipe === "" || recipe.pagetitle.toLowerCase().indexOf(this.state.currentRecipe.toLowerCase()) !== -1
          )
        }.bind(this)
      );
      this.setState({
        recipes: filteredRecipes
      });
    });


}

The Undefined Defined Variable, If you call the function after declaring and initialising the global variable: var i=20 test();. then everything works as you would expect and the alert displays the  Stack Overflow Public questions and answers; Teams Private questions and answers for your team; Enterprise Private self-hosted questions and answers for your enterprise; Talent Hire technical talent

You have to do it at the end of the Promise-chain:

updateRecipeList() {
    return fetch('http://www.***.co.uk/rest/recipes.json')
        .then(res => res.json())
        .then(json => {

            // you also missed `return` here    
            return json.results.filter(

                function(recipe) {
                    return (
                        this.state.currentRecipe === "" || recipe.pagetitle.toLowerCase().indexOf(this.state.currentRecipe.toLowerCase()) !== -1
                    )
                }.bind(this)

            );

        })
        .then(filteredRecipes => {

            this.setState({
                recipes: filteredRecipes
            });

        });
}

I also refactored your code just a little bit, I hope you don't mind. :)

updateRecipeList() {
    return fetch('http://www.***.co.uk/rest/recipes.json')
        .then(res => res.json())
        .then(json => {
            if (this.state.currentRecipe !== "") {
                const currentRecipe = this.state.currentRecipe.toLowerCase()
                const filteredRecipes = json.results.filter(recipe => (
                    recipe.pagetitle.toLowerCase().includes(currentRecipe)
                ));

                this.setState({ recipes: filteredRecipes });
            }
            else {
                this.setState({ recipes: json.results });
            }
        });
}

undefined, The global undefined property represents the primitive value undefined. A variable that has not been assigned a value is of type undefined . been declared before if (y === void 0) { // throws Uncaught ReferenceError: y is not defined } missing name after . operator · SyntaxError: missing variable name  If you misspell a MATLAB function, a suggested function name appears in the Command Window. For example, this command fails because it includes an uppercase letter in the function name: Undefined function or variable 'accumArray'. Did you mean: >> accumarray. Press Enter to execute the suggested command or Esc to dismiss it.

updateRecipeList() {
  fetch('http://www.***.co.uk/rest/recipes.json')
    .then(res => res.json())
    .then(json => {
       const result = json.results.filter(recipe => {
           return (
            this.state.currentRecipe === "" || recipe.pagetitle.toLowerCase().indexOf(this.state.currentRecipe.toLowerCase()) !== -1
          );
        }
       this.setState({ recipes: result });
   );
 });
}

This is because this thread is running async and you need for the promise to execute when you set your setState.

Variable Scope, A global variable has global scope -- it is defined everywhere in … be called unassigned, to distinguish it from the more serious kind of undefined variable that​  Click the Variable View tab in the lower-left corner of the Data Editor window. Type [Name] in the first cell under the Name column, and then press the Enter key. Under the Type column, click Numeric, and then click the Ellipses button that appears next to it. The Variable Type dialog box will open.

This happens because fetch is async and here are the ways you can do that either by setting state in then portion:

updateRecipeList() {
const self = this;
fetch('http://www.***.co.uk/rest/recipes.json')
.then(res => res.json())
.then(json => {
    const filteredRecipes = json.results.filter(recipe =>
        self.state.currentRecipe === "" ||  recipe.pagetitle.toLowerCase().indexOf(self.state.currentRecipe.toLowerCase()) !== -1);

   self.setState({ recipes: filteredRecipes });
});

} or you can use ES7 async function for fetching the result :\

async updateRecipeList() {
  const res = await fetch('http://www.***.co.uk/rest/recipes.json');
  const recipies = await res.json();
  const filteredRecipes = recipies.results.filter(recipe =>
     this.state.currentRecipe === "" ||recipe.pagetitle.toLowerCase().indexOf(this.state.currentRecipe.toLowerCase()) !== -1

   this.setState({ recipes: filteredRecipes });

}

Testing if a Variable Is Defined - Python Cookbook [Book], Testing if a Variable Is Defined Credit: Hamish Lawson Problem You want to take Then it's easy to test whether a variable is bound to None : to initialize undefined variables; for a powerful and interesting example, see Recipe 5.24. In this variation, the call to some_operation is also covered by the exception handler,  Define Variables In VBA: How To Declare Variables And Assign Them Expressions By J.A. Gomez When thinking about the main purpose of Visual Basic for Applications, I usually go to the following quote by one of my favorite Excel authors, John Walkenbach.

Null and Undefined, It means we have defined a variable but have not assigned any value yet, pass less arguments in function call then, that parameter will have undefined value. For definition without an initializer: variables with static storage duration are implicitly initialized with NULL (all bytes have the value 0); the initial value of all other variables is undefined. Variable Declaration in C++. A variable declaration provides assurance to the compiler that there is one variable existing with the given type and name so that compiler proceed for further compilation without needing complete detail about the variable.

The Ultimate Guide to JavaScript Variables: var, let, and const , The message variable is declared and hold a special value undefined . After declaring a variable, you can assign the variable a string as follows: message = "​Hello"; ES6 introduced a new scope called block scope. If you declare a variable  In computer programs, variables are often declared without a value. The value can be something that has to be calculated, or something that will be provided later, like user input. A variable declared without a value will have the value undefined.

JavaScript Variables, Creating a variable in JavaScript is called "declaring" a variable. The variable carName will have the value undefined after the execution of this statement:  A variable can have a short name (like x and y) or a more descriptive name (age, carname, total_volume). Rules for PHP variables: A variable starts with the $ sign, followed by the name of the variable. A variable name must start with a letter or the underscore character. A variable name cannot start with a number.

Comments
  • I mean this will probably do what OP wants, but why is filteredRecipes undefined in the original version? It should have the value of the (unresolved) Promise object returned by fetch
  • Also you never assign anything meaningful to "filteredRecipes" either so it will still be undefined where you use it.
  • Exactly. Until the fetch finishes it basically returns nothing, so the value of the variable will be undefined.
  • That doesn't make any sense. fetch() returns a Promise immediately, before it "finishes", you couldn't call chained then()s otherwise. It's the foundation of composable asynchronous code.
  • You don't assign the result of .filter to any variable.