Logical operators Javascript && [duplicate] - javascript

This question already has answers here:
Does JavaScript have "Short-circuit" evaluation?
(3 answers)
Closed 2 years ago.
When I run this code firstly shows me 1 and then undefined. But I still couldn't understand it.
alert(alert(1) && alert(2));
Here is some explanation :
The call to alert returns undefined (it just shows a message, so there's no meaningful return).
Because of that, && evaluates the left operand (outputs 1), and immediately stops, because undefined is a falsy value. And && looks for a falsy value and returns it, so it's done.

alert does not return anything
So alert(1) runs, since alert does not return anything it is undefined. As a result you have alert(undefined && alert(2)). The alert(2) will not execute because left part needs to be truthy to execute. Undefined is falsey. That evaluates to alert(undefined).
So you get alert of 1 for the first alert and you get undefined for the outside alert and the alert(2) is never executed.
Code written out in a less confusing manner
var action = alert(1) && alert(2) // only runs alert(1)
console.log(action) // shows variable is undefined
alert(action) // alerts undefined

Related

Checking value with JavaScript [duplicate]

This question already has answers here:
How does the single equal sign work in the if statement in javascript
(6 answers)
Closed 3 years ago.
This is my general code (in JavaScript):
let x = Math.floor(Math.random()×6)+1);
if (x=1){
do this
} else if (x=2){
do that
} else if.... and so on.
Whenever I test this code in a browser, only actions that could happen in the {do this} section happen. x is being locked as 1, even though it is meant to be a fair 6 sided die. Any ideas why this is happening, and how I can fix it?
The = operator in JavaScript is for assignment. x=1 will always return true because that is an assignment that will never fail. To test for equality use == (equality with conversion) or === (strict equality).
You have your if (x=1) assigning the value of 1 to x, rather than checking if it's equal to it. This results in it always returning TRUE. Using a pair of == (or ===) will solve this.

Why does this `do`–`while` loop repeat the last value after the end? [duplicate]

This question already has answers here:
Javascript while loop return value
(3 answers)
In Javascript While loop repeats last number when counting from 1 to 5 when run on console [duplicate]
(2 answers)
Closed 4 years ago.
I tried the following code in the Google Chrome console and I’m getting this output. Why is there an additional 4 printed?
var i = 0;
do{
console.log(i);
i++;
} while(i < 5);
Output:
0
1
2
3
4
4
There is no extra 4 at end. Your loop is correct and works just fine :). That's return value of the i++ expression, which you are mistaking for console.log in developer console. Try this, you will figure it out;
var i=0;do{console.log('i = ', i);i++;}while(i<5);
Edit Thanks to #ggorlen for pointing this out, it's the return value of last expression in block({}) which is i++, i increments the value and returns it's last value (if i = 4; i++ returns 4 and makes value of i = 5), (++i, returns 5 and makes value of i = 5)
var i=0;do{console.log('i = ', i);++i;}while(i<5);
will give return value of 5
JavaScript has the concept of "Completion Records". Basically every statement produces a completion record.
The Completion type is a Record used to explain the runtime propagation of values and control flow such as the behaviour of statements (break, continue, return and throw) that perform nonlocal transfers of control.
You usually cannot do anything with these in user land code, but the runtime needs those to properly execute your program. However the Chrome console will print the value of the completion record of the last statement it executes.
Without going into to much details, here is what happens:
The value of the completion record of the do...while loop is the value of the completion record of its body.
The body is a block with a statement list. The value of the completion value of a statement list is the value of the completion record of the last statement in the list.
The last statement is an expression statement (i++;). The value of the completion record of an expression is the value the expression evaluates to.
The simplest example to demonstrate this behavior is simply
42;
The result of evaluating this expression statement is a completion record that looks something like
{
type: normal,
value: 42,
target: empty
}
You will see it print 42 in the console because that's the value of the completion record of the expression statement.
A slightly more evolved example:
if (true) {
42;
}
will print the same.
Yeah, it's normal that extra 4.
It's called expression evaluation. Id doesn't mean it's printing, but instead evaluating i to you.
Check here to know more about it.
This is just chrome helping you to know the dynamic environment of your variables.

Print undefined in console with no reason, Javascript [duplicate]

This question already has answers here:
Chrome/Firefox console.log always appends a line saying 'undefined'
(9 answers)
Closed 5 years ago.
I have the below block of code which in the console print "undefine" twice after "Hello"
JavaScript Code
function f()
{
function g() {
console.log("Hello");
}
return g;
}
var x = f()();
console.log(x);
While I am trying to print only "Hello", where is the two undefined printing from
Output in console
Hello
undefined
undefined
The first undefined is because f()() evaluates to whatever g returns, and g doesn't return anything. You store that undefined in x, then print it when you write console.log(x);.
I'm guessing the second undefined is the result of running this in a console. The last line containing console.log evaluates to undefined, which may be implicitly printed from the console/REPL. You can confirm this by adding something like the string "World" as the last line of the script. Adding anything else to the last line should get rid of the second undefined.

Removing undefined from javascript output [duplicate]

This question already has an answer here:
Console returns undefined [duplicate]
(1 answer)
Closed 7 years ago.
Running the following script in javascript or nodejs or any other javascript environment prints:
undefined
0
1
2
3
4
Script:
for(var i=0;i<5;i++){
var a = function (i) {
setTimeout(function () {
console.log(i);
},i*1000);
};
a(i);
}
Where does the undefined comes from?
When using a REPL environment, the expression you enter is evaluated and its result is returned.
In this case, the result is undefined. It's a side effect of the REPL, it's not part of the output of your code.
If you’re running it from the REPL, undefined is the completion value of the expression, which is a(4). a doesn’t return anything, so its return value is undefined, and the REPL prints that. It is not passed to console.log and won’t appear if you run it as a standalone script.

Weird usage of && outside of a if? [duplicate]

This question already has answers here:
What is "x && foo()"?
(5 answers)
Closed 8 years ago.
Let's say we have this function:
loadView : function(view) {
this.view && this.view.remove();
this.view = view;
}
What does the first line do? For example if the line was this.view && this.otherView, it would return true if both view and otherView exists and false if one of them doesn't, but now there is a function being called at the end, which is confusing me.
Is the first line equivalent to:
if(this.view) {this.view.remove()}
?
it's a short circuit evaluation.
If this.view is "falsey" then this.view.remove() will not be evaluated.
So the answer to your question is yes.
It's called a guard operator. You would usually use && in this way
if(thing1 === 1 && thing2 === 2){}
You'll notice we want to check if BOTH things return true. Well the way it works is that we know that 'thing 2 === 0' will never run if the first expression (thing1 === 1) doesn't evaluate to true. Why run the second expression if they both have to be true and the first one already failed. Taking that knowledge we can now use it as a guard to not run the second expression, unless the first expression it true, or in this case truthy.
So in your code, this.view.remove() only runs if this.view is truthy.

Categories