Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't the OR operation "||" replace the ternary operator "? :" in this JavaScript code?

Tags:

javascript

The following code works in a browser:

var event = event || window.event; 
var eTarget = event.target || event.srcElement; 
var eTargetId = eTarget.id;

When I change it to

var eTargetId = event.target ? event.target.id : event.srcElement.id;

it works, too.

When I change the code to

var eTargetId = event.target.id || event.srcElement.id;

it doesn't work in IE 678. I get the following error:

SCRIPT5007:Object expected.

Why is this happening?

like image 973
xiaoJay Avatar asked Dec 28 '16 02:12

xiaoJay


1 Answers

This is likely happening because event.target is null but event is not. Your first two attempts use short-circuiting to prevent further evaluation if event.target is null.

like image 162
Robert Columbia Avatar answered Sep 25 '22 13:09

Robert Columbia