Search code examples
typescriptnestjsdestructuring

After destructuring assignment with 'let', can't I ressign a variable of them?


In practicing NestJS..

DTO is being used in Controller and I declared 3 variables for them by destructuring assignment. At this time, I used 'let' keyword when declaring for a test.

export class SignUpDto {
  name: string;
  email: string;
  readonly password: string;
}
  @Post()
  async signUp(@Body() signUpDto: SignUpDto): Promise<void> {
    let { name, email, password } = signUpDto;
    console.log(1, name);
    if (!name || !email || !password) {
      throw new BadRequestException();
    }
    name = 'new name';
    console.log(2, name);
    console.log(signUpDto.name);
    await this.usersService.signUp(signUpDto);
  }

Right after declaration, 'name' has the value that REQ's body has.('username') so I changed its value to 'new name'

and then 'name' variable printed 'new name' in console when I log only 'name' variable. But, when I log 'signUpDto.name', it still prints 'username'.

// console.log(1, name);
1 username

// console.log(2, name);
2 new name

// console.log(signUpDto.name);
username

// the result returned from usersService
UsersService { name: 'username', email: '[email protected]', password: 'PassWord' }

I've read official documents but I couldn't find a correct reason.

One of my idea is that they were stored in different locations in a memory so they prints different values.

Could you let me know what this does mean? I don't know why 'name's value isn't changed..


Solution

  • When you destructure the object out via the let { name } = body you are creating a new variable named name. This value is a accessed by value, not by reference, so when you modify it, it does not modify the original objects value too.