Understanding of data type in Javascript

Today, we are going to deep dive into the datatypes and types of variable in javascript.
var
In javascript, var is keywords which help in declaring the variable in javascript and help in declaring function scope as well as global scope.
var name = "Javascript"
var developed_In = 1995
var hasRuntime = true
Key Characteristics of var
Function Scope: Variables declared with
varare scoped to the nearest function block, not to block-level constructs likeif,for, ortry-catch.Hoisting:
vardeclarations are hoisted to the top of their scope (function or global), meaning they are moved to the top during compilation. However, only the declaration is hoisted — initialization happens at the original line.Redeclaration: You can redeclare the same
varvariable multiple times in the same scope without an error.Global Object Property: In a script, a
varvariable becomes a non-configurable property of the global object (windowin browsers), making it difficult to delete.No Block Scope: Unlike
letandconst,vardoes not respect block scope (e.g.,{}), so variables can be accessed outside the block they were declared in.
Let
let is a modern keyword introduced in ES6 (ECMAScript 2015) for declaring variables in JavaScript. It provides block scope, meaning variables declared with let are only accessible within the block, statement, or expression where they are defined—unlike var, which has function scope.
let programmingLanguage = "Java"
let developIn = 1996
let supportCrossPlateform = true
Key Characteristics of let
Block Scoping: Variables are confined to the nearest block (e.g.,
{}inif,for,whilestatements).No Redeclaration: You cannot declare the same variable twice in the same scope.
Temporal Dead Zone (TDZ):
letvariables are hoisted but not initialized. Accessing them before declaration throws aReferenceError.Reassignable: Values can be changed after declaration, but the variable name cannot be reused.
Const
const variables in JavaScript are hoisted to the top of their block scope, similar to let, but they are not initialized during hoisting. This creates a Temporal Dead Zone (TDZ) — a period from the start of the block until the variable's declaration is executed — during which accessing the variable throws a ReferenceError: Cannot access 'variable' before initialization.
const programmingLanguage = "Java"
const developIn = 1996
const supportCrossPlateform = true
Key Characteristic of const
Hoisting: Yes,
constdeclarations are hoisted to the top of their scope.Initialization: No,
constvariables are not initialized during hoisting.Temporal Dead Zone (TDZ): The variable is inaccessible until its declaration is executed.
Error on Access Before Declaration:
ReferenceError: Cannot access 'x' before initializationis thrown.Must Be Initialized:
constvariables must be assigned a value at the time of declaration.
let vs const vs var
JavaScript provides three ways to declare variables: var, let, and const, but they differ in scope, hoisting behaviour, and re-assignment rules.
var: Declares variables with function or global scope and allows re-declaration and updates within the same scope.
let: Declares variables with block scope, allowing updates but not re-declaration within the same block.
const: Declares block-scoped variables that cannot be reassigned after their initial assignment.
Data Types In javascript
String
string is a primitive data types which is used to represent textual data such as name, message etc.. . string is an immutable we can't modify the existing data. Any operation which modify the existing data result in returning a new string.
Creating Strings
Strings can be created using:
Single quotes:
'Hello'Double quotes:
"World"Template literals (backticks):
Hello ${name}
Template literals are especially powerful as they support string interpolation (embedding variables and expressions with ${}), multi-line strings, and tagged templates.
Common Methods of String
lenght(): lenght function used to return the lenght of the stringcharAt(index): charAt function is used to get the character at the given index.includes(subStr): returntrueif string contain the substring.slice(start, end): Extract portion of the string.indexOf(substr): Returns the first occurrence of a substring, or-1if not found.replace(old, new): Replaces the first occurrence of a substring.toUpperCase()/toLowerCase(): Converts the string to uppercase or lowercase.
let str = "javascript"
// Method
// 1. length
let result = str.length
console.log(result);
// 2. charAt()
result = str.charAt(7)
console.log(result)
// 3. includes()
result = str.includes('scr')
console.log(result)
// 4. IndexOf() & valueOf
// NOTE:- return the index of the char in the string
result = str.indexOf('s')
console.log(result)
// NOTE:- Return the value
result = str.valueOf()
console.log(result)
result = str.slice(5)
console.log(result)
result = str.split("")
console.log(result)
String Conversion
String()Constructor
The most straightforward and reliable method. It works for all data types, includingnull,undefined, andNaN.
String(123); // "123"
String(null); // "null"
String(undefined); // "undefined"
String(true); // "true"
.toString()Method
Available on most data types (numbers, booleans, arrays), but throws an error if used onnullorundefined.
(123).toString(); // "123"
true.toString(); // "true"
[1, 2].toString(); // "1,2"
// null.toString(); // TypeError!
- Template Literals (Backticks)
A clean, readable way, especially useful when embedding values in text.
`Value: ${123}`; // "Value: 123"
`Status: ${true}`; // "Status: true"
- Concatenation with Empty String
Uses JavaScript’s type coercion by adding an empty string ("") to the value.
123 + ""; // "123"
true + ""; // "true"
JSON.stringify()
Ideal for converting objects, arrays, and complex data structures to strings. It serializes data into JSON format.
JSON.stringify({name: "John"}); // "{"name":"John"}"
JSON.stringify([1, 2]); // "[1,2]"
JSON.stringify(null); // "null"
new String()(Not Recommended)
Creates a String object rather than a primitive string. Avoid unless you specifically need object behavior (e.g., storing properties).
typeof new String("hello"); // "object"
Object.prototype.toString.call()
Advanced method used for debugging or detecting types. Can be adapted to convert values, but not ideal for simple string conversion.
Object.prototype.toString.call(123); // "[object Number]"
Array.prototype.join()
Converts a value to a string by placing it in an array and joining it. Useful for arrays or when working with number sequences.
[123].join(""); // "123"
+and.toString()(Creative Use)
Use+to coerce to number, then.toString()to convert back—rarely used but demonstrates type coercion.
(+ "123").toString(); // "123"
parseInt()and.toString()
Ensures input is a valid number before conversion—useful when dealing with number strings.
parseInt("123", 10).toString(); // "123"
Number
Number is a primitive data type which is used to represent the Integer, floating value and BigInteger in the world of the programming language. They follow the 64-bit double-precision IEEE 754 standard, meaning all numbers in JavaScript are stored as floating-point values, even whole numbers like 5 or 100.
Key Features of JavaScript Numbers
Floating-Point Representation: There is no separate integer type;
37is stored as a floating-point number.Range and Precision:
Maximum safe integer:
Number.MAX_SAFE_INTEGER=9007199254740991(2⁵³ − 1).Minimum safe integer:
Number.MIN_SAFE_INTEGER=-9007199254740991.Largest representable number:
Number.MAX_VALUE≈1.7976931348623157e+308.Smallest positive number:
Number.MIN_VALUE≈5e-324.
Special Values:
Infinity: Result of dividing a positive number by zero (2 / 0).-Infinity: Result of dividing a negative number by zero (-2 / 0).NaN(Not a Number): Returned when a mathematical operation fails (e.g.,4 - "hello").
Number Literals
JavaScript supports multiple number formats:
Decimal:
123,-456Binary:
0b1010or0B1010Octal:
0o755(standard) or0755(legacy, not allowed in strict mode)Hexadecimal:
0xFF,0x1A3Exponential:
1.23e5(equivalent to123000)
Number Conversion
Number(value): Converts a value to a number. ReturnsNaNif conversion fails.Number("123") // 123 Number("abc") // NaN Number(true) // 1 Number(null) // 0parseInt(): Parses a string and returns an integer.parseFloat(): Parses a string and returns a floating-point number.
Number Methods and Properties
Number.isFinite(): Checks if a value is a finite number.Number.isInteger(): Checks if a value is an integer.Number.isNaN(): Checks if a value isNaN.Number.isSafeInteger(): Checks if a value is a safe integer.Number.EPSILON: Smallest difference between two representable numbers (~2⁻⁵²).Number.MAX_VALUE,MIN_VALUE,MAX_SAFE_INTEGER,MIN_SAFE_INTEGER: Constants for numeric limits.
BigInt for Large Integers
For integers outside the safe range, use BigInt (suffix n):
const bigNum = 123456789012345678901234567890n;
- BigInt supports arbitrary precision but cannot represent decimals and does not work with
Mathfunctions.
Boolean
JavaScript Booleans are a fundamental data type that can only have two values: true or false. They are used to represent logical states and control program flow in conditional statements (like if, while) and loops.
Boolean Primitive vs. Boolean Object
Boolean primitive (
true,false): The standard, recommended way to use booleans. It is a simple value withtypeofreturning"boolean".Boolean object (
new Boolean()): A wrapper object created with thenewkeyword. While it can store a boolean value, it is discouraged because:typeofreturns"object", not"boolean".All objects are truthy, so even
new Boolean(false)evaluates totruein a conditional.It can cause confusion and unexpected behavior.
Converting Values to Boolean
JavaScript uses truthy and falsy values to determine boolean conversion:
Falsy values (coerce to
false):0,-0,0n,null,undefined,NaN,""(empty string).Truthy values (coerce to
true): All other values, including non-empty strings, arrays, objects, andfalseas a string.
Use the Boolean() function (without new) or the double NOT operator (!!) to convert any value to a boolean primitive:
Boolean("hello"); // true
!!""; // false
Null
null in JavaScript is a primitive value representing the intentional absence of any object value. It is explicitly assigned by developers to indicate that a variable or property has no meaningful value at the moment, but may be assigned one later.
Key Characteristics of null:
Purpose: Signifies an intentional empty value (e.g., clearing a variable, indicating no object reference).
Type: Despite being a primitive,
typeof nullreturns"object"— a long-standing bug in JavaScript that has been preserved for backward compatibility.Equality:
null == undefined→true(loose equality, due to type coercion).null === undefined→false(strict equality, different types).
Numeric Context:
nullis coerced to0in arithmetic operations (e.g.,2 + null→2).JSON Handling:
JSON.stringify()can representnullfaithfully, unlikeundefined.Usage Examples:
let user = null; // Intentionally empty const element = document.getElementById('nonexistent'); // Returns null if not found
When to Use null:
When you explicitly want to indicate no value (e.g., resetting a variable, API responses with no data).
When designing APIs,
nullis often preferred overundefinedto signal deliberate absence.
Undefined
undefined in JavaScript is a primitive value automatically assigned to variables that have been declared but not initialized, or to properties and function return values that do not exist or are not explicitly returned.
When it occurs:
A variable declared without a value:
let x; console.log(x); // undefinedAccessing a non-existent object property:
let obj = {}; console.log(obj.nonExistent); // undefinedA function that doesn’t return a value:
function noReturn() {} console.log(noReturn()); // undefinedAn unused function parameter:
function test(param) { console.log(param); } test(); // undefined
Key characteristics:
typeof undefinedreturns"undefined"(the only primitive with this type).undefinedis a global property and should not be reassigned.undefinedis not the same asnull—nullis an intentional absence of value, whileundefinedmeans no value has been assigned.
How to check for it:
Use strict equality:
variable === undefinedUse
typeof:typeof variable === 'undefined'Avoid
==(loose equality) as it treatsundefinedandnullas equal (undefined == nullistrue).
Symbols
Symbol is a primitive data type in JavaScript introduced in ES6 (ECMAScript 2015). It represents a unique and immutable value, guaranteed to be distinct from all other symbols, even if they share the same description.
Key Features of Symbols
Uniqueness: Each
Symbol()call returns a new, unique symbol. Even symbols with identical descriptions are not equal:const sym1 = Symbol('id'); const sym2 = Symbol('id'); console.log(sym1 === sym2); // falseNon-enumerable: Symbols used as object keys are not included in
for...inloops,Object.keys(), orJSON.stringify(), making them ideal for hidden or internal properties.No Automatic String Conversion: Symbols cannot be implicitly converted to strings, preventing accidental misuse:
const id = Symbol('id'); // alert(id); // TypeError: Cannot convert a Symbol value to a string
Creating and Using Symbols
Scoped Symbols: Created with
Symbol():const mySymbol = Symbol('description');Global Symbols: Registered in a global registry using
Symbol.for(key):const globalSym = Symbol.for('sharedKey'); const sameSym = Symbol.for('sharedKey'); console.log(globalSym === sameSym); // trueUse
Symbol.keyFor(sym)to retrieve the key from a global symbol.
Common Use Cases
Avoiding Property Collisions: Safely add unique keys to objects without risk of overwriting existing properties.
Private/Hidden Properties: Attach metadata or internal state to objects that won’t be exposed during serialization or iteration.
Customizing Object Behavior: Well-known symbols (e.g.,
Symbol.iterator,Symbol.toPrimitive) allow developers to define custom behavior for built-in operations like iteration or type conversion.
Important Notes
Symbols are not constructors and cannot be used with
new.They are not garbage collectable if registered globally, but are garbage collectable if scoped.
Well-known symbols (like
Symbol.hasInstance) are predefined and used internally by JavaScript to customize language behavior.
Object
An object in JavaScript is a collection of key-value pairs, where each key (also called a property name) is a string or symbol, and each value can be any data type—such as a primitive (string, number, boolean), another object, or a function. Objects are fundamental to JavaScript and are used to represent real-world entities, like a car, person, or course. Object is a non primitive data type.
Syntax and Creation
Objects are typically created using object literal syntax with curly braces {}:
const person = {
name: "Alice",
age: 25,
greet: function() {
return "Hello!";
}
};
Properties are defined as
key: valuepairs.If a property’s value is a function, it’s called a method.
Multiword keys must be quoted:
"full name": "Alice Smith".Computed properties use square brackets:
[key] = value.
Accessing Properties
Use dot notation (obj.property) or bracket notation (obj["property"]) to access values:
console.log(person.name); // "Alice"
console.log(person["age"]); // 25
Bracket notation allows dynamic property access using variables or expressions.
Key Features
Dynamic: Properties can be added, modified, or deleted at runtime:
person.job = "Developer"; delete person.age;Reference Type: Objects are passed by reference, not by value.
Prototypal Inheritance: Every object has an internal link to a prototype object (via
[[Prototype]]), enabling inheritance.
Common Methods
JavaScript provides built-in methods to manipulate objects:
Object.keys(obj)– returns an array of property names.Object.values(obj)– returns an array of values.Object.assign(target, source)– copies properties from one or more sources to a target.Object.create(proto)– creates a new object with a specified prototype.
Objects are central to JavaScript’s object-oriented programming model and are used extensively in real-world applications.
Arrays
Arrays in JavaScript are ordered collections of values that can store multiple items under a single variable name. They are zero-indexed, meaning the first element is at index 0, and they can hold any data type—numbers, strings, objects, or even other arrays—making them highly flexible. In javascript, Arrays are also an object in javascript.
Creating Arrays
Array literals (most common): Use square brackets
[]to define and initialize an array.const fruits = ["apple", "banana", "cherry"];Array constructor: Use
new Array()(less common due to potential inconsistencies).const numbers = new Array(1, 2, 3);
Key Features
Dynamic size: Arrays automatically grow or shrink as needed.
Mixed data types: A single array can contain different types of values.
Length property: Access the number of elements using
.length.console.log(fruits.length); // 3
Common Array Methods
Accessing elements: Use bracket notation with index.
console.log(fruits[0]); // "apple"Adding elements:
push()adds to the end.unshift()adds to the beginning.
Removing elements:
pop()removes from the end.shift()removes from the beginning.splice()removes or replaces elements at a specific index.
Searching and checking:
indexOf()returns the index of the first match or-1if not found.includes()returnstrueif the value exists.find()andfindIndex()return the first element or its index that passes a test.
Iterating:
forEach()executes a function for each element.map()creates a new array with transformed values.filter()returns a new array with elements that pass a test.
Modifying:
sort()sorts elements (alphabetically for strings, numerically for numbers).reverse()reverses the order of elements.slice()extracts a portion of the array without modifying the original.concat()joins arrays into a new array.
Important Notes
Shallow copying: Methods like
slice()andconcat()create shallow copies. Nested objects are referenced, not duplicated.Sparse arrays: Setting a high index without filling intermediate slots creates empty slots (not
undefined), which can affect iteration behavior.Non-integer keys: Arrays should use nonnegative integers as indices. Using string keys (e.g.,
arr["key"]) creates object properties, not array elements.
Arrays are fundamental to JavaScript and essential for managing collections of data efficiently, especially in loops, data processing, and complex applications.
Function
Functions in JavaScript are reusable blocks of code designed to perform specific tasks. They allow you to organize, reuse, and modularize code by taking inputs (parameters), performing actions, and optionally returning outputs. In javascript, function is also another data type in javascript
function example() {
return "hello world"
}
console.log(typeof example)
Function Declaration
The most common way to define a function is using a function declaration:
function greet(name) {
return "Hello, " + name + "!";
}
Starts with the
functionkeyword.Includes a function name (e.g.,
greet), parameters in parentheses(name), and a code block in curly braces{}.Can be hoisted, meaning it can be called before it's defined in the code.
Function Expression
Functions can also be defined as expressions, often assigned to variables:
const square = function (number) {
return number * number;
};
Functions defined this way are not hoisted (unless using
let/const).Can be anonymous or named (e.g.,
facinconst factorial = function fac(n) { ... }).
Arrow Functions (ES6+)
A concise syntax for writing functions, especially useful for callbacks:
const add = (a, b) => a + b;
Uses the
=>syntax.Does not have its own
thisbinding, making it ideal for functional programming.
Key Concepts
Parameters vs. Arguments: Parameters are placeholders in the function definition; arguments are the actual values passed during a call.
Return Statement: Ends function execution and returns a value. If omitted, the function returns
undefined.Default Parameters: Allow setting fallback values if no argument is provided:
function greet(name = "Guest") { return "Hello, " + name; }Rest Parameters: Capture a variable number of arguments into an array:
function sum(...numbers) { return numbers.reduce((a, b) => a + b, 0); }
Functions are fundamental to JavaScript, enabling modularity, reusability, and clean code structure. They can be passed as arguments, returned from other functions, and used in callbacks, closures, and higher-order functions like map, filter, and reduce.
Final Words in javascript
JavaScript has 8 primary data types, categorized into primitive and non-primitive (reference) types.
Primitive Data Types
These are immutable, directly stored in memory, and represent single values:
string: Textual data, enclosed in quotes (e.g.,"hello").number: Numeric values, including integers and floating-point numbers (e.g.,42,3.14).bigint: Large integers with arbitrary precision (e.g.,9007199254740991n).boolean: Logical values, eithertrueorfalse.undefined: A variable declared but not assigned a value.null: Represents intentional absence of any object value.symbol: Unique and immutable identifiers, often used for object properties.
Non-Primitive (Reference) Data Type
object: A collection of key-value pairs (e.g.,{ name: "John" }). Includes arrays, functions, dates, maps, sets, and more.
Examples
let name = "Alice"; // string
let age = 25; // number
let isStudent = true; // boolean
let bigNum = 123456789012345678901234567890n; // bigint
let id = Symbol("id"); // symbol
let value = null; // null
let status; // undefined
let user = { name: "Bob" }; // object






