Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
December 17, 2021 03:27 pm GMT

Scope in JavaScript(var, let, const)

Scope in JavaScript is divided into the Block Scope, Function Scope and the Global Scope.

Starting with the Global Scope

// Global scopevar a = 1;let b = 2const c = 3console.log(`Global Scope ${a} ${b} ${c}`)
  • This is a global scope and everything is fine, if you console.log the value

Function Scope

// Global scopevar a = 1let b = 2const c = 3//Function scopefunction num() {  var a = 10  let b = 22  const c = 5  console.log(`Function Scope ${a} ${b} ${c}`)}num()console.log(`Global Scope ${a} ${b} ${c}`)

So inside the function scope we get our 10, 22, 5 while in the global scope we still get our 1, 2, 3, because they are different variables in different scope.

  • Var is a Function scope It means they are only available inside the function theyre created in, or if not created inside a function, they are globally scoped..
var a = 1;let b = 2const c = 3for(var a = 0; a < 10; a++) {  console.log(a)}console.log(`Global Scope ${a} ${b} ${c}`)
  • The value of var a = 10 in the global scope.
  • The var a in the loop actually changes the value var a in the global scope which is not good, that's the reason let and const was created.

NOTE: var is kind of wired, that's one of the thing that lot of people didn't like about JavaScript. it causes security risks and it can cause confusion if you have some variables in the global scope.

Block Scope

// Global scopevar a = 1let b = 2const c = 3// Block Scopeif(true) {  var a = 6  let b = 7  const c = 10  console.log(`Block Scope ${a} ${b} ${c}`)}console.log(`Global Scope ${a} ${b} ${c}`)

What do you think the global scope var a result will be?

  • The result will be var a = 6 because after declaring the var a = 1 on the global scope it was change in the block scope.

  • Notice the let and const didn't change, in the global scope they retain their values and also in the block scope.

Benefit of let & const

  • They aren't scoped to the function, they are scoped to the block.
  • What is the block? A block is a set of opening and closing curly brackets.

Points to Take

  • var is function scope.
  • let and const are block scope.
  • Function scope is within the function.
  • Block scope is within curly brackets.

Original Link: https://dev.to/eworld/scope-in-javascriptvar-let-const-i1

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To