In javascript I have an option for log output that allows an element/selector to be used to specify where to output log/error messages. The output is formatted upon initialization like so:
var $messageOutput = options.messageOutputElement ? $(options.messageOutputElement) : null;
and it is used later on through a log function:
function outputMessage(msg)
{
if ($messageOutput !== null)
{
messageNum++;
var $messageOutput = $(options.messageOutputElement);
var html = $messageOutput.html();
html += '<b>' + messageNum + '</b><br/>' + msg + '<br/>';
$messageOutput.html(html);
$messageOutput.scrollTop($messageOutput[0].scrollHeight);
}
}
The problem is that even when $messageOutput === null, the if statement inside outputMessage() falls through. I’ve verified with Chome’s debugger that $messageOutput indeed equals null. And indeed it steps into the if statement anyway.
Can anyone give me any insight as to why this might be happening? Thanks in advance for any input on this matter.
By declaring “var $messageOutput” in the scope of a function, you stop referencing the variable in the global scope. So, instead of referring to that, it refers to a variable that is yet to be set within the function body, which is undefined, not null. You should probably remove the “var” part of “var $messageOutput = $(options.messageOutputElement);”, which will instead make the function refer to the $messageOutput outside the function.
To elaborate a bit:
“var” creates a new variable within the scope you are in, and to add to the confusion something like “var foo = function” behaves differently than “function foo”. Here are a few fun cases & explanations for your reading pleasure:
What you also sometimes have to watch out for is that you can reference a function before declaration outside of the global scope, depending on how it’s declared. For example:
A conventional function declaration can be made anywhere and referenced anywhere, but assigning a function to a variable means it can’t be referenced until the line has been executed.