Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 376
Clifford Fajardo Avatar asked Dec 08 '22 05:12

Clifford Fajardo


2 Answers

Because instead of an argument or variable it uses window.length property which happens to be 0.

like image 88
a sad dude Avatar answered Dec 17 '22 16:12

a sad dude


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.

like image 41
wmock Avatar answered Dec 17 '22 14:12

wmock