Code highlights logo

Learn

Scope

Practice Good Scoping

  1. Avoid Global Variables Global variables can lead to unexpected side effects and make code difficult to debug. Encapsulate variables within appropriate scopes to maintain control.
    1// Avoid
    2globalVar = 'I am global';
    3
    4// Prefer
    5function myFunction() {
    6 let localVar = 'I am local';
    7}
  2. Use Function Scope Localize variables within function scopes to prevent name conflicts and encourage modular programming.
    1function calculateArea(radius) {
    2 const PI = 3.14159;
    3 return PI * radius * radius;
    4}
  3. Declare Variables Properly Use let or const instead of var to create block-scoped variables, restricting their usage to the appropriate scope.
    1if (true) {
    2 let blockScopedVar = 'I am confined to this block';
    3 }
  4. Avoid Reusing Variable Names Descriptive names that represent the purpose and context of variables prevent confusion and errors.
    1// Avoid
    2let name = 'John';
    3function greet() {
    4 let name = 'Doe';
    5}
    6
    7// Prefer
    8let firstName = 'John';
    9function greet() {
    10 let lastName = 'Doe';
    11}
  5. Use Proper Naming Conventions Clear and descriptive names improve readability and reduce scope-related issues.
    1// Descriptive naming
    2let userAge = 25;
    3function calculateDiscount(price) { /* ... */ }

Instructions

1.

Declare another function showLocalVar() inside the checkScope() function.

2.

Inside the showLocalVar() function, console.log the variable localVar.

3.

Call the showLocalVar() function inside checkScope() function.

Sign up to start coding

Already have an account?

Sign In

Course content