-2

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.

3
  • Well what is your question? You seem to already know what is happening. Commented Jun 12, 2020 at 15:21
  • 1
    "The value produced by a && or || operator is not necessarily of type Boolean. The value produced will always be the value of one of the two operand expressions." (Source) Commented Jun 12, 2020 at 15:21
  • What is your expected result? Commented Jun 12, 2020 at 15:23

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

4 Comments

i said i dont understand first shows me "1" and then "undefined". i dont understand why and how it works ?
I am not sure how else to explain it. Do you understand how && works? What are you expecting it to be?
For each operand, converts it to a boolean. If the result is false, stops and returns the original value of that operand. If all operands have been evaluated (i.e. all were truthy), returns the last operand. Yes i understand exactly what mean above. it is firstly undefined. it is falsey . but it runs alert 1 and then shows me undefined. i dont get why it runs like that. i just want to grasb the main idea logically
Added code to the end. I think you are not grasping the fact that the outside alert runs. Code inside the alert is evaluated and then the alert is run. The code really does not make any practical sense so it is confusing.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.