Output the variable name to console - javascript

I am wanting to output the variable and variable name to console by just using the variable. This must be simple but I can't figure out how to do it. So I want the output I'd get from the below code but without hardcoding the variable name.
const myVar = 10
console.log('myVar',myVar)
//OUTPUT myVar, 10
SO just to make it clear I want the variable name to be programatically created from the variable NOT hardcoded 'myVar' as I want to automate this.
I HAVE TRIED
'[myVar]'
//doesn't work
myVar.name
//doesn't work
I HAVE BEEN ASKED TO EXPLAIN WHY
I am sick of writing
console.log('myVar',myVar')
I would like to create a function that takes in a variable to outputs what I want to the console.
I TRIED
const myVar = 10
const outVar = (myVar) =>{
console.log({somethingHere}, myVar)
}
//somethingHere is a placeholder for the correct syntax
outvar(myVar)
//expected Outcome myVar, 10

There is no way to know the variable name. You can make it as an object with the shorthand property names which as close as you can get to what you want. It is great for debugging.
const myVar = 10
const myVar2 = 4
console.log({ myVar })
console.log({ myVar, myVar2 })

Related

How to print out a label for each value in console.log()

I'm having trouble figuring out how to customize console.log() so that it automatically prints out the label for each argument I pass into it. For example, I often do something like this, so that it's clear what each log is printing out:
console.log('firstName: ', firstName);
I would love to be able to simplify this to:
my.log(firstName);
Is there any way to pass the variable names of the caller args into console.log()? Or is there another way to do this? My wish is that I don't have to type out the variable name twice, just the once. And ideally print out multiple arguments each with its own label on its own line in the console. I'm aware that I can access the arguments list, but I don't know how to un-eval() each argument to get just its variable name, if that makes sense. I'm hoping it's something super-easy I missed.
Doing it the way you want is impossible (the log function doesn't know what name you called things.)
The way I work around this is to use the object shorthand {firstName}to create a temporary object.
You can then either use .log or .table to display it:
const firstName = 'bob';
console.log({firstName});
console.table({firstName});
// It also works for multiple variables:
const lastName = 'smith';
console.log({firstName, lastName});
You could use console.table() to print things in a more readable form:
(Look in the real console to see it.)
var obj = {
firstName: "name",
lastName: "smith"
};
function log(obj) {
console.table(obj);
}
log(obj);
Try this :
var my = {
log : function(name) {
console.log('firstName: ', name);
}
};
my.log("Rohit");

How know variable name in javascript?

Suposse an function:
function get(){}
this will get an variable
var name = "Eduardo";
get(name);
function get(n) {}
And i want to show the name of the variable that was passed, without know this name.
function get(n) {
return getNameVariableFromValue(n); // Pseudocode for explain my question
}
so, i want the name of variable without previouslu knowing this name.
PD: My question is mainly to know, who is a variable in the window object, without know this name or value
Your question assumes that no two properties would ever have the same value, which is highly unlikely. But, making that wild assumption, you'd need to make the new window property explicitly rather than just declare a global variable and then you could use Object.keys() to enumerate all the key names of the window object, looking for the one that matches your value. When found, report the key name.
window.myGlobal = "Test";
Object.keys(window).forEach(function(key){
if(window[key] === "Test"){
console.log(key);
}
});
This code won't work in the Stack Overflow snippet environment due to sandboxing, but you can see it working here (make sure to have your developer's tools console open when running).
You can send the value as an object to the function and do something like below
function get(n) {
return Object.keys(n)[0];
}
var name ="Test1";
var name2 = "Test2"
console.log(get({name}))
console.log(get({name2}))

ID Element return when giving as parameter

I am making a website for school and we where working with function. Now i got a litle "problem"
i am using jquery to change the DOM and made a function where you can choose which location you are adding the element to.
Something like this:
function functioname(parameter){
console.log(parameter);
}
when i call this function like this:
functioname("#id");
i will return "#id";
But if i call it like this:
functioname (id);
I get return with the whole div and his children. How can this happen?
And why works this only with divs.
It isn't really a problem i was just wondering how this works.
Thanks in advance if somebody could explain what is happening here.
The window.id will find a DOM element whose id it matches. For example, window.mydiv will find:
<div id="mydiv"></div>
However, this not a recommended practice.
As a general rule, relying on this will lead to brittle code. Which IDs end up mapping to this API can vary over time, as new features are added to the Web platform, for example. Instead of this, use document.getElementById() or document.querySelector().
http://www.w3.org/html/wg/drafts/html/master/browsers.html#named-access-on-the-window-object
In the first function you are passing the string and in the second example you are passing the window object. Same as we pass an object with "this"
<div onclick= " functionname(this); "> </div>
here we get the complete object inside the function.
In first line of code "#id" you are passing the string. it's return the string also as you says.
in second you pass object id that you have earlier in your code. This is maybe why you got the different result.
Let's take a look at the window object. The window is pretty cool in that it allows you to declare global variables from anywhere on the fly. Take the following code for example
//the following three lines of code do the same thing
//create a global variable and store a value in it
window.a = 1;
window["b"] = 2;
var c = 3; //this one is most used though
function g() {
//the following three lines of code do not do the same thing
window.d = 4; //global
window["e"] = 5; //global
var f = 6; //local
}
g();
console.log(a); //prints 1
console.log(b); //prints 2
console.log(c); //prints 3
console.log(d); //prints 4
console.log(e); //prints 5
try {
console.log(f); //ERROR
} catch (err) {
console.log(err);
}
console.log(window.a); //prints 1
console.log(window.b); //prints 2
console.log(window.c); //prints undefined
console.log(window.d); //prints 4
console.log(window.e); //prints 5
console.log(window.f); //prints undefined
console.log(window["a"]); //prints 1
console.log(window["b"]); //prints 2
console.log(window["c"]); //prints undefined
console.log(window["d"]); //prints 4
console.log(window["e"]); //prints 5
console.log(window["f"]); //prints undefined
It is important to know that obj.prop === obj["prop"] is always true in JavaScript. That is why the last two sets of tests have the same results. Also important is prop === window.prop unless you declared prop using var prop;. This is because JavaScript secretly uses the special keyword using on the window variable at all times unless otherwise specified.
All browsers make DOM elements available via id using document.getElementByID but some browsers are nice enough to set up some variables for you so you don't have to write all that code. Imagine that a browser runs this script before any of your scripts do
(function(context) {
var tags = document.getElementsByTagName("*");
for (var i = 0; i < tags.length; i++) {
var tag = tags[i];
if (tag.id) {
context[tag.id] = tag;
}
}
}(window));
Which fills the window variable / global scope with tags that have ids.
Here are a bunch of examples. http://jsfiddle.net/Lk345zez/

JavaScript convert variable name into string

I have a function like:
function testFunction( option )
{
alert(option);
}
(the actual function does more than just answer the option)
And of course, it works if you do testFunction("qwerty");, or testFunction(myvar);, where myvar is a variable.
It does not work if I do testFunction(qwerty);, where qwerty is not a variable, as expected.
I was wondering if there is a way to make the function check to see if option is a variable or string (such as "qwerty" and myvar in the examples above) and if it is continue as normal and alert the string or the variable's value.
However, if it is not a variable or string, but is an undefined variable (such as qwerty in the example above) then I would like it to alert the name of the variable (qwerty in this case).
Is this possible?
Thanks!
Some more examples:
var myvar = "1234";
testFunction("test"); //alerts "test"
testFunction(myvar); //alerts "1234"
testFunction(qwerty); //alert "qwerty"
Your problem here is that testFunction(qwerty); will not even reach the function.
Javascript cannot interpret the variable 'qwerty' as it is not defined, so it will crash right there.
Just for fun, here's a way to do what you request, by catching the error thrown when you try to interpret an undefined variable :
function testFunction( option ){
console.log(option);
}
try {
var myvar = "1234";
testFunction("test"); //alerts "test"
testFunction(myvar);
testFunction(qwerty); //alert "qwerty"
}catch(e){
if(e.message.indexOf('is not defined')!==-1){
var nd = e.message.split(' ')[0];
testFunction(nd);
}
}
JSFiddle here
Bear in mind that you should absolutely never do that, instead, try using existing variables in your programs, it works better ;)

