skip to Main Content

What’s the correct way to access x?

let x = 5
const f = (n:number)=> {
  let x = "Welcome";
  return x * n // First x not second x
  }

and what’s the correct technical name for this operation?

2

Answers


  1. One way is to use block scope and OR operator.

    {
      let x = 5
      const f = (n) => {
        x = x || "Welcome";
        return x * n // First x not second x
      }
      f(1)
    }
    

    Another way is to define x as a default paramter to f

    let x = 5
    const f = (n, z = x)=> {
      let x = "Welcome";
      return z * n // First x not second x
    }
    
    Login or Signup to reply.
  2. The correct way to access a shadowed variable is not to shadow it. Refactor the code by renaming either variable to something else – typically the local one (in the inner scope).

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search