skip to Main Content

I was seeing someone code , what is check(); that is used after every function ?

why in this code check(); function is called I think many times

var a = 0;
var b = 0;
var c = 0;

function logo(c) {
  let nolo = document.getElementById('logo');
  nolo.setAttribute('src', "Office.jpg");
  golo = nolo.getAttribute('src');
  if (golo === "Office.jpg") {
    window.c = 2;
  }
  check();
}

function myflipkart(a) {
  let olo = document.getElementById('flipkart');
  olo.setAttribute('src', "Office.jpg");
  polo = olo.getAttribute('src');
  if (polo === "Office.jpg") {
    window.a = 2;
  }
  check();
}

function mybird(b) {
  let lo = document.getElementById('bird');
  lo.setAttribute('src', "Office.jpg");
  bolo = lo.getAttribute('src');
  if (bolo === "Office.jpg") {
    window.b = 2;
  }
  check();
}

function check() {
  if (a && b && c === 2) {
    console.log("Hello");
  }
}

2

Answers


  1. It is checking if the three elements (logo, flipkart and bird) contain an image named "Office.jpg" in the src attribute.

    What the function is doing is checking if the global variables a and b are true (i.e. different from 0) and if c is equal to 2.

    In javascript when we check a variable with zero value, the return is false and any number above 0 is true.

    Login or Signup to reply.
  2. The code is incorrect.

    It is trying to test if all images have been loaded and if they have, it will
    console.log hello

    But this test is not doing what the write expects. It works by chance because 2 is truthy

    if (a && b && c === 2) {
      console.log("Hello");
    }
    

    So actually it should either be

    if (a === 2 && b === 2 && c === 2) {
      console.log("Hello");
    }
    

    OR use false and true instead of 0 and 2 and use

    if (a && b && c) {
     console.log("Hello");
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search