Put a variable between double quotes

I have a small question:
I have a function in javascript.
var func = function(variable)
{
result = variable;
}
If I call
func(rabbit);
I need the result to be "rabbit".
I cannot figure out how to put the variable between the two quotes.
Assuming rabbit is supposed to be a string:
func("rabbit");
If rabbit is actually a variable, then there's no way to do this because the variable (meaning the implementation's representation of a variable) isn't actually passed to the function, but rather its value is.
Actually there's an ancient way to retrieve the variable name.
var func = function(variable)
{
console.log(variable); // outputs "white"
console.log(arguments.callee.caller.toString().match(/func\((.*?)\)/)[1]); // outputs "rabbit"
}
rabbit = 'white';
func(rabbit);
See it running http://jsfiddle.net/Q55Rb/
You could do this
function whatever(input) {
return '\"' + input + '\"';
}
result should be in quotes
I could not tell from your question whether you wanted "rabbit" to be the property name, or the value. So here is both:
var func = function(variable) {
window[variable] = 'abc'; // Setting the variable as what is passed in
window.result = variable; // Normal
}
func('rabbit'); // Will set both window.rabbit to 'abc', and window.result to 'rabbit'
I wouldn't advise setting global variables, though. More info
Ok I thought that was my problem. Now I'm pretty sure that's not it but I have no clue what it is then.
I have this in my function:
defaults = {title :{'pan':-1,'left':0,'volume':0.30,'top':111}};
Where title is a variable from the function. But as a result I get title in defaults instead of the actual title stored in the variable named title. Do you understand me?

Categories