Javascript - Type

1 - About

Type in Javascript

Javascript is not static typed but it exist Javascript wrapper language that implements it. See Javascript - Static Typing

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

3 - List

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

5 - Management

5.1 - Typeof operator

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

Reference/Operators/typeof

x = ["string", 0, true, undefined, null, {} ];
 
for (i in x) {
    console.log("("+x[i]+") has the type ("+typeof(x[i])+")");
}

5.2 - 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.

5.3 - Checking

Static type checking may be implemented by IDE specifying the type as documentation annotation.

Example: As JSDoc annotation, the Google Closure types syntax (works within Idea).

  • Simple Type: Type of parameter or variable is specified on the left side
/** @param {number} x **/
function inc(x) {return x + 1;}
  • Constructor Type: Every constructor function “becomes” a type and its name can be referenced inside JSDoc tags.
function Point(x,y) { this.x = x; this.y = y; }
 
/** @param {Array.<Point>} points 
* Array of elements of some type could also be specified with [] (for example, Point[]).
*/
function printPoints(points) {
...
}
 
  * It works also for the DOM
<code javascript>
// @param {Node} domNode
// @param {HTMLElement} htmlElement
  • Return Type
/** @return {!Shape|undefined} */
  • Type annotation
/** @type {function(string, *)} */
function 

5.4 - Checker

lang/javascript/es/type.txt · Last modified: 2017/11/10 09:41 by gerardnico