Change the value of an evaluated var in JavaScript - javascript

I have a var containing a JSON string. (Here I won't parse it because it is not the main problem)
var variable = '{"name":"Johnny Appleseed"}';
var string = "variable";
I evaluate the string.
var evaluatedstring = eval(string);
Now I would like to delete the value of the var variable.
variable = undefined;
If I do:
console.log(evaluatedstring)
It works fine and returns me the JSON string as:
{"name":"Johnny Appleseed"}
But if I do:
evaluatedstring = undefined;
Of course it doesn't work.
eval(string) = undefined;
doesn't work either. (Returns the error Uncaught ReferenceError: Invalid left-hand side in assignment)
How can I delete the content that via the evaluated var?
No jQuery, please.
On Chrome 50+ so not a problem with the browser.

If you're working in the browser: Global variables in JavaScript are created as properties of the window object. Therefore, what you're trying to do can be done like this:
var variable = 'some variable';
var variableName = 'variable';
window[variableName] = undefined;
variable === undefined // Will now be true
However, just the fact that this is possible doesn't mean it's a good idea - in fact, it's just the opposite, it's bad style and will probably confuse anyone looking at your program to no end. If this is really necessary for your algorithm to work, you might want to rethink your data architecture. If this is just a scoping issue (you don't want that variable to pollute your global namespace), an IIFE will likely solve your problem.

Related

Why is `s.len` undefined (and not 4) while `s` has the value `test`? - JavaScript

I am puzzled with this one. I have the following code.
var s = "test";
s.len = 4;
var t = s.len;
The question is why the variable t has a value of undefined.
If you check the s.len after that code it is undefined.
If you check s the value is test. Not sure what is going on here. I am sure there is an explanation, but can't get my head around that and don't know how to search that.
For those who consider to vote down. This is a question we got in a course, and we are expected to prepare for the next session with this riddle.
I am not new to programming, but I fail to research how JavaScripts treats this code. It is valid code really, execute it in your Dev Tools and you will see.
I define a property for the string s called len assign to it the value 4. This property is, I believe created, but undefined. I would like to now why is it ? Is it specific to strings in JavaScript ?
but I fail to research how JavaScripts treats this code.
That is easy: strings are primitive types in JS, which means they don't have properties by themselves.
For . operator to work with them (e.g. for .length call) javascript defines such a thing called "wrapper objects".
So when you try to access a property of a primitive object - a temporary wrapper object is created that does behave as an object, hence you can access and assign properties to it.
The problem is that the wrapper object is temporary, so after it's used to access a property the object is discarded with all its state.
That's why when you assign a .len property you cannot access it on the next line: it's lost.
So a pseudo code for what actually happens behind the scenes for your code is
var s = "test";
(new String(s)).len = 4; // here you add an attribute for a new object
// and `s` is left untouched
var t = s.len;
The question is why the variable t has a value of undefined.
Because you have defined s as a string not as an object. so s.len should be undefined!
I am not sure what are you trying to do. But if you want to get the length of s then t = s.length will simply work.
I define a property for the string s called len assign to it the value 4. This property is, I believe created, but undefined. I would like to now why is it ? Is it specific to strings in JavaScript ?
You can find the answer from this question
run :
var s1 = "test";
console.log(typeof s1)//string
var s2 = {}
console.log(typeof s2)//object
s1.len = 4;
s2.len = 4;
console.log(s1.len);//undefine
console.log(s2.len);//4

JavaScript NameSpace Global Variable vs Global Property

I have two part question about creating namespaces in JavaScript, which one of the following is proper/better way to define a namespace:
// style 1
var company = company || {};
company.models = company.models || {};
company.models.class = {...}
// style 2
company = typeof (company) == 'undefined' ? {} : company;
company.models = company.models || {};
company.models.class = {...}
Please note there are TWO differences in the styles. First is use of typeof and Second is the style 2 does NOT use the var key.
Both these styles seem to work and now here is where it gets really confusing. If I remove the var key from style 1 then namespace does NOT work at all. I get something like company is not defined. I think it has something to do with the var creating a global variable and without var we are creating a global property as explained in here
What is the purpose of the var keyword and when to use it (or omit it)?
Would some please explain to me why the style 1 fails without the var key?
Many thanks in advance.
It's matter of likes but I prefer the first one since It is shorter and more readable.
First style 'means':
Create local variable 'company'. If it exists(and its value is not falsy) in an upper scope asign that to this variable else asign a new object.
Second one 'means'
Assign to company variable a new object if it is undefined or itself if it is defined.
The first one triggers a ReferenceError if you remove 'var' because the second reference (company = company) doesn't exists and the interpreter doesn't know how to deal with that. If it exists it will work even if you remove 'var'.
Another note for the first style is that company will be overwritten with a new object even if it is a falsy value like 0, null or ""

Declare variable based on object value in javascript

Simple issue I ran up against today and can't seem to find a way around it, whatever the solution is it's something I've never learned so leaving me stumped.
For reasons I won't get into, I need to get a value from an object and use it as the name of a new variable. Will be looping through a ton of these so needs to be repeatable. For example from an object like so,
obj = {
"name": "object101"
};
What I want to get out of that is a var declaration in such a way that object101 is the name of the new var,
"var object101 = // stuff"
But "var obj.name = // stuff" is not working, the dot is not valid it seems.
I also tried putting the object101 into it's own var like, var name = obj.name;.
Which holds the content fine. But then I immediately saw the hilarious problem with going, var name = // stuff
It just redefines "name" and is not placing the content of name. It does render right when in a console log like console.log("var "+name+" = stuff"); which is pretty much exactly how I want it to write to the code, but having this issue in the real code with the var being redefined in this case.
So I feel like I am missing something very basic in how you can provide the name to declare a var. Maybe some very simple syntax thing I am missing, or perhaps there is a process out there which will dynamically make a var declaration name based on some other object. I've done my fair share of js and never seen var [complex syntax resulting in name] =, it's always quite simple.
But my searching has drawn a blank so far on this exact issue. Anyone able to enlighten me?
Wow, you really don't want to do what you think you want to do, but here goes.
If you are operating in a browser and you want the variables to be in global scope, fortunately the global scope has a name: window.
You can just do this:
window[obj.name] = 'stuff';
If you want it in in local scope, you can use the almost-forbidden keyword with:
var f = function(obj, b) {
var fake_scope = {};
with (fake_scope) {
fake_scope[obj.name] = b;
console.log(d);
}
}
f( { name : 'd' } , 3 )
will print out 3.
If you need local scope and you don't want to use with, you will have to screw around with eval.
But seriously, if you do this, remember.
Well, in the interest of science:
(function() {
var dynaVarName = 'testName';
eval('var ' + dynaVarName + ';');
eval(dynaVarName + ' = 5;');
eval('console.log(' + dynaVarName + ');'); // => 5
}());
testName // => ReferenceError
So yes, you actually can create a local variable with a name based on an expression. I can't imagine the benefits of doing this though.

JS: Get the var name

I have this code here:
var myVar = 'this is a string';
I want to get the string representation of the variable name myVar. This is a very simplified example. Obviously we know it's myVar but it demonstrates my need.
I need to run a function like this:
function getVarName(v) {
return v.blah;
}
var nameOfVar = getVarName(myVar); //should 'myVar'
Is this possible? I'm not worried about cross-browser, it's for a firefox addon so I can use the latest >= ES5.
Thanks
Edit: I wanted to add the reason I was doing this, it was to dump some objects in firefox system, it helps me make addons. I know the key/value thing in objects, but in case the function gets run on a string or some non-object it would be nice to know the var name it got run on. It runs on bunches of stuff automatically so I don't know the var names.
That is not possible. It won't be sent as it is in the method call.
getVarName("var");
function getVarName(variableName) {
/* this would be var */
}
The function has its own parameter for that variable. However, you can get the value in that variable.
That isn't how variables work in JavaScript.
If you want to maintain a mapping of strings to values, use an object:
values = { myVar: 'this is a string' }
I know you have mentioned you don't want objects to be involved. But have a look at this one:
const getVarName = (variable) => {
let varName = '';
for (let key in variable) varName = key;
return varName;
}
const myVar = 'some string';
// Place your string inside curly braces
const nameOfVar = getVarName({myVar});
console.log(nameOfVar); // output: 'myVar'

Why do people declare something as null in JavaScript? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Why is there a null value in JavaScript?
I don't understand what null is for. 'Undefined' as well.
It helps to appreciate the difference between a value and a variable.
A variable is a storage location that contains a value.
null means that the storage location does not contain anything (but null itself is just a special kind of value). Read that last sentence carefully. There is a difference between what null is and what null means. 99% of the time you only care about what null means.
Undefined means that the variable (as opposed to the value) does not exist.
null is an object you can use when creating variables when you don't have a value yet:
var myVal = null;
When you do this, you can also use it to check to see if it's defined:
// null is a falsy value
if(!myVal) {
myVal = 'some value';
}
I wouldn't use it this way, normally. It's simple enough to use 'undefined', instead:
var myVal; // this is undefined
And it still works as a falsy value.
Creating Objects
When you create an object in javascript, I like to declare all my object properties at the top of my object function:
function myObject() {
// declare public object properties
this.myProp = null;
this.myProp2 = null;
this.init = function() {
// ... instantiate all object properties
};
this.init();
}
I do this because it's easier to see what the object properties are right off the bat.
If a variable is not known or not initialized in the current scope it is undefined.
If you want to use a variable and indicate that it has an invalid value for instance you may want to assign it null because accessing an undefined variable will throw an error if you try to work with it (despite checking if it is undefined).
If something is undefined you also have the possibility to add it to an object. If a variable is defined but contains null you know that this variable may be used already by another part of your program.
For example, it can prepare a global variable to be used in more parts of the code.
If you start your code with var iNeedThisEverywhere = null; then you can use it inside more objects/actions in the code, but if you don't do that, then this variable will not be shared throughout the code.
Of course, you will actually put something inside that variable somewhere during the code, but since you defined this variable at the very beginning, it will be shared further anyway.
A variable holding null holds a reference to the "black hole" named null.
10 + 10 + null = null
Null is related historically to databases, http://en.wikipedia.org/wiki/Null_(SQL)
(Correct me if I'm wrong here)
A variable not initiated (unknown) is undefined.
regards,
/t

Categories

Resources