Java script programming -Can it be done?

Java script programming -Can it be done?
0

#1

Hi guys, i was just wandering if i can write anything to make 12<“10” be considered as not logical and that the user has to input 2 numbers without adding more code to my program.something as simple as 12<==“10” which i know doesn’t exist in JS but i’m looking for the realistic equivalent of that just like we do with == and ===.


#2
  • If you mean the user can input anything into the function, so you do not know in advance if it’s a string that is not readable as a number (ie it could be 1, "1", or "one" then you are going to have to check what the type of input is via Number.isInteger or whatever.
  • If you mean that the input is a number or a string with only numbers (ie it could be 1 or "1") then you can force coerce to a number for both - +x < +y (note the +), same as Number(x) < Number(y).

What you’re asking for is strong typing, which JS does not have, though Typescript and Flow can both give you that (you can specify the type of arguments to be integers or whatever, so your issue simply shouldn’t exist with either of those)


#3

your first solution would make me add more code which can be done easily in several ways.As for the 2nd solution i honestly cannot understand it :smiley: . In your conclusion u’re simply saying it doesn’t exist in JS…why something so simple which we already have as == and === does not exist in the rest of the comparisons ? and why does the JS by nature converts strings to integers and vice versa? it’s a bit annoying to anyone who has tried several programming languages before and i haven’t faced that issue before.


#4

Welcome to wonderful world of JavaScript coercion.


#5


#6

In the second one I’m just forcibly coercing input to a number, that’s all. Still adding code, just not much. It’s just guarantee two numbers are compared.

function lt(x, y) {
  return +x < +y;
}

JavaScript attempts to return a value for everything you do (as opposed to throwing errors when you hand it nonsense), it’s pretty much unique. Weakly typed and dynamic and coerces almost anything to a value. Most languages have last-resort escape hatches that let you do similar (like OCaml’s Object.magic function that converts from one type to any other type), but JS is very much all escape hatches.

If it really bugs you, definitely look at Typescript; it’s a superset, so you can just write normal JS and gradually add it in.


#7

so you mean by writing a “+” next to the “1” for the example, the JS will consider it as a number since i’m adding it to a zero ?


#8

It’s the unary + operator, works the same as Number("1") in this case, it coerces the value to a number. It’s not reliable though because if something that definitely isn’t a number comes in the function will blow up.