Interesting Facts About JavaScript Data Types
Last Updated :
29 Nov, 2024
JavaScript (often abbreviated as JS) is one of the most popular programming languages in the world. It comes with its unique take on data types that sets it apart from languages like C, C++, Java, or Python. Understanding how JavaScript handles data types will be very interesting, which can help you write better, more efficient code.
Here are some interesting facts about JavaScript Data Types
Only One Number Type
Unlike languages like C++, Java, or Python, where numbers are categorized as int, float, or double, JavaScript has just one number type: a 64-bit floating-point number (IEEE 754 standard).
- This means all integers and decimals are treated the same.
- Integer precision is accurate up to 15 digits
JavaScript
console.log(999999999999999);
console.log(9999999999999999);
Output999999999999999
10000000000000000
In C++ or Java, you must explicitly define the type (e.g., int or float), and exceeding the type’s range results in an error. JavaScript silently switches to floating-point behaviour.
Dynamic Typing
JavaScript is dynamically typed, meaning a variable's type can change at runtime, unlike statically typed languages like Java or C++.
JavaScript
let data = 42; // Initially a number
data = "Hello"; // Now a string
data = true; // Now a boolean
Primitive vs. Reference Types
JavaScript divides its data types into primitive types and reference types, but with some unique behaviors
JavaScript
let obj1 = { a: 1 };
let obj2 = obj1;
obj2.a = 2;
console.log(obj1.a);
This distinction also exists in other languages, but JavaScript's flexibility in handling them (e.g., mixing object types with primitives) stands out.
undefined and null Are Separate Types
JavaScript treats undefined and null as distinct types, which can confuse developers from other languages.
- undefined: Represents a variable that has been declared but not assigned a value.
- null: Represents an intentional absence of a value.
JavaScript
let a;
console.log(a);
let b = null;
console.log(b);
In many languages, null or None is the default for uninitialized variables. JavaScript’s separate undefined type adds a layer of complexity.
typeof null Returns "object"
One unusual behaviour is typeof operator identifies null as an "object". This is a well-known bug from the early days of JavaScript but remains for backward compatibility.
JavaScript
console.log(typeof null);
This behavior is peculiar to JavaScript and isn’t seen in other languages.
Bitwise Operations and 32-Bit Conversion
In JavaScript, all numbers are stored as 64-bit floating-point numbers, as defined by the IEEE 754 standard. However, bitwise operations in JavaScript are performed on 32-bit signed integers. This involves a multi-step conversion process
- Conversion to 32-Bit Signed Integer: When a bitwise operation is executed, the 64-bit floating-point number is converted to a 32-bit signed binary number.
- Bitwise Operation: The operation (e.g., AND, OR, XOR, etc.) is performed using the 32-bit binary representation.
- Conversion Back to 64-Bit: The result is converted back to a 64-bit floating-point number.
JavaScript
let n = 5.5; // Stored as a 64-bit floating-point number
let res = n | 0; // Bitwise OR operation
console.log(res); // Output: 5
The && Operator Returns Actual Values
Unlike many other languages where the && (logical AND) operator strictly evaluates to a boolean (true or false), in JavaScript, it returns the actual value of the last operand evaluated. The behavior depends on whether the first operand is true or false
- If the First Operand is False: The operation short-circuits, and the first operand is returned without evaluating the second.
- If the First Operand is True: The second operand is evaluated and returned.
JavaScript
let x = 5;
let y = 0;
// 5 (true) && 0 (false)
let res = x && y;
console.log(res);
// 5 (true) && 10 (true)
res = x && 10;
console.log(res);
NaN Is a Number
JavaScript includes NaN (Not-a-Number) as a value of type number.
JavaScript
console.log(typeof NaN);
console.log(NaN === NaN);
Most languages like Python or Java handle NaN differently and don’t classify it as a number.
BigInt: Numbers Beyond 64-Bit Precision
To handle integers larger than 64 bits, JavaScript introduced the BigInt type in ES2020.
JavaScript
const bigN = 123456789012345678901234567890n;
console.log(bigN + 1n);
Output123456789012345678901234567891n
While Python supports arbitrary precision integers by default, languages like Java or C++ require libraries to handle such large numbers.
Strings as Immutable Primitives
In JavaScript, strings are immutable primitives, even though they can be accessed like arrays.
JavaScript
let s = "Hello";
s[0] = "h"; // No effect
console.log(s);
While string immutability exists in Java, JavaScript’s syntax for accessing characters like arrays is unusual.
A character is also a string
There is no separate type for characters. A single character is also a string.
JavaScript
let s1 = "gfg"; // String
let s2 = 'g'; // Character
console.log(typeof s1);
console.log(typeof s2);
Symbol: Unique Identifiers
JavaScript introduces the symbol type for creating unique identifiers, a feature not commonly seen in other languages.
JavaScript
const sym1 = Symbol("id");
const sym2 = Symbol("id");
console.log(sym1 === sym2);
Symbols ensure uniqueness, which is helpful for avoiding naming conflicts in object properties.
Everything Is an Object(Sort of):
In JavaScript, Functions are objects, arrays are objects, and even primitive values can behave like objects temporarily when you try to access properties on them.
JavaScript
let s = "hello";
console.log(s.length);
// Example with a number
let x = 42;
console.log(x.toString());
// Example with a boolean
let y = true;
console.log(y.toString());
/* Internal Working of primitives
to be treeated as objects
// Temporary wrapper object
let temp = new String("hello");
console.log(temp.length); // 5
// The wrapper is discarded after use
temp = null; */
Falsy and Truthy Values
JavaScript’s loose typing leads to unique rules for truthiness and falsiness:
- Falsy Values: false, 0, -0, "", null, undefined, NaN, document.all
- Truthy Values: Everything else.
JavaScript
if ("0") console.log("Truthy");
if (0) console.log("Falsy"); //no output
In this code, because 0 is false it will not execute the 2nd if statement as if statement runs only if condition is true.
This behavior doesn’t exist in strongly-typed languages like C++ or Java.
The && Operator Returns Actual Values
Type Coercion and Dual Equality
JavaScript allows automatic type conversion during comparisons (==), which can yield surprising results.
JavaScript
console.log(5 == "5");
console.log(5 === "5");
Most languages enforce strict type equality for comparisons.
Arrays Are Objects
JavaScript arrays are technically objects, which allows them to have non-integer keys.
JavaScript
const a = [1, 2, 3];
a["key"] = "value";
console.log(a.key);
In most languages, arrays are strictly defined structures and don’t allow such behavior.
Dynamic Object Properties
JavaScript objects can have properties added, modified, or removed at runtime.
JavaScript
const obj = {};
obj.newProperty = "Hello";
console.log(obj.newProperty); // Output: Hello
Unlike Java or C++, you don’t need to predefine object structure in JavaScript.
Similar Reads
Interesting Facts About JavaScript
JavaScript (often abbreviated as JS) is one of the most popular programming languages in the world. It is an interpreted, high-level programming language that follows ECMAScript. It powers interactive websites and is packed with amazing features that make it special and powerful. Interesting Facts A
5 min read
Interesting Facts about JavaScript Arrays
Let us talk about some interesting facts about JavaScript Arrays that can make you an efficient programmer.Arrays are ObjectsJavaScript arrays are actually specialized objects, with indexed keys and special properties. They have a length property and are technically instances of the Array constructo
3 min read
Interesting Facts About Map in JavaScript
JavaScript Map is used to store the data of key-value pairs. It can be used to store any type of value including objects and primitive data types. It is iterable which is the main reason we can manipulate it according to the need.Map Internally Uses Hash TableJavaSctipt Map internally uses Hashing t
4 min read
Interesting Facts about Object in JavaScript
Let's see some interesting facts about JavaScript Objects that can help you become an efficient programmer.JavaSctipt Objects internally uses Hashing that makes time complexities of operations like search, insert and delete constant or O(1) on average. It is useful for operations like counting frequ
4 min read
Interesting facts about JSON
JSON or JavaScript Object Notation is a lightweight format for transporting and storing data. JSON is used when data is transferred from a server to a web page. This language is also characterized as weakly typed, prototype-based, dynamic, and multi-paradigm. Here are some interesting facts about JS
2 min read
Introduction to Built-in Data Structures in JavaScript
JavaScript (JS) is the most popular lightweight, interpreted compiled programming language, and might be your first preference for Client-side as well as Server-side developments. Let's see what inbuilt data structures JavaScript offers us: Data Structure Internal Implementation Static or Dynamic Ja
2 min read
JavaScript Type Conversion
In JavaScript Type Conversion can be defined as converting the data type of the variables from one type to the other manually by the programmer(explicitly) or automatically by the JavaScript(implicitly).Implicit Type Conversion (Coercion): Implicit Type Conversion occurs automatically by the JavaScr
4 min read
JavaScript Data Types
In JavaScript, each value has a data type, defining its nature (e.g., Number, String, Boolean) and operations. Data types are categorized into Primitive (e.g., String, Number) and Non-Primitive (e.g., Objects, Arrays).Primitive Data Type1. NumberThe Number data type in JavaScript includes both integ
5 min read
Types of Arrays in JavaScript
A JavaScript array is a collection of multiple values at different memory blocks but with the same name. The values stored in an array can be accessed by specifying the indexes inside the square brackets starting from 0 and going to the array length - 1([0]...[n-1]). A JavaScript array can be classi
3 min read
Variables and Datatypes in JavaScript
Variables and data types are foundational concepts in programming, serving as the building blocks for storing and manipulating information within a program. In JavaScript, getting a good grasp of these concepts is important for writing code that works well and is easy to understand.VariablesA variab
3 min read