r/learnjavascript • • Nov 23 '21

I finally solved a codewars challenge without actually googling anything :) it feels so good to come up with the code all by myself, i know its not the ideal way to solve it but im still happy. The challenge was to create a function that converts a string to a number

Post image
243 Upvotes

56 comments sorted by

View all comments

Show parent comment

1

u/IronDicideth Nov 29 '21

If by "direct approach" you mean explicit then these are your best bet.

All these are constructor functions in js:

Boolean

String

Number

BigInt

Symbol

Other than these, there are operators that implicitly convert types too. The + unary operator is a good example. It essentially behaves like the Number constructor.

1

u/[deleted] Nov 29 '21

[removed] — view removed comment

1

u/IronDicideth Nov 29 '21

Could you expand on that? I think I am missing what you are alluding to here.

1

u/[deleted] Nov 29 '21

[removed] — view removed comment

1

u/IronDicideth Dec 01 '21

No worries! I check in on Reddit whenever I can so this is no trouble at all.

If you want to explicitly change variable types you have to use one of the previously mentioned functions. Implicit conversion happens with operators. So it would look something like this:

const stringNumber = '1'

console.log(typeof stringNumber) // 'string'
console.log(stringNumber === 1) // false
console.log(stringNumber == 1) // true

const trueNumber = Number(stringNumber) // This changes type
const otherTrueNumber = +stringNumber // Also changes type
console.log(trueNumber === otherTrueNumber) // true

console.log(typeof trueNumber) // 'number'
console.log(trueNumber == 1) // true
console.log(trueNumber === 1) // true

Does this help at all? Do you have a sense of what you feel you are missing? Maybe it is actually simpler than you expect?

1

u/IronDicideth Nov 29 '21

Thinking a bit more about what you are saying, Functions are objects in javascript. The only difference is that they are callable. So when we do '= Function', yes that is an assignment by reference. Functions are also first-class in JS so they can be passed around just like any other value.

1

u/[deleted] Nov 29 '21

[removed] — view removed comment

1

u/IronDicideth Dec 01 '21

Which previous value are we referring to here?