BxtchCraft
BxtchCraft

Reputation: 488

What does it mean when something is "not defined" when using JavaScript?

Recently, I've been learning JavaScript. I'm coming across a few JavaScript errors that say "__ is undefined" - What exactly does this mean, and why is this coming up? I'm looking more or less for an explanation on why this error is occurring and what can be done to fix it, or why it's generally occurring in the first place.

For example: Here are two functions (validate and onSearch) --- When I try to run "onSearch", I get the Ran SEARCH... trace in the console, however it disappears. Additionally, when I run it through JSHero (trying to debug), it tells me that "onSearch" is undefined, and I'm curious as to why.

I've go some experience developing with ActionScript, but I'm totally new to JavaScript. I'd really appreciate your input and explanation regarding what this actually means. Thanks you.

function validate(query){
    console.log("Ran VALIDATE...");
    // Trim whitespace from start and end of search query
    while(query.charAt(0) === " "){
        query = query.substring(1, query.length);
    };

    while(query.charAt(query.length-1) === ""){
        query = query.substring(0, query.length-1);
    };

    console.log("Query length:",query.length);
    console.log("Beginning conditional...");
    // Check search length, must have 3 characters
    if(query.length < 3){
        console.log("Display alert...");
        alert("Your search query is too small, try again.");

        // (DO NOT FIX THE LINE DIRECTLY BELOW)
        searchInput.focus();
    }else{
        console.log("Searching query...");
        onSearch(query);
    };
};

// Finds search matches
function onSearch(query){
//var search = function(query){

    console.log("Ran SEARCH...");
    // split the user's search query string into an array
    var queryArray = query.join(" ");

    // array to store matched results from database.js
    var results = [];

    // loop through each index of db array
    for(var i=0, j=db.length; i<j; i++){

        // each db[i] is a single video item, each title ends with a pipe "|"
        // save a lowercase variable of the video title
        var dbTitleEnd = db[i].indexOf('|');
        var dbitem = db[i].tolowercase().substring(0, dbTitleEnd);

        // loop through the user's search query words
        // save a lowercase variable of the search keyword
        for(var ii=0, jj=queryArray.length; ii<jj; ii++){
            var qitem = queryArray[ii].tolowercase();

            // is the keyword anywhere in the video title?
            // If a match is found, push full db[i] into results array
            var compare = dbitem.indexOf(qitem);
            console.log("Compare:",compare);
            if(compare != -1){
                results.push(db[i]);
            };
        };
    };

    console.log("Hello");
    results.sort();

    // Check that matches were found, and run output functions
    if(results.length === 0){
        noMatch();
    }else{
        showMatches(results);
    };
};

EDIT** "db" is defined in an external file. It's just an array of URL's. It's still saying it's not defined as well, which is what I'm asking.

How do you define 1) A variable 2) A function

Upvotes: 0

Views: 11044

Answers (3)

Oriol
Oriol

Reputation: 288080

Your problem

The problem is not that onSearch is undefined, but it uses a variable db which is undefined.

Cases

(From now on I will assume qwertyuiopasddsghjdsvjkfhjkl is not declared)

You see undefined errors when:

  • You use variable you have not declared.

    qwertyuiopasddsghjdsvjkfhjkl; // ReferenceError: qwertyuiopasddsghjdsvjkfhjkl is not defined
    
  • You use a property on a declared but undefined variable: var a; a.b; // TypeError: a is undefined

A variable is undefined when:

  • (Error) You have not declared it

    // qwertyuiopasddsghjdsvjkfhjkl is undefined
    qwertyuiopasddsghjdsvjkfhjkl; // ReferenceError: qwertyuiopasddsghjdsvjkfhjkl is not defined
    
  • (No error) You have declared it but it has no value

    var a; //a is undefined
    
  • (No error) You assign a variable to void(0) (you can change 0 with everything) or and unmodified undefined

    var a = undefined; //a is undefined
    var a = void(0); //a is undefined
    undefined = 'abc';
    var a = undefined; //a is NOT undefined
    

How to check

If you don't know if a variable is undefined, you can use

  • typeof myVar === 'undefined'

    It returns true if:

    • myVar is not declared
    • myVar is declared but is undefined

    It returns false if myVar is declared and myVar is not undefined

  • myVar === void(0)

    It returns true if myVar is declared and myVar is undefined

    It returns false if myVar is declared and myVar is not undefined

    It throws an error if myVar is not declared

  • myVar === undefined

    It's the same as myVar === void(0) if undefined has not been modified.

  • !myVar, if(myVar)

    It returns true if myVar is declared and

    • myVar is undefined
    • or
    • myVar is falsy (null, 0, false, '')

    It returns false if myVar is declared and myVar is truthy

    It throws an error if myVar is not declared

Upvotes: 0

T.J. Crowder
T.J. Crowder

Reputation: 1074178

If you get a TypeError along the lines "Blah is undefined" or "cannot read property foo of undefined", it means that you have a variable or property that has the value undefined, which is the default value for a variable until you assign something to it.

This is as opposed to having a variable you haven't defined yet and trying to read its value, which will fire a ReferenceError instead.

For instance, consider the below:

var foo;
console.log(foo.bar); // "TypeError: Cannot read property 'bar' of undefined"

The foo variable exists, but its value is undefined, so trying to read a property from it causes an error.

Contrast that to:

console.log(missing); // "ReferenceError: missing is not defined"

Here, the symbol missing is not defined; the engine has no idea what you're talking about. This usually indicates a missing var statement.

Side note: JavaScript has a very surprising behavior if you assign to a variable you've never declared (in ES3 or in ES5 in "loose" mode): It creates a global variable. I call this The Horror of Implicit Globals. It means that if instead of console.log(missing); above, I did this:

missing = "foo";

...I'd be creating a new global variable, even if that code is within a function. Thankfully, in ES5, we can use "strict" mode, which makes this the ReferenceError it always should have been. :-)

Upvotes: 2

CaptainCarl
CaptainCarl

Reputation: 3489

It usually means that the 'thing' you're requesting does not exist(or atleast can't be found by the function requesting it). This can be a variable, object or a function.

In the case of the onSearch you're talking about is that the function can't be found, most likely. It could be that the file with the function in it is loaded after the file requests it(So onSearch is in b.js, the one requesting it is in a.js. a.js is in your <head> before b.js). Therefore it's not yet present, since javascript files load linear.

Upvotes: 0

Related Questions