What does comma mean after javascript object declaration? - javascript

Let's take some javascript code from vk.com
var stManager = {
//some long code with methods and properties...
}, __stm = stManager;
Why do we need last line in this code? Why duplicate stManager one more time?

You are declaring and initializing multiple variables with single 'var' thats it...
var x=1,y=2;

It means you are declaring another variable. Just a different notation. It is the same as:
var stManager = {};
var _stm = stManager;

Related

How to create dynamic variables using jquery?

I want some jquery variables to be created dynamically. In my code I am having a loop, and with the loop values I want to create some variables. Here is my sample code.
array=["student","parent","employee"]
$.each(user_types, function( index, value ){
var value+"_type" // this is the type of variable i want to build.
})
I have found about eval function. That code goes like this.
var type = "type"
eval("var pre_"+type+"= 'The value of dynamic variable, val';");
alert(pre_type) // this gives 'The value of dynamic variable, val' in alert box.
Is there any alternate ways as I have read the eval function is not prefered while coding .js files.
Any time you find yourself using a variable in the name of a variable, you probably want to use an object literal. Create the object with curly braces {}, and then set the object property key using square bracket notation:
var user_types = ["student","parent","employee"];
var types = {};
$.each(user_types, function( index, value ){
types[value] = 'The value of dynamic variable, val';
});
JSFiddle
Note: You haven't tagged it, but I assume because you've used each() that you are using jQuery, please correct me if I'm wrong.
First of all i must say that i can't think of any reason why you want to do this.
If you really need to have those variables, in global scope, you can do the following:
var array=["student","parent","employee"]
array.forEach(function(value){
window[value+"_type"] = 'My value ' + value;
});
console.log(student_type);
console.log(parent_type);
console.log(employee_type);
If you don't want the variables in global scope, i'm afraid i don't know an elegant solution.
I used array.forEach instead of your jQuery loop because the problem is not related to jQuery at all and because i don't think you said enough of your logic to make a coherent example.
EDIT: I should make it clear that while the 'variables' created behave mostly like other variables in global scope, they are NOT variables. Here is how they differ:
// Difference 1: hoisting
console.log(x); // undefined
console.log(y); // ReferenceError: y is not defined
var x = 5;
window[y] = 5;
console.log(x); // 5
console.log(y); // 5
// Difference 2: [[Configurable]]
delete x;
delete y;
console.log(x); // 5
console.log(y); // ReferenceError: y is not defined
If you want to add an intermediate variable inside the string, you can do it as follows:
var itemSelect: number = 1;
$(`#tab${this.itemSelect}-tab`).tab('show');
/* Result -> $(`#tab1-tab`).tab('show'); */
/* HTML */
<a id="tb1-tab"> </a>

Javascript: Naming arrays programmatically

Is it possible to create a new Array, giving it the name of the content of a variable?
For example something like this:
var nameofarray = "array_name";
var ¿nameofarray? = new Array();
So that ¿nameofarray? gets the value of "array_name"?
Assuming you are in global scope (called window) so:
var nameofarray = "array_name";
window[nameofarray] = new Array();
Otherwise it's only posible on objects:
function a() {
var nameofarray = "array_name";
var obj = {};
obj[nameofarray] = new Array();
}
You can also use eval. Which is used for evaluating a string to JavaScript code:
eval('var '+ nameofarray+'=new Array()');
This will work in local scopes as well, but I hardly ever recorment it to anyone.
You would maybe like to read: http://javascriptweblog.wordpress.com/2010/04/19/how-evil-is-eval/
In PHP and other languages, they are called variable variables. This might help: Javascript "Variable Variables": how to assign variable based on another variable?
If nameofarray is declared in the global scope, you can use the window object:
window[nameofarray] = []; // Use an array literal instead also
^^^^^^^^^^^^^^^^^^^
But you really shouldn't be doing this.

variable is already defined

sometime i need to replace a variable value to another
so i use this method
var $$test = "First",
$$test = "Second";
the code work fine but i use jsfiddle JSHint button to check any error on JavaScript (it helped me a lot)
but i got this error '$$test' is already defined
so what is the ideal method to re define any variable
Thank you :)
You're getting that error because you're declaring the same variable twice.
var a = foo, a = bar;
Is the same as:
var a = foo;
var a = bar;
Just break your code in two lines, and you won't get that warning. Like this:
var a = foo;
a = bar;
Also notice that if you declare a variable with a value, and then right after that you change its value, the first line is a noop.
Don't use a comma. You should redefine it as a new statement:
var $$test = 'First';
$$test = 'Second';
this code is trying to define two variable s called $$test. They need to have uniuque names.
Try using $$test1 and $$test2
updated for you http://jsfiddle.net/9CdJN/2/
(function($){
var $$test = "First";
$$test = "Second";
console.log($$test);
})(jQuery);
The problem is that you have a comma , at the end of the first line instead of a semi-colon ;.
Each Javascript statement ends with a semi-colon. You can define multiple variables with a single var by separating them all with a comma.
var var1=1, var2=2, var3=3;
is the same as
var var1=1,
var2=2,
var3=3;
Because you had a comma in the first line, the browser believes you are declaring two different variables with the same name. To fix it, just change it to this:
var $$test = "First";
$$test = "Second";

Trouble with Objects

Basically i'm having trouble with something that i'm sure is super duper simple but I just don't know what to call it and therefore I am having trouble searching for an answer. :(
Basically, say I've declared an object, i.e var meow = {}; and then i decide to create an object within that by doing something like meow.cutekitten = {}; this is all straight forward and i end up with an object called cutekitten within that.
My issue is, what if I've declared cutekitten as a variable and i want to use the contents of that variable as the name of this new object rather than the variable name?
var propertyName = "cutekitten";
var meow = {};
meow[ propertyName ] = {};

In JavaScript, when declaring multiple variables at once are there memory benefits to using only one var statement?

For Example,
//pattern one
function Foo() {
var hello
, world
, how = []
, are
, you = 'you';
}
//pattern two
function Foo() {
var hello;
var world;
var how = [];
var are;
var you = 'you';
}
Would it be more memory efficient to use pattern one, versus pattern 2? Are there other benefits one provides over the other?
No, they're both exactly the same. Some people prefer doing all variable declarations at the top of the function, because that's where they effectively are due to hoisting. JSLint also has an option to require a single var statement (onevar), but I really don't find that necessary.
No. It's just a matter of code readability.
memory allocation is done internally using different memory locations (storage wise), therefore it really does not make difference to use with a single declaration or multiple declaration.

Categories

Resources