Proof of Work based Consensus protocols in a blockchain network utilizes block difficulty number to control average time taken to find a new block. For ex. Bitcoin network block generation time is approx 10 minutes ( 2016 block over a period of 2 weeks).So,if 2016 blocks are found in less than 2 weeks, bitcoin blockchain network difficulty increases, and if it took more than 2 weeks difficulty decreases for next 2016 blocks.

Then, How Exactly Difficulty is Calculated ?

If last 2016 blocks took time T, then new difficulty will be 2 weeks / T.

Bitcoin protocol has defined maximum variance to be 1/4th to 4 times of current difficulty.

In bitcoin network miners compete to add next block in blockchain for that they have to calculate SHA256 hash of current block header which has to be less than current target specified by network.

Lowest difficulty defined in bitcoin network 1 which corresponds to highest possible target of 0x1d00ffff.

0x1d00ffff is a shorthand notation of base 256 in big endian order.
1d is exponent
00ffff is mantissa.
base is 256

We will calculate current target based on current difficulty.

Following code uses bignumber.js library

  var base = new BigNumber(256);
  var hTargetCompact = '1d00ffff';
  var e = hTargetCompact.slice(0,2); //First Byte 
  var exponent = new BigNumber(e,16);
  //Three Significant Bytes less
  exponent = exponent.minus(3); 
  var m = hTargetCompact.slice(2);
  //Three Significant Bytes
  var mantissa = new BigNumber(m,16);
  var hTarget = mantissa.times(base.toPower(exponent));

  var d = new BigNumber('1.19679269409879e12');
  // Current Difficulty 1196792694098.79
  var cTarget = hTarget.div(d).ceil();
  // Output Current Target in Hex

Highest possible target(difficulty 1) can be written in hex as:
which is 0x00ffff * 2 ** 208 possible outcomes.

SHA256 hash is a random number between 0 to 2^256 - 1.

Probabilty of finding a hash less than highest possible target is 2 ** 224 / 2 ** 256 = 2 ** -32.

That means 2 ** 32 hashes in 10 minutes at diffculty D will find a block.
which is equal D * 2 ** 32 / 600 hashes per second, and at difficulty 1 it was approx 7 MH per second.

Today at the time of writing this article difficulty is 1196792694098. So 1196792694098 * 2 ** 32 / 600 per second is average Network Hashrate which is 8566974812 GH per second approx.