0

In Get the real width and height of an image with JavaScript? (in Safari/Chrome), a claimed clever solution is made on how to figure out the actual size of an image.

var t = new Image();
t.src = (img_element.getAttribute ? img_element.getAttribute("src") : false) || img_element.src;

I'm trying to figure out what the second row does. I know the source that I want to use and thus simply declared it. This did not result in any other attributes, such as t.width.

Community
  • 1
  • 1
Himmators
  • 14,278
  • 36
  • 132
  • 223
  • 1
    Try for yourself with truthy and falsy values of foo/bar/fobar. Write a test program. I answered anyway cuz it was kind of fun but you really should have worked on this on your own more. – djechlin May 16 '13 at 14:59
  • 1
    In this particular case the problem is that the image has not been loaded when you try to determine its dimensions. This has nothing to do with the logic – user123444555621 May 16 '13 at 15:07
  • @Pumbaa80 I realized that aswell! thanks though! – Himmators May 16 '13 at 15:09

4 Answers4

1

Same as

if(foo){ 
    if(bar) {
         bar;
    }
    else {
        xyz;
    }
else {
    if(fobar) {
          fobar;
    }
    else {
        xyz;
    }
}

In your real life case since fobar is false

if(foo){ 
    if(bar) {
         bar;
    }
    else {
        xyz;
    }
else {
    xyz;
}

So

if(foo && bar) {
    bar;
}
else {
    xyz;
}
djechlin
  • 59,258
  • 35
  • 162
  • 290
  • But you forgot the assignment? Those ifs are statements, while his expression has a result value. – Bergi May 16 '13 at 15:05
1

First, we check where there is such thing like getAttribute, some field/method belonging to img_element. Actually, this check is, ti judge strictly, insufficient, since getAttribute can be literally anything, and, while we check it to be equal to true, we then are trying to call getAttribute as if it is a function, which is not guaranteed by our check.

But we assume that if some object have getAttribute, it is a DOM function and not something else. In javascript such assumptions are quite common.

So, we first check whether img_element has getAttribute, and if it has, we check "src" attribute. And it is a truthy string then we are done here. If not, we are making last attempt, by checking .src directly.

The snippet you've provided is actually about that we should first check attribute and then - the field directly.

shabunc
  • 23,119
  • 19
  • 77
  • 102
0

It will test if img_element.getAttribute ? img_element.getAttribute("src") : false) equals something else than false

if the test equals false, it test if img_element.src different false and else returns false

Pouki
  • 1,654
  • 12
  • 18
0
var x = false,
    y = x || true;

In this case, y will be true, it is an OR operator, it checks if first OR second(in this order) is true; if both are false, then returns false. Otherwise, returns the first element that is true.

Niccolò Campolungo
  • 11,824
  • 4
  • 32
  • 39