Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript A Real World Example

tal Shnitzer
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
8,303 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

//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
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);};

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

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