Declare variable name dynamically in javascript - javascript

In JavaScript I want to make a function which takes an argument and in this function a variable will be created whose name will be the value of the argument.
For example if user pass "jack" in the argument then in function I want a variable whose name is jack like:
var jack = "";

Typically, you won't need to do this. As Bergi pointed out, a local variable would usually suffice. However, in the event that you do need to use this technique, you could give the property to the window object:
function setVariable(userPassedString);
window[userPassedString] = "";
}
Don't use eval for this, ever, no matter how tempted you are to.

Creating local variables via a function is typically a bad idea. You could accomplish something similar by passing a local object around, e.g.
function setVar(o, name, value)
{
o[name] = value;
}
Then, inside your local scope:
var o = {};
setVar(o, 'jack', 123);
// o.jack contains 123
In this way, if the need would really arise (this is rarely required) to introduce global variables in this manner, you can always call the function like this:
setVar(window, 'jack', 123);
// now window.jack == jack == 123

The best that you can do about is to create an object and assigns the variable name to the keys of the created object like this -
var myvar={};
function create(var){
myvar[var]='values';
}

You could always use a dictionary. Here is a very simple stub:
function Dictionary(){
var container = {};
this.set = function(key, value){
container[key] = value;
}
this.get = function(key){
return container[key];
}
}
var vars = new Dictionary();
vars.set('foo', 'foo rocks');
vars.set('bar', 'bar rocks too');
console.log(vars.get('foo'));
console.log(vars.get('bar'));

To prevent using the window global array, you can create a local array which holds your variables.
function doSomething(var) {
var vars = {};
vars[var] = value;
}

Related

is there such thing as function.name for objects

So I was wondering if there is a way to use function.name but for objects.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name
What I mean by this is to have something like this:
function myFunction() {}
console.log(myFunction.name); // logs "myFunction"
// but like
var myObj = {};
console.log(myObj.name); // logs "myObj"
and if it is possible, how would it handle something like this?
var myObj = {};
var myObj2 = {};
console.log(myObj2.name); // logs "myObj" or "myObj2" or both?
Two things
Object don't have name property by default, unless you specify the same while defining the object,
for example
var myObj = {
name : "myObj"
};
In myObj2.name, myObj2 is not the name of the object, it is the name of reference (variable) to object.
Short answer? No.
On the other hand, as you may know, global variables are part of window variable. Therefore, you could do something like:
function findName(obj, scope){
if(scope === void 0){
scope = window
}
for (prop in scope) {
if(scope.hasOwnProperty(prop) && scope[prop] == obj){
return prop
}
}
}
NOTE: This is extremly inefficent way to get variable name!

Does JS prototype have access to the argument(s) passed to an object during initialization?

Everything is in the the title really... I know that functions created using prototype can't have access to private object data/functions, but what about having access to the arguments that were passed to the object when it was created ?
var Voice = function (word)
{
/*
I know I can obviously do something like : 'this.word = word;'
But I was wondering whether there is a standard way of calling an
argument from within a prototype function without having to do
the above ?
*/
};
Voice.prototype.speak = function ()
{
console.log({{word}});
};
x = new Voice('all I can say is this');
x.speak();
Thanks!
No.
The functions on the prototype weren't defined within the function that the variables are in scope for, so they don't have access to them.
You can store the variable as an object property and then read it back from there.
this.word = word;
Maybe like this:
var Voice = function (word) {
this.init_word = word;
};
Voice.prototype.speak = function (){
console.log(this.init_word);
};
x = new Voice('all I can say is this');
x.speak();

How do I access the variable name of an object that is a function argument in Javascript with jQuery?

