Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Why JavaScript 'var null' throw an error but 'var undefined' doesn't?
In JavaScript, var null throws a syntax error because null is a reserved keyword, while var undefined works because undefined is not a reserved identifier.
Reserved Keywords in JavaScript
JavaScript has reserved keywords that cannot be used as variable names. These include:
null true false if for while function var let const
Why 'var null' Throws an Error
When you try to declare a variable named null, JavaScript throws a syntax error:
// This will throw a SyntaxError var null = "some value";
SyntaxError: Unexpected token 'null'
Why 'var undefined' Works
undefined is not a reserved keyword in JavaScript. It's a global property, but you can still use it as a variable name (though it's not recommended):
var undefined = "Hello World"; console.log(undefined);
Hello World
Understanding null vs undefined
null represents an intentional absence of value, while undefined indicates a variable has been declared but not assigned a value:
var a;
var b = null;
console.log("a:", a);
console.log("b:", b);
console.log("typeof a:", typeof a);
console.log("typeof b:", typeof b);
a: undefined b: null typeof a: undefined typeof b: object
Best Practices
Avoid using undefined as a variable name even though it's allowed. It can lead to confusing code and unexpected behavior. Instead, use meaningful variable names:
// Bad practice var undefined = "some value"; // Good practice var userInput = "some value"; var result = null; // Explicitly setting to null is fine
// No output - just showing proper syntax
Conclusion
var null fails because null is a reserved keyword, while var undefined works because undefined is not reserved. However, avoid using undefined as a variable name for code clarity.
