Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
April 4, 2022 06:53 pm GMT

Scoping In JavaScript

In JavaScipt, scoping is the able of accessing variables. Back in the day, you could only use the keyword var to declare a variable. It was a terrible practice of declaration. When variables are declared with the keyword var, it cant have a block scope. For example, when declaring a variable inside a {} block, it can also be accessed outside of the {} block.
ex:

{   var a = 1;}// a can be used here

Meaning you could of created a variable inside of the block and declare the same variable locally. Both of these variables would of modified the variable.
To fix this problem, JavaScript introduced two new keywords: let and const. let is used to declare a variable inside a block scope. const keyword is used when you dont want the variable to change its value after it was declared.

The two ways of scoping is Global scope and Function Scope. Any variable declared outside of a function can be used Globally. These variables can be accessed from anywhere in the file.
ex:

let x = 0 // Global Scope

A variable declared inside a function arent accessible or in other words, visible from outside the function. This is known as function scope. It is accessible only within the scope of the function.
ex:

function x(){   let y = 1 // Function Scope}

Original Link: https://dev.to/rusty619/scoping-in-javascript-22on

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