Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)
like image 388
user14005342 Avatar asked Jul 27 '20 19:07

user14005342


People also ask

What is the walrus operator?

The walrus operator creates an assignment expression. The operator allows us to assign a value to a variable inside a Python expression. It is a convenient operator which makes our code more compact. We can assign and print a variable in one go.

Which version of Python has walrus?

The walrus operator was implemented by Emily Morehouse, and made available in the first alpha release of Python 3.8.

How does the walrus operator look in Python?

Assignment expression are written with a new notation (:=) . This operator is often called the walrus operator as it resembles the eyes and tusks of a walrus on its side. The assignment expression allows you to assign True to walrus , and immediately print the value.


2 Answers

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

like image 194
The Dev with No Name Avatar answered Sep 21 '22 13:09

The Dev with No Name


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)
}
like image 27
juanpa.arrivillaga Avatar answered Sep 23 '22 13:09

juanpa.arrivillaga