Home > Blockchain >  problem with javascript array assignment, how can " == true : false" working in this code?
problem with javascript array assignment, how can " == true : false" working in this code?

Time:10-14

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.

CodePudding user response:

It should be:

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

Or as Array.isArray() returns a boolean, simply:

function checkIsArray(couldBeAnything) {
  return Array.isArray(couldBeAnything);
}

CodePudding user response:

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.

CodePudding user response:

I think you are not 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)
}

CodePudding user response:

The Conditional operator is supported in many programming languages. This term usually refers to ?:

enter link description here

  • Related