What does this[var_name] = 12; do in JavaScript - javascript

Today I've seen code on w3resource and I was thinking what it does:
var var_name = 'abcd';
var n = 120;
this[var_name] = n;
console.log(this[var_name]);
// the OUTPUT : 120
// This line was added to this example.
console.log(abcd);
Firstly I thought it's to change the variable value but when I type var_name in the console to get the value it gave me 'abcd'. Actually this is very confusing to me.

In JavaScript this always refers to the “owner” of the function we're executing, or rather, to the object that a function is a method of. But since in the code the this is used globally it relates to the document level. So,
var var_name = 'abcd';
Creates a variable name var_name with value abcd. This is commonly used to create a variable.
But,
var n = 120;
this[var_name] = n;
Can be accessed when you make an object. We add properties to this when we want the properties to exist with the life of the object. We Use var for local variables.
Hence, this[var_name] and var_name are treated separately.

Hey I've added comments to the lines. Hope this helps you to understand the code
var var_name = 'abcd'; //creates a new variable with the name var_name and the
value 'abcd'
var n = 120; //creates a new variable with the name n and the value 120
this[var_name] = n; //add a new property with the value of var_name (abcd) to this and the value of n (120)

Related

Using a variable increment to create new variables in Javascript

It might be a beginner's question, but I can't seem to find an answer on this.
The data it is getting is data out of a JSon file. I want it to loop through all the rows it is seeing. The loop works how it is written below and returns me the info I need with the rest of the code. I am trying to create multiple variables like testVar1, testVar2, testVar3, .... I don't know if it is possible to do it this way, or if I need to find another solution.
var i = 0;
for (var x in data) {
var testVar1 = data[0][1]; // works
var testVar[i] = data[0][1]; // doesn't
i += 1;
}
How can I make the testVar[i] work ?
What is the correct syntax for this?
Your code misses the initialization of your array variable: var testVar = [];.
⋅
⋅
⋅
Anyway, you may want to create those variables in the window object :
for (var i = 0; i <= 2; i++) {
name = 'var' + i;
window[name] = "value: " + i;
}
console.log(var0);
console.log(var1);
console.log(var2);
That way you can keep using the "short" variable name.
You can wrap all those variables in an object.
instead of:
var testVar1 = data[0][1];
Try:
var Wrapper = {};
//inside the for loop:
Wrapper["testVar" + i] = data[0][i];
...and so on.
You'd access them as Wrapper.testVar1 or Wrapper["testVar" + 1].
The problem you're having is pretty simple. You try to declare a variable as an array and in the same statement try to assign assign a value to a certain index. The reason this doesn't work is because the array needs to be defined explicitly first.
var testVar[i] = data[0][1];
Should be replaced with:
var testVar = []; // outside the loop
testVar[i] = data[0][1]; // inside the loop
Resulting in:
var i = 0,
testVar = [],
data = [
['foo', 'bar', 'baz'],
['kaas', 'is', 'baas']
];
for (var x in data) {
var testVar1 = data[0][1];
testVar[i] = data[0][1];
i += 1;
}
console.log('testVar1', testVar1);
console.log('testVar', testVar);
console.log('testVar[0]', testVar[0]);
console.log('testVar[1]', testVar[1]);
If i isn't an integer you should use an object instead. This can be seen in the answer of Tilepaper, although I advise against the use variables starting with a capital letter since they suggest a constant or a class.

AngularJS variable insertion to another is not copying value

