How can I check whether a variable is defined in JavaScript?

JavascriptDomUndefined

Javascript Problem Overview


How to check whether a JavaScript variable defined in cross-browser way?

I ran into this problem when writing some JavaScript utilizing FireBug logging. I wrote some code like below:

function profileRun(f) {
	// f: functions to be profiled
	console.profile(f.constructor);
	f();
	console.profileEnd(f.constructor);
}

It works fine in FireFox/FireBug, but it reports error in IE8 RC1. So, I'd like to do some checking whether console variable exists in the execution environment.

Below code works fine in FireFox, but not in IE8 RC1.

function profileRun(f) {
	if (console != undefined) {
		console.profile(f.constructor);
	}

	f();

	if (console != undefined) {
		console.profileEnd(f.constructor);
	}
}

However, if I do it this way. It works in IE8 RC1. Why?

function profileRun(f) {
	if (window.console != undefined) {
		console.profile(f.constructor);
	}

	f();

	if (window.console != undefined) {
		console.profileEnd(f.constructor);
	}
}

Is there any cross-browser way to check it?

Javascript Solutions


Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMorgan ChengView Question on Stackoverflow