1

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

3
  • 1
    Functions and presumably components are both just objects. JSON data is just a string. There’s nothing special about them. Commented Sep 22, 2018 at 22:20
  • 2
    They 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. Commented Sep 22, 2018 at 22:21
  • @jonrsharpe - You have the soul of a poet. Commented Sep 22, 2018 at 22:40

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.