I have an interesting problem.
App.controller('ABCController', function() {
$scope.valueA = 'abcd';
var tmp = $scope.valueA;
/* Do some actions with tmp */
tmp = tmp.replace('a', 'bc');
tmp = tmp.split('b');
...
console.log(tmp);
console.log($scope.valueA);
}
The result of console.log is showing updated tmp, but also, $scope.valueA is updated, too, which is same as tmp.
This is not what I expected. In the "var tmp = $scope.valueA" clause, angular provides the pointer of $scope.valueA? Did you face this problem before?
Try this
var tmp = value;
reportList.push({tag : 'abcd',ticker :'bcde',published : true, key:value);
You can use var tmp = angular.copy(value);
In your case both tmp and value are pointing to the same location in memory. So any changes in tmp will result in a change in value. Both tmp and value holds the same instance and any update or change will be reflected on both variables.

jQuery .each function not persisting global variable

I have a function whereby I wish to run a .each loop and return the running total of the values
At the end of my .each function, the amountSold variable is 0 and during the .each loop, it is shown as undefined. What am I doing wrong?
function processChange(currentTarget) {
var amountSold = 0; //VARIABLE DECLARED
//limit these operations to the currentlySelected tab
var availableFundContainer = $(currentTarget).closest(".available-content").parent();
var fundBeingSold = $(availableFundContainer.children(0)).attr('data-investment-code');
availableFundContainer.find('.available-handler').each(function (index, val) {
var origVal = $(this).attr('data-original-value');
var currentSliderVal = $(this).next('.available-content').find('.slider').slider("value");
var amountSold = amountSold + (origVal - currentSliderVal); //PROBLEM LINE!!!!!
....}
You're creating a locally scoped variable, also called amountSold, inside the each callback function.
Replace
var amountSold = amountSold + (origVal - currentSliderVal); //PROBLEM LINE!!!!!
with
amountSold += (origVal - currentSliderVal); //PROBLEM LINE!!!!!
You are confused with how the function scope works in JS. Consider the following example:
var someArray = [0,1,2,3,4,5];
var a = 0;
var b = 0;
someArray.forEach(function(item) {
a = a + item;
var b = b + item;
console.log("loop", a, b);
});
console.log("final", a, b);
Run the snippet, and you will see that within the loop, the variable b starts out as undefined. This is so, because the function passed to the forEach method creates a new scope, and any variables declared with the var statement, will override any variables that exist in the parent scope. In this case, it means that b ends up being NaN. On the other hand, a keeps its previous value and increments as expected.
The final console log demonstrates, that the value of b in the global scope was not changed by the statements executed in the loop.
This feature of JS allows a user to create a functions that do not have side effects on the global scope.
And to answer your question, you are using the var statement:
var amountSold = amountSold + (origVal - currentSliderVal);
when you should be using a simple assignment
amountSold = amountSold + (origVal - currentSliderVal);
Make the variable global using
window.amountSold = 0
Inside the loop just call it the same way
window.amountSold += (origVal - currentSliderVal);

Dynamically Select Variable [duplicate]

This question already has answers here:
Access value of JavaScript variable by name?
(7 answers)
Closed 5 years ago.
I have 2 variables like so
var variable_1 = "foo";
var variable_2 = "bar";
I use a function to grab the value of a checkbox input and for each checkbox which is checked, I want to load the particular variable which depends on value of checkbox.
$("input:checked").each(function() {
$(div).append('variable_'+$(this).val());
}
So I'd concatenate the text 'variable_' with the value of each checkbox.
Thanks!
You can use eval to get any variable values dynamically.
var variable_1 = "foo";
var variable_2 = "bar";
$("input:checked").each(function() {
$(div).append(eval('variable_'+$(this).val()));
}
Note: it's not the best solution because eval has some security issues as well.
Because calling a variable or function from a user input is dangerous, and particularly if you are only using two different variables, you would be better off using a simple if statement.
This one is a ternary if:
var variable_1 = "foo";
var variable_2 = "bar";
$("input:checked").each(function() {
var isChecked = $(this).is(':checked');
var append = (isChecked) ? variable_1 : variable_2;
$(div).append(append);
}
Alternatively you could use a switch statement for multiple values.
If the variables are globals then you can use
var y = window["variable_" + x];
to read or
window["variable_" + x] = y;
to write to them dynamically.
Better practice however is to use an object to store them instead of using separate variables...
var data = { variable_1: null,
variable_2: null };
...
y = data["variable_" + x];
Javascript can also use eval to access dynamically variables, amazingly enough even local variables
function foo(s) {
var x = 12;
return eval(s);
}
console.log(foo("x"));
and even more amazingly this allows the dynamic creation of new local variables...
var y = 42;
function foo(s) {
var x = 1;
eval(s);
return y; // may be global y or a local y defined by code in s
}
foo("x") // returns 42
foo("var y = 99") // returns 99 (but global y is not changed!)
but these uses of eval should be considered more a bug than a feature and are best avoided (they also makes the code basically impossible to optimize or understand so "just don't do it"™).
Create object with properties and access that properties via obj['prop'] notation, see code below:
var myObj = {'variable_1': 'foo', 'variable_2': 'bar'};
$("input:checked").each(function() {
var dynamicVariableName = 'variable_' + $(this).val()
var dynamicVarValue = myObj[dynamicVariableName];
$(div).append(dynamicVar);
}
If your variables lives under window it's better to create new global object which contains that variable rather than keeping that variables as globals.

Declare javascript object property issue

I am trying to declare a javascript object properties.
I have
var myObj = {};
var rowsCount, columnsCount, texts;
var temp = document.createElement('div');
temp.innerHTML = tableData; //tableData is bunch of tables in html
var tables = temp.getElementsByTagName('table')
//use tables as array...
for(var i = 0; i<tables.length; i++){
var table = tables[i];
myObj.rowsCount = $('tr', table).length;
myObj.columnsCount = $('td', table).length / myObj.rowsCount;
}
The above codes work. However, if I remove
var rowsCount, columnsCount, texts;
the code will complain rowsCount, columnsCount and texts are not defined.
However, in W3Cschool object page, they have
person=new Object();
person.firstname="John";
person.lastname="Doe";
person.age=50;
person.eyecolor="blue";
and it seems fine without declaring the property first.
Can someone help me out here? Thanks a lot!
myObj.rowsCount is not the same as the rowsCount variable. The first is a property of an object, the other one is just a variable (with the same name).
If you're getting that error (assuming it's a ReferenceError), it's because you're trying to read from the rowsCount variable (not myObj.rowsCount) when it doesn't exist. That must be happening in some part of your code that you didn't show us.

Categories

Resources