Golang Tutorials - Learn Go Programming with Easy Step-by-Step Guides

Explore comprehensive Golang tutorials for beginners and advanced programmers. Learn Go programming with easy-to-follow, step-by-step guides, examples, and practical tips to master Go language quickly.

Js Scope in JavaScript

Js Scope in JavaScript

? JavaScript Scope

Scope defines the accessibility or lifetime of variables and functions in your code. It determines where a variable can be accessed.


Types of Scope in JavaScript

1. Global Scope

  • Variables declared outside any function or block.

  • Accessible from anywhere in the code.

var globalVar = "I'm global";function test() {  console.log(globalVar);  // Accessible here}test();console.log(globalVar);    // Accessible here too

2. Function Scope

  • Variables declared inside a function using var are scoped to that function.

  • Not accessible outside the function.

function example() {  var localVar = "I'm local";  console.log(localVar);  // Works here}example();console.log(localVar);    // Error: localVar is not defined

3. Block Scope (ES6+)

  • Variables declared with let or const inside {} blocks (like inside if, for) are scoped to that block.

if (true) {  let blockVar = "I'm block scoped";  const blockConst = 42;  console.log(blockVar);    // Accessible here}console.log(blockVar);      // Error: blockVar is not definedconsole.log(blockConst);    // Error: blockConst is not defined

Scope Chain

  • When accessing a variable, JavaScript looks in the current scope.

  • If not found, it looks in the outer scope, continuing up to the global scope.

  • If variable is not found anywhere, it's undefined or throws ReferenceError if accessed before declaration (for let/const).


Example of Scope Chain

let a = "global";function outer() {  let b = "outer";  function inner() {    let c = "inner";    console.log(a); // global    console.log(b); // outer    console.log(c); // inner  }  inner();}outer();

Summary

Scope TypeDeclared WithAccessible Where
Globalvar, let, const outside functionsEverywhere
Functionvar inside functionsOnly inside the function
Blocklet, const inside blocksOnly inside the block {}

If you want, I can also explain hoisting and how it relates to scope!

Disclaimer for AI-Generated Content:
The content provided in these tutorials is generated using artificial intelligence and is intended for educational purposes only.
html
docker
php
kubernetes
golang
mysql
postgresql
mariaDB
sql