Scope of variables in Javascript

Submitted 3 years, 2 months ago
Ticket #351
Views 248
Language/Framework Javascript
Priority Medium
Status Closed

What is the scope of variables in javascript?

Any answer along with examples will be really helpful...........

Submitted on Feb 14, 21
add a comment

1 Answer

Verified

JavaScript, starting with ES6, offers 3 types of scope:
- global scope - using var  - (not recommanded; for backward compatibility)
- block scope - using let or const - (recommanded approch)
- function scope - variables declared inside a function

OBS:

1. const doesn't allow you to change the value of a variable after declaring it. Just like a constant.

2. It doesn't matter if you use var, let, or const to declare variables inside a function. They aren't visible outside that function, unless returned.
Module Design Pattern is based on this approch.
 

// global scope example
const PI = 3.1415;

if(PI == 3.1415) {
  var euler = 2.72
  euler++
}

console.log(euler);  // output: 3.72


// functional scope example
function say_boo(){
  var boo = "Boo"
  
  console.log(boo);
}

say_boo();  // output: "Boo"

console.log(boo); // output: "error"


// block scope example
const PI = 3.1415;

if(PI == 3.1415) {
  let euler = 2.72
  euler++
}

console.log(euler);  // output: "error"

Submitted 3 years, 2 months ago

@bhanu could you please confirm whether this resolved or not?.

- Vengat 3 years, 2 months ago


Latest Blogs