Get last return value - javascript

In nodeJS terminal, I can enter this expression and have as a return 'true':
> var x = true; x;
true
How can I capture this return value in a variable, without changing the expression?
The following is not working:
> var y = (var x = true; x)
SyntaxError: Unexpected token var

In node REPL, you can just use _ :
> var x = true; x;
true
> var y = _
undefined
> y
true

You can't use a statement as an expression.
x = true is an expression, and x is also an expression. var x = true is not an expression, it's a statement.
To use the expression you would declare the variable x first. The value of an assignment expression is the value that was assigned, so you don't need to put x; after the assignment (which helps as that makes it a statement):
var x; var y = (x = true);

Related

JS: assigning document.getElement... doesn't work with var/let (works without)

If I do
x = document.getElementsByClassName("something")[0]
I get the expected result.
But if I do
var x = document.getElementsByClassName("something")[0]
or
let x = document.getElementsByClassName("something")[0]
I get undefined.
Why is that?
Declaring a variable doesn't return anything (ie, undefined), however assigning a variable does return the value. For example:
let x, y
x = y = 7 // this sets both x & y to seven
The line above works because y = 7 returns the value of y which is then assigned to x. However you can't do anything with a variable declaration:
let x = 7
x = let y = 3 // syntax error
The point is that declaring a variable does not return a value, which is why you see undefined after it in console (also in node REPL), but assignments or other values that do return a value will display that value.
Note that you can do this:
var x = document.getElementsByClassName("something")[0]
x // this line will return the value of x
The document.getElementsByClassName will return the array named as HTMLCollection
Please have a look in this code,
var testElements = document.getElementsByClassName('test');
var testDivs = Array.prototype.filter.call(testElements, function(testElement){
return testElement.nodeName === 'DIV';
});
Also you can check the details here

If Statement Returning True All The Time

I am trying to check if the input is true, and continue to next word if false.
"Apples",
"Bananas",
"Pears",
"Door",
"Towel",
"Computer",
];
var x = myArray[Math.floor(Math.random()*myArray.length)];
function clearbox(){
if (x = myInput.value){
var x = myArray[Math.floor(Math.random();*myArray.length)]);
document.getElementById('myInput').value = ''
document.getElementById("word").innerHTML = x
} else {
document.getElementById('myInput').value = '' ;
}
};
For some reason the if statment is not working, can someone help please?
Your if statement if (x = myInput.value) should be using a boolean comparison operator (==), but you used an assignment operator (=) instead. As a result, the variable x is being set to the value myInput.value which will always return true, as values > 0 are interpreted to be true by the compiler. Instead, your function should read:
function clearbox(){
if (x == myInput.value){
var x = myArray[Math.floor(Math.random()*myArray.length)]);
document.getElementById('myInput').value = ''
document.getElementById("word").innerHTML = x
} else {
document.getElementById('myInput').value = '' ;
}
You should be using == instead of = which results in true always (you can also use === for type checking as well):
if (x == myInput.value)
You have a syntax error here (remove the ;):
var x = myArray[Math.floor(Math.random()*myArray.length)]);

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.

Why var x = 5 work and not var n = a?

Why am I able to write:
var x = 5;
console.log(x);
5
but when I write:
var n = a;
console.log(n);
Uncaught ReferenceError: a is not defined
Well, you don't have a variable a. Set it beforehand, like this:
var a = 10;
var n = a; // n is now also 10
If you want a character string, enclose the characters in quotes:
var n = "a"; // n is now a character string, not a number
When you write
var n = a;
then it means to set n's value the same value as variable a. But you haven't defined a yet, so you get an error message.
I think you mean the string "a", so use that:
var n = "a";
console.log(n);
Because a is not a defined variable as the error clearly states.
If you want to set n to the character 'a', then you need to put it in either single or double quotes.
n = 'a';
or
n = "a";
to print a in console,
var n = "a";
console.log(n);
print some other variable
var a = 10;
var n = a;
console.log(n);
Because you are trying to print out put of n which reference value of a which is undefined variable.
You are getting error instead of undefined because javascript does not allow you assignment of undeclared variable

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