How many ways to create JavaScript variables?
Besides the following, what are other ways?
data = 1;
var data = 1;
const date = 1;
let data = 1;
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.
You must log in to post a comment.
You must log in to post a comment.