Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript A Real World Example

tal Shnitzer
PLUS
tal Shnitzer
Courses Plus Student 5,242 Points

in this video example where does the parameter "error" is defined?

the "error" parameter is used in the code on the below line. but where is it defined?

xhr.onerror = function(error){reject(error);};

2 Answers

Aaron Loften
Aaron Loften
12,864 Points

Its defined in the function declaration.

In Javascript, and many other languages, you define a function and also the expected arguments/parameters passed.

Saying "function someFunction(thing)" is declaring "thing" as an expected value right up front. :)

Like in the example below...

//this function is declaring three variables that it demands in order to run
function makeBurger(topping1, topping2, topping3) {
    alert("Here is your burger with " + topping 1 + ", " + topping2 + ", and " + topping 3);

}

//calling the following function would fail with an error because it only passes one value to the function
makeBurger("cheese");

//the following passes three values, even if only one matters
makeBurger("cheese", "", "");

In the example you provided, it looks like a data was sent, and after it was sent, a reply returns and if it contains an error, itll pass an error string through. This means it would fail if it DIDNT pass through a string because it is always expecting an error string, even if the error string is "unknown error occurred."

It would be roughly the same as saying...

//passing a string through the function
xhr.onerror("error - your code never went through :( ");
tal Shnitzer
PLUS
tal Shnitzer
Courses Plus Student 5,242 Points

thanks for your answer. it is my fault I didn't provide the whole code cause I thought that if I sent it via "get help"button in the video page the link will automatically be presented..

function getJSON(url){
  return new Promise(function(resolve, reject){
    var xhr = new XMLHttpRequest();
    xhr.open('GET', url);
    xhr.onreadystatechange = handleResponse;
    xhr.onerror = function(error){reject(error);};
    xhr.send();

    function handleResponse() {
      if(xhr.readyState === 4 && xhr.status === 200) {
        var employees = JSON.parse(xhr.responseText);
        resolve(employees)
      } else {
        reject(this.statusText);
      }
    };    
  });
};

I can't see where "error" is being passed.