Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a variable is undefined versus it is undeclared in javascript?

I know that to find if a variable is undeclared in javascript, I can use if (typeof variable === 'undefined'). If I declare a variable as undefined (var variable = undefined), the if statement still returns true. Is it possible, in JavaScript, to find the difference between undeclared variables and variables with a value of undefined? I know that they are similar, but doing const variable = undefined and then variable = "something else" will throw an error, so they must be different.

const variable = undefined

if (typeof variable === 'undefined') {
  console.log('"variable" is undefined')
}

if (typeof undeclaredVariable === 'undefined') {
  console.log('"undeclaredVariable" is undefined')
}

I wouldn't like to use a try catch block because I want to be able to assign another constant based on this. I would like a solution like this: const isVariableDeclared = variable === undeclared, except undeclared does not exist in javascript. I know I can use let with a try catch block but am looking for something more elegant.

like image 868
Nathan Chu Avatar asked Oct 17 '20 19:10

Nathan Chu


People also ask

How check variable is undefined or not in JavaScript?

Answer: Use the equality operator ( == ) In JavaScript if a variable has been declared, but has not been assigned a value, is automatically assigned the value undefined . Therefore, if you try to display the value of such variable, the word "undefined" will be displayed.

What is the difference between undefined and undeclared variables in JavaScript?

Undefined: It occurs when a variable has been declared but has not been assigned with any value. Undefined is not a keyword. Undeclared: It occurs when we try to access any variable that is not initialized or declared earlier using var or const keyword.

How do you check if a null is undefined or undeclared?

null is a value of a variable and is a type of object. We use 'console. log();' and 'type of' to check if a variable is undefined or null. undeclared variables is a variable that has been declared without 'var' keyword.

What is the difference between undeclared & undefined?

Undeclared − It occurs when a variable which hasn't been declared using var, let or const is being tried to access. Undefined − It occurs when a variable has been declared using var, let or const but isn't given a value.


2 Answers

At least in the time of writing... No, it does not seem that you can do something like this:

var a = undeclared(var) ? 'undeclared' : 'undefined'

The reason is that you cannot pass an undeclared variable to a function; It raises an error, even in non-strict mode.

The best we can do, is this:

var barIsDeclared = true;

try { bar; }
catch (e) {
  if (e.name == "ReferenceError") {
    barIsDeclared = false;
  }
}

console.log(barIsDeclared);

Why?

Undefined: It occurs when a variable has been declared but has not been assigned with any value. Undefined is not a keyword.

Undeclared: It occurs when we try to access any variable that is not initialized or declared earlier using var or const keyword. If we use ‘typeof’ operator to get the value of an undeclared variable, we will face the runtime error with return value as “undefined”. The scope of the undeclared variables is always global.

For example:

  • Undefined:
var a;
undefined
console.log(a) // Success!
  • Undeclared:
console.log(myVariable) // ReferenceError: myVariable is not defined

When we try to log an undeclared variable, it raises an error. Trying to log an undefined variable does not. We make a try catch to check for just that.

'use strict'

Worth mentioning that adding 'use strict' in your code verifies that no undeclared variable is present, and raises an error if one is present.

function define() {
 //'use strict' verifies that no undeclared variable is present in our code     
 'use strict';     
 x = "Defined";  
}

define();

ReferenceError: x is not defined

Further reading:

  • Checking if a variable exists in javascript
  • What are undeclared and undefined variables in JavaScript?
  • JS Interview Question: What’s the difference between a variable that is: null, undefined or undeclared?
  • JavaScript check if variable exists (is defined/initialized)
  • Strict mode
like image 91
barhatsor Avatar answered Oct 05 '22 22:10

barhatsor


As others already did point to, the OP might want to distinguish between declared but undefined references and undeclared reference names ...

let declaredButUnassignedAndStrictlyEqualToUndefinedValue;
const declaredAndHavingAssignedTheUndefinedValue = undefined;

// There is no way of telling the above two (un/)assignements appart.

console.log(
  '(declaredButUnassignedAndStrictlyEqualToUndefinedValue === declaredAndHavingAssignedTheUndefinedValue) ?',
  (declaredButUnassignedAndStrictlyEqualToUndefinedValue === declaredAndHavingAssignedTheUndefinedValue)
);


// the `typeof` operator is of no help
// if it comes to distinguish between
// declared but undefined references
// and undeclared reference names ...

console.log(
  'typeof notDeclaredWithinScope :', typeof notDeclaredWithinScope
);

// ... just a try catch can do that.

try {
  notDeclaredWithinScope;
} catch (err) {
  // console.log(err.message);

  console.log('`notDeclaredWithinScope` does not exist within this scope.')
}
.as-console-wrapper { min-height: 100%!important; top: 0; }
like image 41
Peter Seliger Avatar answered Oct 05 '22 20:10

Peter Seliger