0

My Asp masterpage has this code:

<script>
    if (theForm !== undefined) { // <<== line 746: error
        theForm.onsubmit = ...bla bla... ;
    }
</script>

The Chrome console reports the error:

Uncaught ReferenceError: theForm is not defined   bla.aspx:746

My question is: is this a wrong way of detecting if a name is undefined? Or is this handled differently by Chrome?

(NB: Firefox console does not report an error, but still stops processing following JS code of this script block)

Roland
  • 4,619
  • 7
  • 49
  • 81

2 Answers2

2

The message Uncaught ReferenceError: theForm is not defined

should be interpreted as

theForm is not declared

Why? Basically, a variable can be undefined (but declared) and can be not declared at all.

Example

  1. Declared and undefined

var foo;        // if a value would be assigned (i.e.: var foo = 3), then it wouldn't be undefined
console.log(foo);
  1. Not declared (it will throw an error)

console.log(foo); // <-- foo was never declared

How to fix it?

Use typeof like this:

  console.log('Is undefined:', typeof foo === 'undefined');
lealceldeiro
  • 14,342
  • 6
  • 49
  • 80
  • I had case 2,but a run-time ReferenceError, not a compile error. Also, dgeare answered faster, so I accepted his answer, although I appreciate your code snippets – Roland Aug 14 '18 at 15:16
  • @Roland, thanks for pointing that out. I updated the answer for avoiding any misleading understanding :) I'm glad you found useful the snippets. Don't worry about checking the answer as accepted. I appreciate the upvotes too :) Sometimes a more elaborated post takes more time than other. – lealceldeiro Aug 14 '18 at 15:20
  • Good sport, thanks. Your first sentence in the answer is the key. You could have submitted your short answer to be first,then edit to elaborate on it :-) – Roland Aug 14 '18 at 15:33
1

There is a distinction between a variable being declared but having a value of undefined and a variable that was never even declared. I'm guessing your scenario is the latter. Use the typeof operator for this.

if(typeof(theForm) !== 'undefined'){ //typeof returns a string
dgeare
  • 2,618
  • 5
  • 18
  • 28
  • 3
    `typeof` isn't a function so it doesn't need parentheses. – JLRishe Aug 14 '18 at 15:03
  • 1
    @JLRishe I'm aware, thank you. But it takes them all the same and I prefer to use them because I feel it improves readability. – dgeare Aug 14 '18 at 15:07
  • @dgeare still strange that `if(undeclaredvar)` causes a ReferenceError and probably `somefunction(undeclaredvar)` too, while `typeof(undeclaredvar)` is fine. `typeof undeclaredvar ` is perhaps more clear that it is not a function. Comparing with a hard-coded string is kind of a hack,why can't we just write `if (defined somevar)` ? – Roland Aug 14 '18 at 15:42