Put a variable between double quotes - javascript

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?

Related

Convert var to const javascript

Is it possible to convert a var to a const?
Say in a scenario like this:
var appname = ''
function setAppName(name) {
appname = name // can I convert this to const now?
}
Basically, this is for a parameter level. Parameter needs to be accessible throughout the file and I want to make it const after first assignment. Is this possible?
To add: If there is any other way besides creating an object with to contain this parameter, it would be better (for a more straightforward solution). I will be working on multiple parameters like this and freezing an object will cause the entire object to freeze. I am hoping to do this on the parameter level.
So either change the parameter to become const. OR (this one I dont think is possible) change the scope of the paramter to global:
function setAppName(name) {
const appname = name // can I change the scope and make this global?
}
Thanks.
Put your app name in an object and freeze it.
let appSettings = { name: "" };
function setAppName(name) {
appSettings.name = name;
Object.freeze(appSettings);
}
Freezing prevents adding, removing and modifying the values of the properties in your object so you should call Object.freeze only once after all other settings (if there are more variables you want to make constant) have been set.
You can do this using a object.
const globals = {
appname: ''
}
function setAppName(name) {
globals.appname = name;
Object.freeze(globals)
// After this point, value of appname cannot be modified
}
Thank you for all your inputs.
I was able to find a workaround for what I was trying to achieve.
var appname = ''
function setAppName(name) {
if (appname === '') {
appname = name // can I convert this to const now?
}
}
Although this doesnt convert it to const, I just added a guard on the setter and it will not be able to overwrite the value now (unless otherwise I am going to initialize again to an empty string).
It is not fool-proof, but this will address my need.
Thanks all!

Javascript variable is undefined outside if condition

I have defined a javascript variable but it returns undefined.
variable = "";
if(somecondition){
variable=myString.length;
}
alert(variable);
here variable returns undefined. If I keep the alert inside the if condition, I am able to get the value but its not working if I keep the alert outside the if condition.
Your myString does not have an property called length and hence you are getting undefined.
Usually, String, array has length property while objects don't have it.
Either you are invoking a wrong property or invoking it on a wrong data type or you have to define one yourself :P
Using var will do it:
var variable;
You need to declare and define your variable.
var variable = "";
if(somecondition) {
variable = myString.length;
}
alert(variable);
Are you missing the initialization of mystring?
Look at the following
var variable = '';
if (true) {
variable = 'Yes'
}
alert(variable);
This will show alert as Yes.
So in your case myString.length; is probably undefined
If variable isn't undefined in the function, it's because it is still equal to the initial value, "" (Empty String).
What I bet is happening, is myString is actually a number and not a string. Try the following and see if you are still having a problem:
variable = "";
if(somecondition){
variable=myString.toString().length;
}
alert(variable);

How to get property of an object to a variable in Javascript?

Learning from Codecademy. I have to get property of an object to a variable( not property value). This is messing with my brain from an hour.
Here is the code (I messed up a bit to find solution. Please use comments understand it correctly. I am confused to ask)
SCREENSHOT: http://prntscr.com/bcj94x
var james = {
job: "programmer",
married: false
};
// set to the first property name of "james"
var aProperty = james["job"];
// print the value of the first property of "james"
// using the variable "aProperty"
console.log(james["job"]);
console.log(aProperty);
I am getting: this in the console when run the script
programmer
programmer
Thanks
What result did you expect?
Defining your object using with the Javascript Object Notation (JSON for short) results in an object with two properties job and married.
This object is referenced via the variable james. Everytime you are using james in your code, you are dealing with the referenced object.
The same goes for var aProperty = james["job"];. Everytime, when your variable aProperty is used, it refers to the job property of the object referenced with james.
It is like saying: »From now on, when I say "aProperty", I mean the job-property of james«.
Your comment is a bit misleading:
// set to the first property name of "james"
In this case job is the first property. Correct would be set to the property named job.
From the above should the result be not unexpected.
console.log(james["job"]);
console.log(aProperty);
Both print programmer because aProperty is equivalent to james["job"] like saying Thomas or the person who wrote this is referencing to me and thus equivalent.
If you want to get the key associated to a given value, you can do this:
var james = {
job: "programmer",
married: false
};
Object.prototype.getKey = function (value){
for(var property in this){
if(this.hasOwnProperty(property)) {
if(this[property] === value )
return property;
}
}
};
console.log(james.getKey('programmer'));
It will give you "job".
So, using this function, you can simply write:
var aProperty = james.getKey('programmer');
You can use a for in loop to put the key values of the key : value pairs found in your james object inside an array called aProperty, and then print out your results in the console.
var james = {
job: "programmer",
married: false
};
var aProperty = [];
for (myvar in obj) {
if (obj.hasOwnProperty(myvar)) {
aProperty.push(myvar);
}
}
console.log(aProperty[0]);
console.log(aProperty[1]);

creating variable names from parameters in javascript

I was wondering if it is possible to create variable names from parameters passed to a function in javascript. Something like this:
function createVar(number) {
var "number" + number;
}
createVar(1)
I'm new to Stack Overflow and programming, so any help would be appreciated.
You could attach this to the window object, but note it will be global. For example:
function createVar(varName, value) {
window[varName] = value;
}
createVar("test", "Hello World");
alert(test); // Outputs "Hello World".
It is possible to interpret Object as associative array where you specify index and get value by name of index ( hash ):
var x = Array();
x[number] = value;
Single variable name is for programmer, and the code would be hard to maintain and understand when you set variable dynamically in code.
Honestly, I don't see why this would ever be useful, because every time you want to use the variable you'd have to search for it with your number argument.
However, you can do it, albeit not the exact way you had described:
function createVar(number){
eval("var number" + number.toString() + ";");
}
however, this variable will only be accessible within the function, to make it global assign to the window object:
function createVar(number){
window["number" + number] = 15; // creates "global" variable
}
As I've stated before, however, I don't see this being useful, [i]ever[/i], if you want to stratify values by numbers you'd be much better off with an array.

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 ;)

Categories