errgod
errgod

Reputation: 355

How to use typed variables in javascript?

Is there any way to use typed variables in javascript? Like integer, string, float...

Upvotes: 15

Views: 29817

Answers (11)

Valery Rode
Valery Rode

Reputation: 11

<html>
    <head>
        <meta charset="utf-8">
        <title>JS_Byte</title>
        <script>
        class Byte 
        {
            constructor(Value) 
            {
                this.Number = new Uint8Array(1);
                this.Number[0] = Value;
            }
            get Get() 
            {
                return this.Number[0];
            }
            set Set(newValue) 
            {
                this.Number[0] = newValue;
            }
        };
        //On load
        function Load_Page()
        {
            let Byte_Num = new Byte(12);
            document.write(Byte_Num.Get.toString() + "<br>");// -> 12
            Byte_Num.Set = 14;
            document.write(Byte_Num.Get.toString() + "<br>");// -> 14
            Byte_Num.Set = 256;
            document.write(Byte_Num.Get.toString() + "<br>");// -> 0
        }
        </script>
    </head>
    <body onload="Load_Page()"> 
    </body>
</html>

Upvotes: 0

David Leppik
David Leppik

Reputation: 3304

While JavaScript is not explicitly a typed language, it's like a typeless filling in a language sandwich with stronger-typed representations above (in the IDE) and below (in the compiler.) To support IDE-friendly and optimizer-friendly code, there are a number of tricks you can use to obtain explicit types.

JavaScript implementations include just-in-time compilers (JITs) to convert JavaScript into fast machine language. One of the tricks they use is to convert it into an intermediate, strongly typed form. If your goal is performance, you can make life easier by favoring const variables and coercing types into more explicit types.

For example, JavaScript supports two number types outside of typed arrays: 64-bit Float (a.k.a. double) and 32-bit integer. While double is the default, you can coerce a number into an integer with |0, like this:

const myInt = 3.0 | 0;

You see this pattern a lot in high-performance code, particularly stuff that was written before typed arrays.

The other reason to have explicit types is to make life easier for developers. Microsoft invented TypeScript so that IDEs (particularly their Visual Studio) can provide code completion, refactoring (in particular renaming), and error detection. It does this by being a strongly typed language. One of the language goals for TypeScript is to provide a future direction for JavaScript. Because of this goal TypeScript is a superset of JavaScript and no features are added to TypeScript that couldn't be in a future JavaScript release. Similarly, if future versions of JavaScript break TypeScript, TypeScript will be changed to match JavaScript.

TypeScript isn't JavaScript, so why do I bring it up? Because even if you aren't using it, your editor may be. Since TypeScript is a superset of JavaScript, the TypeScript compiler can parse JavaScript—and produce type information for all the functions and variables. So if you use Visual Studio, WebStorm, or an editor with a TypeScript plugin, you get type information even with pure JavaScript! (The smarter ones will warn you if you use TypeScript features in JavaScript.)

In fact, one of the arguments against using TypeScript I've heard recently is that JavaScript editors have gotten so good (thanks to the embedded TypeScript compiler) that the advantages no longer outweigh the burden of having another language.

However, to have strong typing (from the IDE's perspective) it helps to make it easy for the compiler to guess how your source files connect together, favor consts, and avoid writing functions that return more than one type.

Upvotes: 0

Hossein Aghatabar
Hossein Aghatabar

Reputation: 1

you can use TypeScript for definition types for values

Upvotes: 0

M81
M81

Reputation: 491

There is a simple hack to simulate typed variables in Javascript using typed arrays.

var a = new Int8Array(1);
a[0]=5;
a[0]=~a[0]; // -6
var b = new Uint8Array(1);
b[0]=5;
b[0]=~b[0]; // 250

The only useful reason I know for ever doing this is when you need to use bitwise operations on an unsigned integer when translating code from a typed language which has to do exactly the same in Javascript. Javascript integers are signed by default and bitwise operations can mess up the sign.

Creating a typed array for just a single variable is generally not good for the performance.

Often...

var b=5;
b=(~b)&0xff; // 250

will do the trick just fine and only 32-bit unsigned integers need to be typed in Javascript to avoid problems with bitwise operations.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Typed_arrays#Typed_array_views

Upvotes: 2

FloatOverflow
FloatOverflow

Reputation: 1171

People writing "why shouldn't use it / you shouldn't use it" are wrong. In the next Java Script 2.x specification there is a plan to add strong typed variables.

Meanwhile you may use very simple solution to emulate strong types:

var = Object.create( String );

After that autocompleting in a lot of IDE (including IntelliJ IDEA) will work great and you have declared and initialized an object of specified type.

Read more on my blog.

Upvotes: 1

Chris
Chris

Reputation: 1174

Not possible in Javascript, but if you really need it, you should check TypeScript. It is a superset of Javascript that adds optional static typing. It also has class-based programming.

Upvotes: 3

Peter Olson
Peter Olson

Reputation: 142921

Javascript is dynamically typed, whereas other languages, C# and Java for example, are statically typed. This means that in Javascript variables can be reassigned to values of any type, and thus that you don't ever need to explicitly denote the type of variables or the return type of functions. If you saw code like this in a statically typed language

int x = 5;
x = "hello";

you would rightfully expect the compiler to start throwing up a big nasty TypeError. Javascript, on the other hand, will happily run this code even though the type changed.

var x = 5;
x = "hello";

Because variables can change types, the compiler can't know as much information about them. You should expect the tools for Javascript to be inferior to those of Java/C# as far as useful niceties like code completion go. Fewer mistakes will be caught at compile time and you will have to do more runtime debugging than you are probably used to.

That said, this also allows you to be more free with your variables and you can change types at will, which can often be convenient. You can write code like this if you want:

var x;               //typeof x === "undefined"
x = "Hello, world!"; //typeof x === "string"
x = 42;              //typeof x === "number"
x = false;           //typeof x === "boolean"
x = {};              //typeof x === "object"

Upvotes: 9

John Pick
John Pick

Reputation: 5650

JavaScript variables are not typed.

JavaScript values are, though. The same variable can change (be assigned a new value), for example, from uninitialized to number to boolean to string (not that you'd want to do this!):

var x;       // undefined
x = 0;       // number
x = true;    // boolean
x = "hello"; // string

Upvotes: 23

clagccs
clagccs

Reputation: 2324

I recommend you read this:

http://en.wikipedia.org/wiki/Strong_typing

javascript is a weak and dynamic type..it's dynamic because the variable type is determine in the runtime, and is loosely type because you can perform this operation for example

var letter = "2";
var number = 2;
console.log(letter+number);

this in java, c# or any other static and stricted type language will make an error but in javascript you get a "22" as result (it is because javascript is weak typed or loosely typed)

now..you've other languages than keep use typed values, like clojure or dart, where for performance reasons, you can use functions or methods with typed arguments, javascript doesn't let this and only accept dynamic values, like ruby...

I hope this help and you can understand my poor english :D

Upvotes: 1

Andrei
Andrei

Reputation: 287

One of the main characteristics of Javascript is that it is weak typed language. Why do you need strong types anyways?

Upvotes: 0

Kenneth Funk
Kenneth Funk

Reputation: 396

Javascript is a loosely typed language, so no, there aren't types as you are used to in some other languages.

Upvotes: 0

Related Questions