ReasonJun

javascript : Scope, Garbage Collection 본문

Frontend/Javasciprt

javascript : Scope, Garbage Collection

ReasonJun 2023. 6. 7. 01:35
728x90

Scope

In JavaScript, the term "scope" refers to the context in which variables, functions, and objects are declared and accessed. It determines the visibility and lifetime of variables and the availability of functions and objects in different parts of your code.

JavaScript has function scope and block scope:

  1. Function Scope: Variables declared inside a function are locally scoped, meaning they are accessible only within that function. They are not visible outside the function.

Example:

function myFunction() {
  var x = 10; // locally scoped variable
  console.log(x);
}

myFunction(); // Output: 10
console.log(x); // Error: x is not defined

In this example, the variable x is scoped to the myFunction function and cannot be accessed outside of it.

  1. Block Scope: Introduced in ECMAScript 2015 (ES6), block scope allows variables to be scoped within blocks of code, such as within an if statement or a for loop. Variables declared with let and const keywords have block scope.

Example:

function myFunction() {
  if (true) {
    let y = 20; // block-scoped variable
    console.log(y);
  }

  console.log(y); // Error: y is not defined
}

myFunction(); // Output: 20

In this example, the variable y is scoped to the block within the if statement and is not accessible outside of it.

It's important to note that variables declared without any explicit keyword (var, let, or const) are automatically assigned global scope. Global variables are accessible throughout your entire code, including within functions and blocks.

 

Example:

var z = 30; // global variable

function myFunction() {
  console.log(z);
}

myFunction(); // Output: 30
console.log(z); // Output: 30

In this example, the variable z is globally scoped, so it can be accessed both inside the myFunction function and outside of it.

 

Understanding scope is crucial for writing maintainable and bug-free JavaScript code. Properly managing scope helps prevent naming conflicts, improves code readability, and ensures that variables and functions are accessed and modified in the intended places.

 

Garbage Collection

// garbage collection
// How JavaScript manages memory
// Release data that is no longer used from the memory allocated to the data.
// This function cannot be enforced/managed directly by the developer.

// Global variables remain in memory until the app is closed! Therefore, do not declare it as much as possible.

728x90
Comments