variable is already defined - javascript

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

Related

What does comma mean after javascript object declaration?

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;

Javascript split() not working! completely stumped

filename = "file_1";
name = filename.split('_');
test1 = name[0];
test2 = name[1];
console.log(test1);
console.log(test2);
Expected Result:
file
1
Actual Result:
f
i
http://jsfiddle.net/j667q/1/
I must be doing something wrong, but can't for the life of me work out what.
I have tried:
Using different quotes ' and "
Defining filename and name before using (filename = '';
name = [];)
Spliting using a different character ('-')
Define the array variable first:
var name = [];
DEMO http://jsfiddle.net/j667q/5/
Why this works?
Update for more clarification based on comments:
Although name is not a reserved word, it's a global property of window (eg. window.name and name mean the same), var name; will define a new variable called name which is in another scope and avoids the conflict.
JavaScript Reserved words: http://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Reserved_Words
The problem is, something to do with global conflicts the global object has a property called name and is somehow conflicting with your code.
rename it http://jsfiddle.net/j667q/3/
you could do var name = ...split... if you don't want to rename it
Yeah, also note, you should ALWAYS declare variables with var there is no reason not to, if you want a global property do window.someName = something;
Declare the variables as var to scope them properly
var filename = "file_1";
var names = filename.split('_');
test1 = name[0];
test2 = name[1];
console.log(test1);
console.log(test2);
name is a js global property. so try not to use it. hope that will help
you have to declare both variables like this.
var filename = "file_1";
var name = filename.split('_');
check out the updated JSFIDDLE (http://jsfiddle.net/prakashcbe/j667q/17/)
Try this...
Other answers all are correct. I don't know your mistake. Anyway, try this as well
[http://jsfiddle.net/puvanarajan/Nytgh/][1]

Why can't I call a reference to document.getElementById I've stored in a variable?

While I'm at work, I'll write little snippets of JS to explore the language proper, not using any frameworks. However, since I'm lazy, I'll keep a reference to document.getElementById by storing it in a variable:
var grab = document.getElementById;
var foo = grab('some_id');
var bar = grab('some_other_id');
This has always worked in IE7/8, but I tried it back home on Firefox and it didn't like the shortcut. Now, it works when I wrap it up in a function and close over the argument:
var grab = function (some_id) {
return document.getElementById(some_id);
};
but I don't understand why I need to do that; in Firefox I can throw around references to user-defined functions and it doesn't complain:
var foo = function(x) {
alert(x);
};
var bar = foo;
foo('foo'); // alerts 'foo'
bar('bar'); // alerts 'bar'
Why can't I call a reference to document.getElementById I've stored in a variable?
It's about this value. I've created a test case on jsFiddle http://jsfiddle.net/pomeh/mPRZR/ to show you the problem.
When you do var foo = document.getElementById("...");, this value of this inside the function is the document object.
When you do var grab = document.getElementById; var foo = grab("..."); you're executing the getElementById in a global context. In this case, the value of this inside the function is the global object, and not the document object.
I hope that's clear for you :) Look at the example and logged values.
This works:
var grab = document.getElementById.bind( document );
So, you use the bind function method to explicitly set the context for your grab function.
Live demo: http://jsfiddle.net/E2tvB/
(Note: you'll need to polyfill bind to achieve cross-browser compatibility.)
I usually use this to short my codes. And as this far, I have never found any problem with my method.
var grab=function (x){return document.getElementById(x);};
grab("par").textContent="This is textContent of paragraph AFTER changed by javascript";
<html>
<body>
<p id="par">This is textContent of paragraph BEFORE changed by javascript</p>
</body>
</html>

Javascript create variable from its name

In PHP we can do this:
$variable = "name_of_variable";
$this->{$variable} = "somevalue";
how to do this in javascript?
where use case should look like:
function Apple(){
var name = "variable_name";
this.(name) = "value";
}
console.log(new Apple());
to output
[Apple: {variable_name:"value"}]
try:
this[name] = "value";
All objects can use dot and array notation for variable access.
Also note, this will allow you to create name value pairs that are inaccessible via dot notation:
var foo = {};
foo['bar-baz'] = 'fizzbuzz';
alert(foo.bar-baz); //this will not work because `-` is subtraction
alert(foo['bar-baz']); //this will work fine
If you are creating a new object literal, you can use string literals for the names for values with special characters:
var foo = {'bar-baz':'fizzbuzz'};
But you will not be able to use variables as the key within an object literal because they are interpreted as the name to use:
var foo = 'fizz';
var bar = { foo:'buzz' }
alert( bar.fizz ); //this will not work because `foo` was the key provided
alert( bar.foo ); //alerts 'buzz'
Because other answerers are mentioning eval, I will explain a case where eval could be useful.
Warning! Code using eval is evil, proceed with caution.
If you need to use a variable with a dynamic name, and that variable does not exist on another object.
It's important to know that calling var foo in the global context attaches the new variable to the global object (typically window). In a closure, however, the variable created by var foo exists only within the context of the closure, and is not attached to any particular object.
If you need a dynamic variable name within a closure it is better to use a container object:
var container = {};
container[foo] = 'bar';
So with that all being said, if a dynamic variable name is required and a container object is not able to be used, eval can be used to create/access/modify a dynamic variable name.
var evalString = ['var', variableName, '=', String.quote(variableValue), ';'].join(' ')
eval( evalString );
You can use square bracket notation in Javascript:
variable = "name_of_variable";
window[variable] = "somevalue";
You can do this with any object in Javascript.
var name = "var_name";
var obj = {};
obj[name] = 'value';
alert(obj.var_name);
I suggest using associative arrays to do whatever you're trying to do as they are significantly cleaner and easier to debug.
However if you really insist, you can use eval() to accomplish this:
variable = "name_of_variable";
eval(variable + " = \"somevalue\""); // this will work, but please do not do it
alert(name_of_variable);
EDIT: It his just come to my attention that a significantly easier (and better) way of doing this is by simply accessing the window object:
window[variable] = "somevalue";
http://jsfiddle.net/WJCrB/
window['name_of_variable'] = 'somevalue';
or
eval('var ' + variable_name + ' = ' + variable_name + ';');
Beyond that, don't do this. Variable variables are NEVER a good idea and make it nearly impossible to debug problems when (invariably) things break.

Adding a dynamic function to an object

I'm trying to get this to work, but it doesn't:
var i;
i.test = function() {
alert("hello");
}
i.test();
I expect the code to alert 'hello', but instead, the Firefox error console shows:
missing } in XML expression
alert("hello");
---------------^
How do I fix this...
Your i isn't assigned to anything so it's not an object. It is, in fact, pointing to the global undefined object which happens to be read-only in Firefox (as it should be). You need:
var i = {}; //init to empty object
then all will be fine.
You can't add a function to an undefined value, you need to create an actual object:
var i = {};
Although not required, you should have a semicolon at the end of the statement to avoid ambiguity:
i.test = function() {
alert("hello");
};
var i = {};
i.test = function() {
alert("hello");
};
You had two separate issues. You were not initializing i (as noted by slebetman), and you were missing a semi-colon, forcing the interpreter to use semi-colon replacement.

Categories

Resources