3

This question:

JavaScript check if variable exists (is defined/initialized)

does not regard the case of variables which have been declared but not defined (as opposed to undeclared and undefined). Specifically, if I want to check whether x has been declared, this:

typeof x == 'undefined'

will not do, because...

var x; //<- declared but undefined
// idontexist  not declared

typeof idontexist === typeof x; // evaluates to true

This has implications: if variable has been declared it wont become a global variable, whereas if a variable has not declared, it would become a global variable, possibly leading to memory leak.

So how do I check in javascript if undefined variable has been declared?

Regarding the implications of this, consider this code:

function test() {

  var x
  console.log(typeof x == typeof y); // true
  if (typeof x == 'undefined') {
     x = 3;
  } 
  if (typeof y == 'undefined') {
     y = 5; 
  }
}
test();
y; // 5
x; // Reference Error
Community
  • 1
  • 1
Muhammad Umer
  • 17,263
  • 19
  • 97
  • 168
  • 1
    Global variables and memory leaks have very little to do with each other. That said, it's really unclear why you could possible need to know this. You tell whether a variable is declared by *looking at the source code*. Are you doing some kind of code generation? – user229044 Aug 26 '16 at 15:31
  • 2
    With `try-catch`, I guess. – Sebastian Simon Aug 26 '16 at 15:32
  • good to know, i dont use strict mode. – Muhammad Umer Aug 26 '16 at 15:33
  • Agreed with @meagar, not sure what you're hoping for here - is there a real world example of this causing an issue? Memory leak is not an issue from this. – Liam MacDonald Aug 26 '16 at 15:33
  • memory leak does happen and so will conflicts, but just to stay on topic.. how would i check if variable has been declared or not. I am not asking about memory leak – Muhammad Umer Aug 26 '16 at 15:34
  • With ES6 you can use const variable so you can check and change this if not assign. – Anshuk Aug 26 '16 at 15:35
  • that only works for const since you have to define it right away. what about var and let – Muhammad Umer Aug 26 '16 at 15:36
  • @meagar you have assigned this question as duplicate, answers there clearly use `typeof` and as i explained in the body of this question the very first thing that is not what i want – Muhammad Umer Aug 26 '16 at 15:40
  • `window.hasOwnProperty('prop')` ? – Jose Hermosilla Rodrigo Aug 26 '16 at 15:40
  • 1
    An interesting question, but to all intents and purposes, this should be irrelevant at run-time. This seems like a job for an IDE rather than the code itself. – DBS Aug 26 '16 at 15:41
  • @JoseHermosillaRodrigo i thought about that but what if you are inside a function – Muhammad Umer Aug 26 '16 at 15:41
  • only solution that i know is to assign everything as null upon declaration. But it seems logical that there is a difference between a declared property and undeclared property so a way to check between them should exist. – Muhammad Umer Aug 26 '16 at 15:43
  • At least one answer there explicitly addresses this issue. – user229044 Aug 26 '16 at 15:58
  • 1
    Instead of checking `if (typeof x == 'undefined')` you can easily simplify this by just doing `x = x || 3` – Brian Glaz Aug 26 '16 at 16:38
  • What is the scenario for not knowing whether a variable is global or local? This is all known at compile time. It's not a runtime decision. – Raymond Chen Aug 26 '16 at 18:06
  • 1
    Simple way to find this in runtime is by using "use strict" directive in your JavaScript files. This will throw error if you have any undeclared variables. – Developer Aug 27 '16 at 09:39

2 Answers2

1

Trying to use an undeclared variable will throw a ReferenceError, so you can use a try catch block to determine if a variable has been declared.

var myVar;

try {
  myVar;
  console.log('myVar was declared.');
} catch(error) {
  if (error instanceof ReferenceError) {
     console.log('myVar was NOT declared');
  } else {
    console.log('Caught some other error.');
  }
}

try {
  notDeclared;
  console.log('notDeclared was declared');
} catch(error) {
  if (error instanceof ReferenceError) {
    console.log('notDeclared was NOT declared.');
   } else {
    console.log('Caught some other error.');
  }   
}
Todd Chaffee
  • 6,754
  • 32
  • 41
0

I had answered this several years ago..., can't remember where.

    "variablename" in this //> true : false

where this is any executional context which would otherwise have access to that variable name value.

    function exists( x ){ return x in this }
Bekim Bacaj
  • 5,707
  • 2
  • 24
  • 26