DEV Community

Himanshu Baghel
Himanshu Baghel

Posted on

Variable in ReactJS(all about)

What is variable ?
Variable is like a container or box which used for store data(info,value etc).

History -
In past before ES-6(ECMA Script 6) there are only one way of definig variable like var x=8.5 but now after ES-6 there are 3 way of defining variable i.e var, let and const.

Explain -

Var

  1. The var statement declares a function-scoped or globally-scoped variable, optionally initializing it to a value.
  2. Default value is undefined.
  3. Var first declare then used otherwise it show undefine error.
  4. If you use var outside of a function, it belongs to the global scope.
  5. If you use var inside of a function, it belongs to that function.
  6. If you use var inside of a block, i.e. a for loop, the variable is still available outside of that block.
function foo() {
  var x = 1;
  function bar() {
    var y = 2;
    console.log(x); // 1 (function `bar` closes over `x`)
    console.log(y); // 2 (`y` is in scope)
  }
  bar();
  console.log(x); // 1 (`x` is in scope)
  console.log(y); // ReferenceError, `y` is scoped to `bar`
}

foo();
Enter fullscreen mode Exit fullscreen mode

let

  1. let Declaration declares a block-scoped local variable, optionally initializing it to a value.
  2. If you use let inside of a block, i.e. a for loop, the variable is only available inside of that loop.
function var() {
  var x = 1;
  {
    var x = 2;  // same variable!
    console.log(x);  // 2
  }
  console.log(x);  // 2
}

function let() {
  let x = 1;
  {
    let x = 2;  // different variable
    console.log(x);  // 2
  }
  console.log(x);  // 1
}
Enter fullscreen mode Exit fullscreen mode

const

  1. const is a variable that once it has been created, its value can never change.
  2. It does not define a constant value. It defines a constant reference to a value.
  3. Because of this you can NOT:
  4. Reassign a constant value
  5. Reassign a constant array
  6. Reassign a constant object

But you CAN:

  • Change the elements of constant array
  • Change the properties of constant object
// define MY_FAV as a constant and give it the value 7
const MY_FAV = 7;

// this will throw an error - Uncaught TypeError: Assignment to constant variable.
MY_FAV = 20;

// MY_FAV is 7
console.log("my favorite number is: " + MY_FAV);

// trying to redeclare a constant throws an error
// Uncaught SyntaxError: Identifier 'MY_FAV' has already been declared
const MY_FAV = 20;

// the name MY_FAV is reserved for constant above, so this will fail too
var MY_FAV = 20;

// this throws an error too
let MY_FAV = 20;
Enter fullscreen mode Exit fullscreen mode

Thank You.

Top comments (2)

Collapse
 
naucode profile image
Al - Naucode

Hey, that was a nice read, you got my follow, keep writing šŸ˜‰

Collapse
 
himanshubaghel07 profile image
Himanshu Baghel

Thank you Naubit