Since it is possible to do:
var x = 'foo', y = 'foo';
Would this also be possible?
var x, y = 'foo';
I tried it, however x becomes undefined.
I know this may seem like a silly or redundant question, but if I'm curious about something, why not ask? Also you will probably wonder why I would need two variables equal to the same thing in scope. That is not the point of the question. I'm just curious.
Not sure if this is what you're asking, but if you mean "Can I assign two variables to the same literal in one line without typing the literal twice?" then the answer is yes:
var x = 10, y = x;
You need two separate statements to get the exact same semantics.
var x, y; x = y = 'foo';
// or
var x = 'foo'; var y = x;
// or
var y; var x = y = 'foo';
The solution other users are suggesting is not equivalent as it does not apply the var to y. If there is a global variable y then it will be overwritten.
// Overwrites global y
var x = y = 'foo';
It is a good practice to correctly apply var to local variables and not omit it for the sake of brevity.
You can do
var x = y = 'test'; // Edit: No, don't do this
EDIT
I just realized that this creates/overwrites y as a global variable, since y isn't immediately preceded by the var keyword. So basically, if it's in a function, you'd be saying "local variable x equals global variable y equals …". So you'll either pollute the global scope, or assign a new value to an existing global y variable. Not good.
Unfortunately, you can't do
var x = var y = 'test'; // Syntax error
So, instead, if you don't want to pollute the global scope (and you don't!), you can do
var x, y;
x = y = 'test';
In order for that to work, you will either need to initialize them separately (like your first example) or you will need to set them in a separate statement.
// This causes bugs:
var x = y = 'test';
Watch:
var y = 3;
function doSomething(){ var x = y = 'test'; }
doSomething();
console.log( y ); // test !?
On the other hand:
// this does not
var x,y; x = y = 'test';
Watch:
var y = 3;
function doSomething(){ var x,y; x = y = 'test'; }
doSomething();
console.log( y ); // 3 -- all is right with the world.
Below is my test function. The currently uncommented line in the pollute function does what you were looking for. You can try it and the other options in jsfiddle here.
var originalXValue = 'ekis';
var originalYValue = 'igriega';
var x = 'ekis';
var y = 'igriega';
function pollute()
{
// Uncomment one of the following lines to see any pollution.
// x = 'ex'; y = 'why'; // both polluted
// var x = 'ex'; y = 'why'; // y was polluted
// var x = y = 'shared-ex'; // y was polluted
var x = 'oneline', y = x; // No pollution
// var x = 'ex', y = 'ex'; // No pollution
document.write('Pollution function running with variables<br/>' +
'x: ' + x + '<br/>y: ' + y + '<br/><br/>');
}
pollute();
if (x !== originalXValue && y !== originalYValue)
{
document.write('both polluted');
}
else if (x !== originalXValue)
{
document.write('x was polluted');
}
else if (y !== originalYValue)
{
document.write('y was polluted');
}
else
{
document.write('No pollution');
}
Note that although
var x = y = 'test';
is legal javascript
In a strict context (such as this example):
function asdf() {
'use strict';
var x = y = 5;
return x * y;
}
asdf();
You will get:
ReferenceError: assignment to undeclared variable y
to have it work without error you'd need
var x, y;
x = y = 5;
You'd use var x, y = 'foo' when you want to explicitly initialize x to undefined and want to restrict the scope of x.
function foo() {
var x, y = 'value';
// ...
x = 5;
// ...
}
// Neither x nor y is visible here.
On the other hand, if you said:
function foo() {
var y = 'value';
// ...
x = 5;
// ...
}
// y is not visible here, but x is.
Hope this helps.
Source: http://www.mredkj.com/tutorials/reference_js_intro_ex.html
I would avoid being tricky. Since I only use one variable per var (and one statement per line) it's really easy to keep it simple:
var x = "hello"
var y = x
Nice, simple and no silly issues -- as discussed in the other answers and comments.
Happy coding.
I am wondering why nobody posted that yet, but you can do this
var x, y = (x = 'foo');
You can't do
var a = b = "abc";
because in that case, b will become a global variable.
You must be aware that declaring a variable without var makes it global. So, its good if you follow one by one
var a = "abc";
var b = a;
Related
In my code, the x value is undefined. If I remove if block, the x value is displayed as 77. I don't understand why if block is modifying the x value.
var x = 77;
function fn() {
if (false) {
var x = 55;
}
console.log(x);
}
fn();
var x = 77;
function fn() {
if (false) {
var x = 55;
}
console.log(x); // undefind
}
fn();
In the intermediate phase, x will be hoisted to its scope:
var x = 77;
function fn() {
//var x = undefind; intermediate phase
if (false) {
var x = 55;
}
console.log(x);
}
fn();
var x = 77;
function fn() {
if (false) {
x = 55;
}
console.log(x); // 77
}
fn();
The x variable is redeclared and hoisted inside the function, but never set because if (false) will never be reached thus undefined. The outer x is known inside the function if you remove the inner declaration.
This can be solved by using const or let (ES6) instead of var. const and let is not hoisted and lives only inside of the brackets they are declared:
const x = 77;
function fn() {
if (false) {
const x = 55;
}
console.log(x); // 77
}
fn()
Another solution is to just use two different variable names or remove the var inside the if statement depending on your needs...
Inside the scope of the function, the variable x is hoisted to the top as follows var x; If you print it, you get undefined. It is never assigned a variable as it is not going inside the if block
Simply remove the var inside the if-statement. That will fix the hoisting issue.
var x = 77;
function fn() {
if(false) {
x = 55;
}
console.log(x); // 77
}
fn();
You can also use let keyword.
let x = 77;
function fn() {
if (false) {
let x = 55;
}
console.log(x); // 77
}
fn()
one should use wither ES6 define syntax const OR let while assigning the variable, if needs to mutate the variable then use let, otherwise use const , stop using var .
In your scenario while using var there, it means you are trying to re initialize the x, it gets hoisted
var x = 77; means
var x; outside the block.
So one should not need to re initialize the x just pass the value or either use let or const .
function fn() {
if (false) {
//
x = 55;
}
console.log(x);
}
fn();
What am I missing here? This behaves as expected:
var x = 1;
(function(){
// x === 1
})();
But,
var x = 1;
(function(){
var x = x;
// x is undefined
})();
I would think that x should be 1. It seems as though the var x = x nukes the value of x before it is assigned. Is this a bug? This doesn't seem very intuitive.
Was this behavior changed? I remember doing something like this in the past.
For reference:
var x = 1;
(function(){
var y = x;
// y === 1
})();
And:
var x = 1;
(function(){
x = x;
// x === 1
})();
var x = 1;
(function(){
var x = x;
})();
After variable hoisting becomes:
var x = 1;
(function(){
var x;
x = x;
})();
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Statements/var
Because variable declarations (and declarations in general) are processed before any code is executed, declaring a variable anywhere in the code is equivalent to declaring it at the top. This also means that a variable can appear to be used before it's declared. This behavior is called "hoisting", as it appears that the variable declaration is moved to the top of the function or global code.
That's why sometimes in plugins you see code like
var i,j,abc, d;
//code
In you example, the code is transformed like this:
function() {
var x;
x = x;
}
The example with function arguments is different, you just change the function argument itself and the var declaration is ignored.
If a scoped variable is declared with let, it will only move up to the beginning of that scope and not of the function, so this code works:
var x = 1;
(function(){
var y = x;
{
let x = y;
console.log(x);
}
})();
As pointed out, it's a new feature, so not supported everywhere.
And finally, here:
var x = 1;
(function(){
x = x;
// x === 1
})();
You do not declare x locally, so if you edit it, it'll also edit it at global scope.
In JavaScript all variables declared in global scope or in scope of whole function where it declared. Consider example:
var x = 1;
function f()
{
console.log(x);
if (true) {
var x;
}
}
f();
This is weird programming language design but this code also prints "undefined" because of this rule.
Everytime you type var you are reassigning a new variable. When you just reference x inside the function it looks up to the assignment statement above.
function f(){
var x = x; //this tries to reassign var x to undefined.
}
what you are doing here is setting x as a global variable and then setting it to reference itself, overwriting the 1, making x => x which would be undefined.
I want to reduce the initialization of multiple combination variables.
My aim is to create a function and pass a function with variable.
If I pass a variable x into function value(x); I should get output as "123". Similarly, if I pass a variable xy into function value(xy), then I should get output as "123456". Basically, I want to concatenate variables
Here is the javascript code as
var x = "123";
var y = "456";
var z = "789";
var a = "0-+";
var xy = x + y;
var yz = y + z;
var zx = z + x;
var xa = x + a;
var ya = y + a;
var za = z + a;
var ax = a + x;
var ay = a + y;
var az = a + z;
var xz = x + z;
var yx = y + x;
var zx = z + x;
var zy = z + y;
var xyz = x + y + z;
var xyza = x + y + z + a;
function value(input) {
console.log(input);
}
Sample execution as follows:
value(x); //output: 123
value(y); //output: 456
value(xy); //output: 123456
value(za); //output: 7890-+
In this case, there are lots of combination for the above variables i have defined to meet all possible combinations. I want to validate the user input from the above combination and also i dont want to write so many variables. Is there any possible easy solution ?
Please suggest. Thanks
I would declare a global object to store the variables as keys:
var globals = {
"x": "123",
"y": "456",
"z": "789"
};
Note that you can refer to your "variables" by globals.x, or globals.y (you can replace globals with a shorter keywork to reduce code of course).
It is a little extra effort to define the "variable names" with quotes.
However, now you get to use:
alert(Combinate("xz"));
// output: 123789
With a function like:
function Combinate(phrase) {
result = "";
for (var i = 0, len = phrase.length; i < len; i++) {
result += globals[phrase[i]];
}
return result;
}
Here's a JSFiddle.
You'll want to use some form of iterating over an array or object. As an example:
var x = "dave";
var y = "bill";
var z = "john";
var a = "suzan";
var people = [x,y,z,a];
for(i=0; i<people.length; i++) {
for(x=0; x<people.length; x++) {
value(people[i] + people[x]);
for(y=0; y<people.length; y++) {
value(people[i] + people[x] + people[y]);
for(z=0; z<people.length; z++) {
value(people[i] + people[x] + people[y] + people[z]);
}
}
}
}
// not sure why you'd have a function to wrap console.log(), but...
function value(input) {
console.log(input);
}
See in action on jsFiddle.
There are more elegant paths, but this should get you on the road to learning about JavaScript.
I'm new to javascript and I'm not sure if there is anything called re-initialization in javascript, so please excuse if there is no such concept.
What happens if a javascript variable is re-initialized?
Ex:
function foo()
{
var x = 10;
.... //do something
.... //do something
.... //do something
var x = 20;
console.log("x: " + x);
}
What would be the value of x here?
x will be 20. var is "hoisted" (more below), which means that the variable gets declared as of the beginning of the function, before any step-by-step code is run. Any initializer on a var statement is actually just an assignment statement.
So your code:
function foo() {
var x = 10;
//do something
var x = 20;
console.log("x: " + x);
}
is treated as though it were like this:
function foo() {
var x;
x = 10;
//do something
x = 20;
console.log("x: " + x);
}
When you call a function, the JavaScript engine does several things before it starts executing the step-by-step code in the question. one of the things it does is look through the code and process any var statements. (Although it's called the var statement, var is more of a declaration.)
It's quite fun, your code could also be written this way:
function foo() {
x = 10;
//do something
x = 20;
console.log("x: " + x);
return;
var x;
}
It would still be valid, and it would do exactly the same thing.
More (on my blog): Poor, misunderstood var
ES6 will introduce let, which behaves differently (amongst other things, it is scoped to the block it's in, whereas var is scoped to the function as a whole even if declared within a block); details on MDN.
The var keyword essentially just determines the scope of the variable and is handled before any of the code is actually executed (look up "hoisting"). Using var twice for the variable is redundant, but doesn't really do anything in particular. In the end you're just assigning 10 to x and later you assign 20 to x; nothing more, nothing less.
You can always run simple test to check that. var means it's this variable is in current scope. So in your example x will be equal to 20
var x = 10;
var x = 20;
var y = 10;
function Test() {
var x = 30;
y = 20;
alert('X in function: ' + x);
alert('Y is global, so it\'s ' + y);
}
Test();
alert('X outside of function: ' + x + ', also Y = ' + y);
I'm getting stuck somewhere (as newbies do). Is it ok to re-define a variable once it has been trimmed and tested for content?
function setarea() {
var dbasedata = document.forms[0]._dbase_name.value;
dbasedata = dbasedata.toUpperCase();
dbasedata = dbasedata.replace(/\s/g, "");
dbasedata = dbasedata.remove("UK_CONTACTS", "");
if (dbasedata != "") {
_area.value = _dbase_name.value;
}
else var dbasedata = document.forms[0]._dbase_name.value;
dbasedata = dbasedata.toUpperCase();
dbasedata = dbasedata.replace(/\s/g, "");
if (dbasedata.indexOf("UK_CONTACTS")>-1 {
var dbaseterm = "UK_CONTACTS";
else var dbaseterm = "";
}
It makes no sense to use var more than once for the same variable in the same scope. Since all var x; are hoisted to the top of the scope every additional var on that variable will be a no-op.
Assigning a new value is fine though - they are variables and not constants after all.
function x() {
var x = 123;
foo();
x = 456;
var y = 'hello';
var x = 678;
}
is actually this internally:
function x() {
var x, y; // both are === undefined
x = 123;
foo();
x = 456;
y = 'hello';
x = 678;
}
Yes, you can do this and it is legal.
It may 'work', but isn't recommended. You don't need to redeclare it.
Probably want to run your code through JSLint . There are a few tidyness/bracing issues you would want to address.