var myObj = {
key: "element",
key2: "element2"
}
function stuff(obj) {
var a = obj;
console.log(a);
}
stuff(myObj);
How do I make stuff(myObj) console.log myObj, which is the name of the object? If I were to run this code, it would print that the argument myObj passed into stuff is an object and console.log its keys and elements. I want var a to store and console.log the name of the object instead of its contents, which in this case, is myObj.
You can't. JavaScript passes by value, there is no connection to the variable that was used to pass the object.
Take this example:
var foo = {};
var bar = foo;
window.baz = bar;
stuff(foo);
function stuff(obj) {
var a = obj;
console.log(a);
}
You now have 5 variables / properties which are all "names" for the same object.
If you need an object to have some kind of identifying name, then give it as a property.
var foo = { name: "foo" };
Use for-in loop to iterate through object. a and b are keys of the object which are mapped to id of the elements..
Try this:
var obj = {
a: "A",
b: "B"
};
for (var i in obj) {
$('#' + i).hide();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="a">A</div>
<div id="b">B</div>
<div id="c">C</div>
<div id="d">D</div>
It is possible! You can do something like this:
function stuff(obj) {
var a = Object.keys(window);
a.forEach(function(item, i, a) {
if (window[item] == obj)
{
console.log((item);
}
});
}
There is no (good) way to do that. The myObj variable has a pointer to the object in the memory. When you send myObj as parameter to a function, it will be sent by reference, so the obj parameter of your function will also have the pointer to the object in memory.
At this point the global variable myObj and local variable obj are synonyms for the same object. Modifying the property of one will also affect the other variable.
Theoretically there could be hundreds of variables pointing to the same object, but the object would never have any link back to any of the variables that point to it, so there is no way to retrieve the name of an object. There is no correct or original variable: all variables are identical no matter in what order they were linked to this object.
This said, of course if myObj is a global variable, it would be possible to compare your variable with all properties of the window object and then know which variable it was originally, but that's an awful waste of processing power. And it will only work with global variables.
So this should do the trick for global variable, but I strongly advise against doing this (most of all if it's a big project with lots of global variables). Still, if used during coding for debugging only, which I assume this is all about, it might be of some help:
function getVariableName(x) {
for (var i in window) {
if (window[i] === x) return i;
}
return false;
}
Attention: if you got more than one global variable pointing to this object, there is no way to know which of those variable names you will get back ... javascript does not define a fix order of enumerating properties of an object. The first match will be reported back!

Javascript: Use function as variable

Is there a way to use a variable name which has a function assigned to it, for example, to get the actual width of an element?
var xvar = function(){ return $('#y').width()}
And use it as
console.log(xvar);
Instead of
console.log(xvar());
Not with variables, but it is possible with properties on objects. It's called a getter.
var obj = {
get xvar() { return $('#y').width(); }
};
Then you can use:
obj.xvar; // will run the above function
(Theoretically, a way to use a variable getter is when an object's properties reflect the variables. For example, the window object.)
As long as your function returns String or Number this could be an alternative for non-ES5 environments:
var xvar = new function(id){
this.toString =
this.valueOf = function(){
return $(id).width()};
}('#y');
If I not mistake it will work because xvar will store reference to result of immediately-invoked function:
var xvar = (function() { return $('#y').width(); })();
console.log(xvar);
But after it you can't use xvar() version.

Javascript: Reference a variable name from the variable itself

I want to create a quick function that will console.log a variable name and the value. I'd like the result of the function to show in the console: foo: bar.
My basic idea for the function looks like this:
function varlog(var_name)
{
console.log(var_name + ": " + eval(var_name));
}
And I'd call is thusly:
function someRandomFunction()
{
var foo = "bar";
// ... some stuff happens
varlog("foo");
}
This works if foo is global, but doesn't work in the example provided. Another option that also only works globally is using window[var_name] instead of the scary eval.
I don't think what I'm asking is possible, but I figured I'd throw it out there.
I'm spending a lot of time attempting to be lazy. My current method is just console.log('foo: ' + bar); which works just fine. But now I just want to know if this is possible.
Some other questions I referenced in searching for this / creating what I have now:
Variable name as a string in Javascript
How to convert variable name to string in JavaScript?
Javascript, refer to a variable using a string containing its name?
How to find JavaScript variable by its name
--
Edit: I'd love to just call varlog(foo), if the name "foo" can be derived from the variable.
Solution - (for your actual use case) - console.log({foo})
In ES6 IdentifierReferences are being accepted as PropertyDefinitions on the ObjectLiteral's PropertyDefinitionList (see compatibility chart):
The variable name is being set to the Object's Property's key
and the variable value is being set to the Object's Property's value.
As console.log shows Objects with their Propertiy/ies' keys and values you can use that to see both your variable's name and value by invoking console.log({foo}).
Note that when you initialize a single anonymous object with several
variables as I did in the second console.log while they appear in
the same order as initialized here in the snippet's output they might
get reordered (alphabetically) elsewhere.
var testint = 3
var teststring = "hi"
var testarr = ["one", 2, (function three(){})]
var testobj = {4:"four", 5:"five", nested:{6:"six",7:"seven"}}
console.log({testint})
console.log({testint, teststring, testarr, testobj})
Answer - (to the question title) - Object.keys({foo})[0]
You can also use this shorthand Object Initializer together with Object.keys() to straightly access the variable name:
var name = "value"
console.log(Object.keys({name})[0])
The reason it doesn't work is because the variable foo is not accessable to the function varlog! foo is declared in someRandomFunction, and is never passed into varlog, so varlog has no idea what the variable foo is! You can solve this problem by passing the variable foo into the function(or using some sort of closure to make foo in the scope of varlog) along with its string representation, but otherwise, I think you are out of luck.
Hope this helps.
While I'm not aware of such a possibility, I'd wanted to share a small idea:
Object.prototype.log = function(with_message) {
console.log(with_message + ":" + this);
}
var x = "string";
x.log("x");
Like I said, a small idea.
Kind of combining a couple of anwers into a small function
Would this work for you?
const log = function() {
const key = Object.keys(this)[0];
const value = this[key];
console.log(`${key}: ${value}`);
}
let someValue = 2;
log.call({someVlaue}); //someValue: 2
Works with function too, even itself.
log.call({log});
// It would return the following
log:function() {
const key = Object.keys(this)[0];
const value = this[key];
console.log(`${key}: ${value}`);
}
I don't believe what you want to do is possible.
The best alternative I can think of is to pass an object to varlog that is basically a key-value hash:
function varlog(obj)
{
for (var varname in obj) {
console.log(varname + ": " + obj[varname]);
}
}
function someRandomFunction()
{
var foo = "bar";
// ... some stuff happens
varlog({foo: foo});
}
I loved #mhitza idea, so I'm making it a little bigger...
The downside is the need to use .valueto reach the variable content.
Object.prototype.log = function(message) {
if (message) console.log(this.name, this.value, message);
else console.log(this.name, this.value);
}
function nar (name, value) {
var o = {name: name, value: value};
this[name] = o;
return o;
}
// var globalVar = 1;
nar('globalVar', 1);
globalVar.log();
// > globalVar 1
globalVar.value += 5;
globalVar.log('equal six');
// > globalVar 6 equal six
var someFunction = function () {
// var localVar = 2;
nar('localVar', 2);
localVar.log('someInfo');
// > localVar 2 someInfo
};
someFunction();
Surprised to see no super simple solution yet.
let varname = "banana"
console.log(`${JSON.stringify({varname}).split('"')[1]}`)
Prints varname in the console

Categories

Resources