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
-
1Functions and presumably components are both just objects. JSON data is just a string. There’s nothing special about them.Sebastian Simon– Sebastian Simon2018-09-22 22:20:07 +00:00Commented Sep 22, 2018 at 22:20
-
2They can't contain a river, or or the feeling of joy. Ir doesn't make sense to say they can "contain JSON", if anything that would be a string or just regular arrays/objects/values. But they can refer to any value in JS.jonrsharpe– jonrsharpe2018-09-22 22:21:22 +00:00Commented Sep 22, 2018 at 22:21
-
@jonrsharpe - You have the soul of a poet.T.J. Crowder– T.J. Crowder2018-09-22 22:40:27 +00:00Commented Sep 22, 2018 at 22:40
2 Answers
Any value can be stored in a JavaScript variable. Values include:
- All primitives
- Object references
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.
Comments
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.