• Jobs
  • About Us
  • professionals
    • Home
    • Jobs
    • Courses and challenges
  • business
    • Home
    • Post vacancy
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

275
Views
problem with javascript array assignment, how can " == true : false" working in this code?

I am studying javascript and here is my problem.

They gave me the variable named "couldBeAnything" which can be any data type. And another variable which named result, too. I must check if the given variable is array then assign true to result. Other cases then false to result. Here is the code.

function checkIsArray(couldBeAnything) {
var result = true ? Array.isArray(couldBeAnything) == true : false
return result;
}

Sorry for my wonder, because this code is from my senior, so I can not understand it clearly, I just only understand if else, so could you please explain this code for me ? How dose it work ? Thank you very much.

almost 3 years ago · Juan Pablo Isaza
2 answers
Answer question

0

This is working because it's doing several pointless operations that complicate reading it, but it's really just using Array.isArray.

Array.isArray(couldBeAnything) == true

If an array is passed in, Array.isArray is true, true == true is true.

So what you get is, if an array is passed in:

var result = true ? true : false;

Which is true.

And for a non-array:

var result = true ? false : false;

Which is false.

This is hopefully the result of several refactorings or lazy merges, because writing this on purpose is pretty silly as others have stated.

almost 3 years ago · Juan Pablo Isaza Report

0

I think you are have not been exposed to ternary operators.

let x=true
let result
if(x){
  result="Thats true"
}
else{
  result="No thats false"
}
console.log(result)

The above can be written as

let x=true
let result=x?"That's true":"No that's false"
console.log(result)

The logic is that if the expression before ? is true then the code after the ? will be executed and if it's false then the code after : will be executed.

That's simple, right?

In your case the code is wrong. It should be like this:

function checkIsArray(couldBeAnything) {
 var result = Array.isArray(couldBeAnything) ? true : false
 return result;
}

But there is no need for ternary conditions here. You can directly use this

function checkIsArray(couldBeAnything) {
   return Array.isArray(couldBeAnything)
}
almost 3 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 Our process Sales
Legal
Terms and conditions Privacy policy
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recommend me some offers
I have an error