Table of Contents

About

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 en-US/docs/Web/JavaScript/Data_structures

Structure

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

Primitive

Object

Type

Weak

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

Strong

If you want to add type to Javascript, you need to use typescript

Management

Typeof operator

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])+")");
}

Prototype

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())

toStringTag

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.

Checking

See Javascript - (Static) Typing (Checker)

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"