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
JavaScript Tutorial JavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. It's an interpreted language that executes code line by line, providing more flexibility.JavaScript on Client Side: On the client side, Jav
11 min read
Web Development Web development is the process of creating, building, and maintaining websites and web applications. It involves everything from web design to programming and database management. Web development is generally divided into three core areas: Frontend Development, Backend Development, and Full Stack De
5 min read
React Interview Questions and Answers React is an efficient, flexible, and open-source JavaScript library that allows developers to create simple, fast, and scalable web applications. Jordan Walke, a software engineer who was working for Facebook, created React. Developers with a JavaScript background can easily develop web applications
15+ min read
JavaScript Interview Questions and Answers JavaScript (JS) is the most popular lightweight, scripting, and interpreted programming language. JavaScript is well-known as a scripting language for web pages, mobile apps, web servers, and many other platforms. Both front-end and back-end developers need to have a strong command of JavaScript, as
15+ min read
React Tutorial React is a JavaScript Library known for front-end development (or user interface). It is popular due to its component-based architecture, Single Page Applications (SPAs), and Virtual DOM for building web applications that are fast, efficient, and scalable.Applications are built using reusable compon
8 min read
Domain Name System (DNS) DNS is a hierarchical and distributed naming system that translates domain names into IP addresses. When you type a domain name like www.geeksforgeeks.org into your browser, DNS ensures that the request reaches the correct server by resolving the domain to its corresponding IP address.Without DNS, w
8 min read
NodeJS Interview Questions and Answers NodeJS is one of the most popular runtime environments, known for its efficiency, scalability, and ability to handle asynchronous operations. It is built on Chromeâs V8 JavaScript engine for executing JavaScript code outside of a browser. It is extensively used by top companies such as LinkedIn, Net
15+ min read
HTML Interview Questions and Answers HTML (HyperText Markup Language) is the foundational language for creating web pages and web applications. Whether you're a fresher or an experienced professional, preparing for an HTML interview requires a solid understanding of both basic and advanced concepts. Below is a curated list of 50+ HTML
14 min read
What is an API (Application Programming Interface) In the tech world, APIs (Application Programming Interfaces) are crucial. If you're interested in becoming a web developer or want to understand how websites work, you'll need to familiarize yourself with APIs. Let's break down the concept of an API in simple terms.What is an API?An API is a set of
10 min read
Introduction of Firewall in Computer Network A firewall is a network security device either hardware or software-based which monitors all incoming and outgoing traffic and based on a defined set of security rules it accepts, rejects, or drops that specific traffic. It acts like a security guard that helps keep your digital world safe from unwa
10 min read