javascript re-define a variable - javascript

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.

Related

Javascript and Hoisting

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();

JavaScript var keyword: redefining a variable's value inside a closure

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.

Access variables like a text?

Let's say i got a variable Var123;
var x = "Var";
var VariableMixLOL = x + "123";
//so VariableMixLOL should be equal to Var123, ex. Var123 = "Abc", VariableMixLOL should be "Abc" too
How can I do this? Btw i'm using as3
PS: Added at Tags JS too because i think it's the same thing
One option is to use eval()
var x = "Var";
var Var123 = "lalaala";
var VariableMixLOL = eval( x + "123" );
Another option and the better one is to model such things in a JavascriptObject.
var x = "variable";
var variables = { "variable123" : "laalala"}; //OR variables = {}; variables["variable123"] = "laalala";
var VariableMixLOL = variables[ x + "123"];
Variable name as String can be used if you incorporate an object to which you store it.
For example:
var x = "Var";
var compoundVar = x + "123";
var obj : Object = {};
obj[compoundVar] = 7;
//Now you can call the variable like this
trace(obj.Var123); //7

If I have a variable, assigned to the value of a function call, can that variable be updated if the function call's parameters are changed?

If I have a function, like this:
function f(x,y){
return x + y;
}
And if I have variables of parameters I want passed to f:
var parameter1;
var parameter2;
If I assign this function call to a variable:
var functionCallValue = f(parameter1,parameter2);
How can I ensure that functionCallValue changes depending on different values I assign to the variable parameter1 and parameter2?
I suppose what you need is a closure.
var servant = function(x, y) { return x + y; };
var param1 = 40;
var param2 = 2;
var master = function() { return servant(param1, param2) };
var result = master(); // 42.
param1 = 2;
param2 = 40;
var anotherResult = master(); // still 42, because that's really the answer!
functionCallValue is assigned the result (returnvalue) of your function f. (The function is called, the value calculated and the result handed over to your variable.) Thus functionCallValue does not automatically update, if you change the parameters (which would make no sense at all), you need to call the function again with the altered parameters.
For something like an auto-update you need a closure like this:
var asdf = (function(){
var param1 = 1;
var param2 = 2;
var result = param1+param2;
function compute(){
result = param1 + param2;
}
return{
param1:function(x){
param1 = x;
compute();
},
param2:function(x){
param2 = x;
compute();
},
result:function(){
return result;
}
}
})();
console.log(asdf.result()); // logs 3
asdf.param1(3);
console.log(asdf.result());​ // logs 5
Demo

var x, y = 'foo'; Can this be accomplished?

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;

Categories

Resources