Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

135
Views
JavaScript convert string to operator

I am trying to convert a string representation of an operator to the operator itself in comparisons.


For example, something like

{obj1} '==' {obj2}

should be:

{obj1} == {obj2}

OR

{obj1} '!==' {obj2}

should be:

{obj1} !== {obj2}

I can use eval(), but that forces the objects to be compared to be converted to a string, causing === (strict type check) comparisons useless.

For example, in the following example, eval would give wrong results:

const obj = "5"
const obj2 = 5

const operator = '===';

eval(`console.log(${obj} ${operator} ${obj2})`) //outputs true, incorrect (obj is of type string, obj2 is of type number)

console.log(obj === obj2) //outputs false, correct

How should I approach this?


Possible approach

One way that I came up with is just to go through the if else ladder and let js handle the comparison instead of parsing the comparison operator.

Something like

if(condition === '!=='){
  return before_OrderRequest.Id !== after_OrderRequest.Id
}else if (condition === '==='){
  return before_OrderRequest.Id === after_OrderRequest.Id
}
//...more if statements
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You can define an object with the string representation of operators as properties that return an arrow function performing the corresponding comparison.

const compare = {
  '==': (a, b) => a == b,
  '!=': (a, b) => a != b,
  '===' : (a, b) => a === b,
  '!==' : (a, b) => a !== b
}

const obj1 = 1;
const obj2 = 2;

console.log(compare['=='](obj1, obj2))
console.log(compare['!='](obj1, obj2))
console.log(compare['==='](obj1, obj2))
console.log(compare['!=='](obj1, obj2))

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!