javascriptfunctionglobal-variablesevaluatewindow-object

Why doesn't my javascript function throw up an error?


After invoking my function, I was startled that my function didn't throw up an error due having a variable & using a variable not define in the function's scope.

My question: Why doesn't my function throw an undefined,error, or the like? Shouldn't it throw up an error because "length" isn't in my function's parameter? I am aware that if I switch "length" to "height" it will work.

If someone could explain how javascript interprets this function in a step-by-step manner that would help me. Here is my code:

function areaRectangle(width, height) {
   aRectangle = width * length;
   console.log("The area of the rectangle is: " + aRectangle);
}
areaRectangle(10, 7); # The area of the rectangle is: 0

Solution

  • This depends on which environment you execute this function in.

    If you executed this in the browser, it seems like there is a length property in the global context which evaluates to a numeric value. When you execute your function in the console and it tries to access length, since length is not defined within your function, the JavaScript engine will look up the length variable in the global context (because of closure).

    If you executed this in Node, you'll notice that an error gets thrown because the global context in Node doesn't have a length property.