Javascript - Type


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.

See Data_structures


The set of all JavaScript types is divided into two groups:





In JavaScript, you don't need to specify the type for each property. JavaScript is a weakly typed language.

function Employee() { = "";
  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


Typeof operator

The typeof operator returns if the value of variable has the corresponding data type


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");


The toStringTag symbol is added to the output of the toString function.

var firstTier = document.childNodes;

It's not unique but you can get a good insight on what you get.


Coercion (Type change)

Javascript - Coercion

  • objects can be converted to string via their toString method.
foo = "J" + { toString: function() { return "S"; } }; // "JS"
console.log(foo); //JS
  • objects can be converted to numbers via their valueOf method.
bar = 2 * { valueOf: function() { return 3; } };      // 6
console.log(bar); // 6

Special Plus Operator

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"

Powered by ComboStrap