Reputation: 111
I know they can contain primitive data types and objects. And since I've been programming in react, I know they can contain objects, components, and even json. Is there any limitations on javascript variables? var/const/let
Upvotes: 1
Views: 196
Reputation: 1074425
Any value can be stored in a JavaScript variable. Values include:
Almost everything is an object in JavaScript. Notably, functions are objects (including React stateless functional components [SFCs] and React components, which are constructor functions), and so a variable can contain a reference to a function:
function foo(msg) {
console.log("foo: " + msg);
}
function bar(msg) {
console.log("bar: " + msg);
}
const f = Math.random() < 0.5 ? foo : bar;
f("Hi");
You have a 50/50 chance of seeing "foo: Hi" or "bar: Hi" with that code.
There are only a few things I can think of that a variable cannot contain:
Operators. E.g. this is not valid:
// NOT VALID
const op = Math.random() < 0.5 ? + : -;
console.log(10 op 5);
...although it's easy to get the same effect with functions:
const op = Math.random() < 0.5
? (a, b) => a + b
: (a, b) => a - b;
console.log(op(10, 5));
Execution contexts or lexical environments, but only because nothing ever exposes a reference to them in code.
Memory locations, because (again) nothing ever exposes them in code.
...and even json
JSON is a textual notation for data exchange. (More here.) If you're dealing with JavaScript source code, and not dealing with a string, you're not dealing with JSON.
Upvotes: 3
Reputation: 421
Variables are the way to address all objects. JavaScript is an Object-based language (String, Number, etc. are all Objects with different prototypes).
For example, a var
can hold: true, undefined, null, "string", `template`, {}, [], NaN, 7, infinity, /abc/
There aren'y any limitations I can think of.
Upvotes: 0