简体   繁体   中英

Is there a walrus operator in Node.Js?

In Python3.8 There is new operator called walrus which can assign new variables inside a condition. Is there something similar to it in Node.Js ?

my_var = 5
if (result := my_var == 5):
    print(result)

There's no need for a separate operator, assignment is already an expression in Javascript:

"use strict";
var my_var = 5;
var result;
if (result = my_var == 5){
  console.log(result)
}

Assign and compare as one expression. To make it work in strict mode and avoid linter complaints, add parentheses to the assignment.

const my_var = 5;
let result;
if ((result = my_var) === 5) {
  console.log(result);
}

https://eslint.org/docs/rules/no-cond-assign#except-parens

You can do it like this:

const myNumber = 2;
let newNumber;

if (newNumber = myNumber === 2) {
  console.log('this works!');
}

It's kind of the same, it has an assignment and a comparison in the same line. You can obviously substitute your problem with this:

const my_var = 5;
let result;
if(result = my_var === 5) {
 console.log(result);
}

As you can see it's obligatory to have a let declaration before-hand.

This can't work unless you're not using strict mode. It's to prevent mistakes.

You can see this part of the document on MDN for more info

You can do what @juanpa.arrivillaga mentioned if you don't use strict mode, which I strongly advise again. Strict mode will save you 100x more headache than it will make you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM