user2454455
user2454455

Reputation:

How do i convert c++ 'int' to javascript?

I am about to translate my C++ code to javascript on my c++ web-based ide with source content tracer I want the converted variable to not just be a var but an something like an int so that it can detect if the assigned value is valid or not

UPDATE:Knowing that int and float in javascript cannot be distinguish using typeof Then what is the best way to detect if the c++ float variable has a valid float value? same as detecting if a c++ int variable has a valid int value?

Upvotes: 2

Views: 473

Answers (2)

Dan Tao
Dan Tao

Reputation: 128327

JavaScript and C++ are very different beasts. Traditionally, variables in JavaScript are not strongly typed, which is why you can do this:

var x = 5; // x is a number
x = 'foo'; // now x is a string
x = {};    // now an object
x = [];    // now an array (which is also an object)
x = false; // etc., etc.

In C++, if you declared x as an int then the compiler wouldn't allow that code. There is no such check in JavaScript.

If you really want type safety, there is something approaching it if you compile your JavaScript using something like Google's Closure Compiler. This involves annotating your JavaScript code with specially-formatted comments that enable the compiler to verify consistent typing in your code to some extent. It is far from perfect, and I wouldn't recommend it for anything other than a Very Serious™ project due to the significant overhead it imposes on development.

Upvotes: 0

Brad
Brad

Reputation: 163232

There is no int in JavaScript, only number. Also, variables in JavaScript are not strongly typed. The type is defined by the value assigned.

If you want to determine if the assigned value is a number, you can use typeof exampleVar === 'number'.

See also:

Upvotes: 3

Related Questions