That's not true. In JavaScript there is no block scope, only function scope*. All variables introduced in a function are hoisted up to the top of the function.
So this code:
function prepForDrag(obj, event) {
if (event = "undefined") {
var event = obj || window.event;
}
// ...
}
gets interpreted somewhat like this:
function prepForDrag(obj, event) {
var event;
if (event = "undefined") {
event = obj || window.event;
}
// ...
}
As Marcel Korpel's pointed out, declaring variable event
is unnecessary in this case because event
is already a local variable since it's a function parameter.
function prepForDrag(obj, event) {
if (event = "undefined") {
event = obj || window.event;
}
// ...
}
For futher details, read Ben Cherry's article on JavaScript Scoping and Hoisting.
Nevertheless there are two additional problems in your code.
In the condition you used the =
assignment operator instead of the ==
comparision operator. So the condition always evaluates to true.
If you want to check whether a function argument was given, use the typeof event == 'undefined'
statement.
And I'm afraid there is even one more issue here. What is the purpose of the condition? Does argument obj
anything to do with event
? Modern browsers pass an event object to the event handler function as argument but some do not. To avoid the problem, the following pattern tends to be used:
function prepForDrag(e) {
var event = e || window.event;
// ...
}
*NB: there is a let
statement introduced in JavaScript 1.7 that provides block scope inside functions. Currently it's only supported in Firefox.