How many ways to create JavaScript variables?

QuestionsCategory: JavaScriptHow many ways to create JavaScript variables?
hf asked 7 months ago

Besides the following, what are other ways?

data = 1;
var data = 1;
const date = 1;
let data = 1;
1 Answers
christian Staff answered 7 months ago

There are plenty of ways although unusual.  In addition to what already said, here are others:
Using the “globalThis” property:

globalThis.data = "JavaScript";
console.log(data);

Using “this” and “self“:

this.data1 = "JavaScript";
self.data2 = "JavaScript";
console.log(data1, data2)

Using “window” object:

window.data = "JavaScript";
console.log(data);

Using “window.constructor.prototype” property:

window.constructor.prototype.data = "JavaScript";
console.log(data);

Using “this.constructor.prototype” property:

this.constructor.prototype.data = "JavaScript";
console.log(data);

Using “Object.prototype” property:

Object.prototype.data = "JavaScript";
console.log(data);

Using the Object instance’s “__proto__” property (two underscores _ _ ):

const obj1 = new Object();
obj1.__proto__.data = "JavaScript";
console.log(data);

const obj2 = {};
obj2.__proto__.data = “JavaScript”;
console.log(data);

Using the object literal’s “__proto__” property:

(new Object()).__proto__.data = "JavaScript";
console.log(data);

({}).__proto__.data = “JavaScript”;
console.log(data);

The above examples are possible due to JavaScript being a dynamically typed language and its confusing yet powerful inheritance and prototype chain. If you know another way, please comment and share below.  Also, any corrections are appreciated.

Your Answer

11 + 10 =