0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

[TS/JS] Logical Assignment Operatorの挙動

Posted at

挙動のメモ書き

/**
 * Logical Assignment Operators
 */

{
  /**
   * Logical AND assignemnt
   * 
   * @link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_AND_assignment
   */
  const log = (...args: any[]) => console.log("#AND", ...args);

  let a1 = undefined;
  a1 &&= "this is NOT new value"; // 🙅‍♀️
  log({ a1 });

  let b1 = "this is prev value";
  b1 &&= "this is new value"; // 🙆‍♂️
  log({ b1 });

  let c1 = "";
  c1 &&= "this is NOT new value"; // 🙅‍♀️
  log({ c1 });
}

{
  /**
   * Logical OR assignemnt
   * 
   * @link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_OR_assignment
   */
  const log = (...args: any[]) => console.log("#OR", ...args);

  let a1 = undefined;
  a1 ||= "this is new value" // 🙆‍♂️
  log({ a1 });

  let b1 = "this is prev value";
  b1 ||= "this is NOT new value"; // 🙅‍♀️
  log({ b1 });

  let c1 = "";
  c1 ||= "this is new value"; // 🙆‍♂️
  log({ c1 });
}

{
  /**
   * Nullish coalescing assignment
   * 
   * @link 
   */
  const log = (...args: any[]) => console.log("#NULLISH", ...args);

  let a1 = undefined;
  a1 ??= "this is new value" // 🙆‍♂️
  log({ a1 });

  let b1 = "this is prev value";
  b1 ??= "this is NOT new value"; // 🙅‍♀️
  log({ b1 });

  let c1 = "";
  c1 ??= "this is NOT new value"; // 🙅‍♀️
  log({ c1 });
}

0
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?