Here is a break down:
line 1:
$(document).on('click', function(event) { ... });
binds on any click made in your document (DOM). make use that you unbind (.off('click', .....); after you used it. Otherwise it will be endlessly executing on every click.
line 2:
if (!$(event.target).closest('#menucontainer').length) {
event.target ===(equals) the element that is click in the dom.
.closest('#menucontainer') = get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree. Meaning: when there is clicked inside MenuContainer it will return an array with the first '#menucontainer' element. When there is click outside the MenuContainer it will return an Empty array. (no element found).
.length = The default behavior from JQuery is to return an empty array when nothing is found. If you put and empty array in a If statement it will return true. because its an Defined Object. Its defined as an Array. however the number 0 == false. thats with they put .length on the array. It will return 0 (false) when its empty of > 0 (true) when it found an element.
In JavaScript, everything is 'truthy' or 'falsy', and for numbers 0 (and NaN) means false, everything else true.
check NickG his link( Is there an "exists" function for jQuery? )