Type in Javascript
Javascript is not static typed but it exist Javascript wrapper language that implements it. See Javascript - (Static) Typing (Checker)
Only values have types in JavaScript; variables are just simple containers for those values.
JavaScript supports a runtime system based on a seven data types. See list. They are all primitive with the exception of object.
The set of all JavaScript types is divided into two groups:
Data Type | Primitive |
---|---|
Javascript - String | Yes |
Javascript - Number (Double) | Yes |
Javascript - Boolean (Truthy|Falsy) | Yes |
Javascript - Undefined | Yes |
Javascript - Null | Yes |
Javascript - Symbol | Yes |
Data Type | Primitive |
---|---|
Javascript - Object | No |
Example of Object Derived Type | |
Javascript - Array | No |
How to manipulate and show a Date Time in Javascript? | No |
How to use Regular expression (Regexp) in Javascript? | No |
Javascript - Error | No |
In JavaScript, you don't need to specify the type for each property. JavaScript is a weakly typed language.
function Employee() {
this.name = "";
this.dept = "general";
}
whereas with a strongly typed language as Java:
public class Employee {
public String name = "";
public String dept = "general";
}
If you want to add type to Javascript, you need to use typescript
The typeof operator returns if the value of variable has the corresponding data type
en-US/docs/Web/JavaScript/Reference/Operators/typeof
x = ["string", 0, true, undefined, null, {} ];
for (i in x) {
console.log("("+x[i]+") has the type ("+typeof(x[i])+")");
}
Javascript has a prototype mechanism for object.
To get the prototype of an object check the __proto__ attribute.
var element = document.querySelector("body");
console.log(element.__proto__.toString())
The toStringTag symbol is added to the output of the toString function.
var firstTier = document.childNodes;
console.log(firstTier[Symbol.toStringTag]);
It's not unique but you can get a good insight on what you get.
foo = "J" + { toString: function() { return "S"; } }; // "JS"
console.log(foo); //JS
bar = 2 * { valueOf: function() { return 3; } }; // 6
console.log(bar); // 6
The + operator is overloaded to perform both string concatenation and addition. Javascript is supposed to choose between concatenation and addition based on the variable types, but with implicit coercion, the types are on the value and not on the variable. It's therefore not given. JavaScript resolves this ambiguity by choosing always valueOf (over toString).
var obj = {
toString: function() {
return "[object MyObject]";
},
valueOf: function() {
return 1;
}
};
console.log("Implicit coercion in a concatenation chooses the valueOf function: object: " + obj); // "object: 1"
console.log("The solution is to explicitly coerce the object: object: " + obj.toString()); // "object: MyObject"