The world is all about Variables !

The mischief of var

var has been the traditional way of declaring variables in JS but it has got its own drawbacks..

Now let us see the functioning of var in action.

Consider an example

function firstFunction() {
  var a = 10;
  return function secondFunction() {
    var b = a + 1;
    return b;
  };
}
var g = firstFunction();
secondFunction(); // returns '11'

What is the intuition that one can build here?

Try this now, what does the below code return?

function f() {
  var a = 1;
  a = 2;
  var b = g();
  a = 3;
  return b;
  function g() {
    return a;
  }
}
f(); // returns what ?  //%{rendu}%

Scopes 🔭

As we have made some observations; bluntly put the scopes in JS are of three kinds:

{
  let val1 = 2;
}
// val1 can NOT be used here

#####################################

{
  var val2 = 3;
}
// val2 CAN be used here


######### TRY IN BROWSER CONSOLE ###########

var globalVar =5; //window scope

function fun1() {
    var localVar = 10;
    console.log(globalVar);
}

//now call fun1()
fun1();

// now try to access localVar in global scope
console.log(localVar);

what if a local scoped variable & a global scopes variable have the same name ?

ans: Generally, it is not a good coding practice. Yet, to say the preference will be given to the local variable.

Try in console:

var a =10;

function fun() {

var a = 5;

console.log(a);

}

fun(a);

let and const: the new members of the family

let is all about the Block scoping

function f(input: boolean) {
  let a = 100;
  if (input) {
    // Still okay to reference 'a'
    let b = a + 1;
    return b;
  }
  // Error: 'b' doesn't exist here
  return b;
}

Here, we have two local variables a and ba’s scope is limited to the body of f while b’s scope is limited to the containing if statement’s block.

Re-declaring and shadowing

function f(x) {
  var x;
  var x;
  if (true) {
    var x;
  }
}

//all declarations of x actually refer to the same x, and this is perfectly valid. 
//This often ends up being a source of bugs. 
//Thankfully, let declarations are not as forgiving.

let x = 10;
let x = 20; // error: can't re-declare 'x' in the same scope

function g() {
  let x = 100;
  var x = 100; // error: can't have both declarations of 'x'
}

What is const doing then ?

All variable declarations other than those you plan to modify should use const

That’s all folks!