Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript types

Tags:

As per http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-262.pdf, JavaScript has 6 types: undefined, null, boolean, string, number and object.

var und; console.log(typeof und); // <-- undefined  var n = null; console.log(typeof n); // <--- **object**!  var b = true; console.log(typeof b); // <-- boolean  var str = "myString" console.log(typeof str); // <-- string  var int = 10; console.log(typeof int); // <-- number  var obj = {} console.log(typeof obj); // <-- object 

Question 1:

Why is null of type object instead of null?

Question 2:

What about functions?

var f = function() {}; console.log(typeof f); // <-- function 

Variable f has type of function. Why isn't it specified in the specification as a separate type?

Thanks,

like image 778
Alex Ivasyuv Avatar asked Mar 25 '10 18:03

Alex Ivasyuv


People also ask

What are the 8 types of JavaScript?

The Eight Types of JavaScript. JavaScript has 8 types: undefined, null, boolean, number, bigint, string, symbol, and object.

What are the three types of JavaScript?

JavaScript allows you to work with three primitive data types: numbers, strings of text (known as “strings”), and boolean truth values (known as “booleans”). JavaScript also defines two trivial data types, null and undefined, each of which defines only a single value.

What are the 7 data types in JavaScript?

There are seven primitive data types, Number, String, Boolean, NULL, Undefined and Symbol and one non-primitive data type 'object'. There are differences between NULL and undefined data types though both contain the same value.

How many types Does JavaScript have?

JavaScript has seven built-in types: null , undefined , boolean , number , string , object , and symbol . They can be identified by the typeof operator. Variables don't have types, but the values in them do.


1 Answers

About typeof null == 'object', this is a mistake that comes since the early days, and unfortunately this mistake will stay with us for a long time, it was too late to be fixed in the ECMAScript 5th Edition Specification.

About the functions, they are just objects, but they have an special internal property named [[Call]] which is used internally when a function is invoked.

The typeof operator distinguish between plain objects and functions just by checking if the object has this internal property.

like image 191
Christian C. Salvadó Avatar answered Oct 13 '22 00:10

Christian C. Salvadó