0

I came across the following code in the Typescript docs:

function createSquare(config: SquareConfig): { color: string; area: number } {
    let newSquare = {color: "white", area: 100};
    if (config.color) {
        newSquare.color = config.color;
    }
    if (config.width) {
        newSquare.area = config.width * config.width;
    }
    return newSquare;
}

If let variables are only visible within their block scope - why does this not throw an error? newSquare is initialised, but then modified within a new block scope where (as I understand it) it should not be visible?

DJC
  • 1,175
  • 1
  • 15
  • 39
  • 5
    any blocks that are inside the current block will see the let variable too. – toskv Feb 07 '18 at 16:41
  • 3
    Within their block scope means that they are in the same block **OR** in a block within the defining block. – Twometer Feb 07 '18 at 16:42
  • 1
    right, if you declared it in the first `if` statement, it would not be available outside of that if statement. – ps2goat Feb 07 '18 at 16:42
  • Two things that might help: those if blocks are nested within the function block where the variable is defined. Also, let and const variables whose values are complex (object, array) can be modified. – mikkelrd Feb 07 '18 at 16:42
  • Why would this throw an error? – evolutionxbox Feb 07 '18 at 16:43
  • @evolutionxbox "newSquare is not defined" error if it wasn't in scope - but as others above have explained, it is in scope – DJC Feb 07 '18 at 17:08
  • @toskv gotcha, thanks – DJC Feb 07 '18 at 17:10

0 Answers0