-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.

j08691
  • 204,283
  • 31
  • 260
  • 272
  • Well what is your question? You seem to already know what is happening. – Adder Jun 12 '20 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](https://tc39.es/ecma262/#sec-binary-logical-operators)) – Andreas Jun 12 '20 at 15:21
  • What is your expected result? – Michele Della Mea Jun 12 '20 at 15:23

1 Answers1

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
epascarello
  • 204,599
  • 20
  • 195
  • 236
  • i said i dont understand first shows me "1" and then "undefined". i dont understand why and how it works ? – halilibrahimtosun Jun 12 '20 at 16:26
  • I am not sure how else to explain it. Do you understand how && works? What are you expecting it to be? – epascarello Jun 12 '20 at 17:55
  • 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 – halilibrahimtosun Jun 12 '20 at 18:17
  • 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. – epascarello Jun 12 '20 at 19:05