Log In

Don't have an account? Sign up now

Lost Password?

Sign Up

Prev Next

Module 3: Data Types & Type Coercion

1. The Two Categories of Data Types

In JavaScript, data types are divided into Primitives and Objects.

A. Primitive Types (Immutable)

These are stored by value in the Stack. Once created, they cannot be changed (you can only reassign a new value to the variable).

  1. Number: 64-bit floating point (handles integers and decimals). Includes Infinity and NaN (Not a Number).
  2. String: Text data enclosed in ' ', " ", or ` `.
  3. Boolean: Only true or false.
  4. Undefined: A variable that has been declared but not assigned a value.
  5. Null: Intentional absence of value.
  6. Symbol: Unique and immutable identifier (introduced in ES6).
  7. BigInt: For integers larger than $2^{53} – 1$.

B. Reference Types (Objects)

Stored in the Heap. These include:

  • Objects { }
  • Arrays [ ]
  • Functions function() {}

2. The typeof Operator

The typeof operator is used to check the type of a value. However, it has a famous “bug” that you must remember for interviews:

JavaScript

console.log(typeof 42);           // "number"
console.log(typeof "Hello");      // "string"
console.log(typeof true);         // "boolean"
console.log(typeof undefined);    // "undefined"
console.log(typeof { name: "A" }); // "object"

// THE WEIRD ONES:
console.log(typeof null);         // "object" (This is a historical bug in JS!)
console.log(typeof function(){}); // "function" (Technically an object, but returns function)

3. Type Coercion (Implicit Conversion)

JavaScript is a loosely typed language. This means it automatically converts types when needed.

A. String Coercion

When you use the + operator with a string, JS converts the other value to a string.

JavaScript

console.log("5" + 2);    // "52" (Number 2 is coerced to string)
console.log("5" + true); // "5true"

B. Number Coercion

Other mathematical operators (-, *, /, %) convert strings to numbers.

JavaScript

console.log("10" - 2);   // 8
console.log("10" * "3"); // 30
console.log("10" / "two");// NaN (Not a Number)

C. Boolean Coercion (Truthy vs. Falsy)

In a conditional (like an if statement), JS coerces values to Booleans.

Falsy Values (There are only 6):

  1. false
  2. 0 (and -0, 0n)
  3. "" (Empty string)
  4. null
  5. undefined
  6. NaN

Everything else is Truthy, including empty arrays [] and empty objects {}.


4. Double Equals (==) vs. Triple Equals (===)

This is the most common source of bugs.

  • == (Abstract Equality): Compares values after performing type coercion.
  • === (Strict Equality): Compares both value and type without coercion.

Example:

JavaScript

console.log(5 == "5");  // true (Coerces string to number)
console.log(5 === "5"); // false (Different types)

console.log(null == undefined);  // true
console.log(null === undefined); // false

Pro Tip: Always use === to avoid unexpected bugs.


5. Explicit Type Conversion

Sometimes you want to convert types manually to keep your code predictable.

JavaScript

// To String
String(123); // "123"
(123).toString();

// To Number
Number("123"); // 123
parseInt("123.45px"); // 123
parseFloat("123.45px"); // 123.45

// To Boolean
Boolean(1); // true
Boolean(0); // false
!!(1);      // true (Short way using "double bang")

In Simple Words

1. Introduction to Data Types

What is a Data Type?

A data type defines:

  • What kind of data a variable can store
  • How much memory is allocated
  • What operations can be performed on it

Example:

  • int age = 21;int is the data type

Why Data Types Are Important

  • Efficient memory usage
  • Data safety
  • Faster execution
  • Prevent invalid operations

2. Classification of Data Types

High-Level Classification

  1. Primitive (Basic) Data Types
  2. Non-Primitive (Derived / Reference) Data Types
  3. User-Defined Data Types

3. Primitive Data Types

1. Integer Types

Used to store whole numbers.

TypeTypical Size
byte1 byte
short2 bytes
int4 bytes
long8 bytes

Examples:

  • int count = 10;
  • long population = 1400000000;

2. Floating-Point Types

Used for decimal values.

TypePrecision
floatSingle precision
doubleDouble precision

Example:

  • double price = 99.99;

3. Character Type

Stores a single character.

Example:

  • char grade = 'A';

4. Boolean Type

Stores true or false values.

Example:

  • boolean isActive = true;

4. Non-Primitive (Reference) Data Types

1. Arrays

  • Store multiple values of the same type
  • Stored in heap memory

Example:

int marks[5]

2. Strings

  • Sequence of characters
  • Immutable in many languages (Java, Python)

Example:

  • "Hello World"

3. Objects

  • Instance of a class
  • Stores data and behavior

4. Pointers / References

  • Store memory address of another variable
  • Used for memory efficiency and performance

5. User-Defined Data Types

1. Structure (C/C++)

Groups different data types.

Example:

struct Student {
   int id;
   char name[20];
};

2. Union

Shares memory among variables.


3. Enum

Defines named constants.

Example:

enum Status { ACTIVE, INACTIVE };

4. Class

Blueprint of objects (OOP).


6. Type Conversion

What is Type Conversion?

Converting one data type into another.

Two types:

  1. Implicit Type Conversion
  2. Explicit Type Conversion (Type Casting)

7. Implicit Type Conversion (Type Promotion)

Definition

Automatically done by the compiler or interpreter.

Example:

  • int → float
  • float → double

Example:

int a = 10;
double b = a;

Rules

  • Smaller types → larger types
  • No data loss (generally)

8. Explicit Type Conversion (Type Casting)

Definition

Manually converting one type to another.

Example:

double x = 9.8;
int y = (int)x;

Characteristics

  • Possible data loss
  • Programmer responsibility

9. Widening vs Narrowing Conversion

Widening

  • Small → large data type
  • Safe conversion

Example:

  • int → double

Narrowing

  • Large → small data type
  • Risky conversion

Example:

  • double → int

10. Type Coercion

What is Type Coercion?

Automatic conversion of data types during expression evaluation, often seen in loosely-typed languages.

Example:

"5" + 2 = "52"
"5" - 2 = 3

(Common in JavaScript, Python to a limited extent)


11. Type Coercion vs Type Conversion

AspectType ConversionType Coercion
ManualYesNo
AutomaticSometimesYes
ControlProgrammerLanguage
RiskMediumHigh

12. Strongly Typed vs Weakly Typed Languages

Strongly Typed

  • Strict type rules
  • Less unexpected behavior

Examples:

  • Java
  • Python

Weakly Typed

  • Automatic coercion
  • Flexible but risky

Example:

  • JavaScript

13. Type Checking

Compile-Time Type Checking

  • Errors detected during compilation
  • Faster execution

Example:

  • C, C++, Java

Run-Time Type Checking

  • Errors detected during execution
  • More flexible

Example:

  • Python, JavaScript

14. Type Safety

What is Type Safety?

Ensures operations are performed on compatible data types.

Benefits:

  • Prevents crashes
  • Improves reliability
  • Makes code predictable

15. Common Type Coercion Pitfalls

  • Unexpected string concatenation
  • Precision loss
  • Boolean confusion (0, 1, true, false)
  • Comparison errors (== vs ===)

16. Best Practices

  • Avoid unnecessary type casting
  • Use explicit conversions for clarity
  • Prefer strongly typed constructs
  • Validate input types
  • Use strict comparison operators

Leave a Comment

    🚀 Join Common Jobs Pro — Referrals & Profile Visibility Join Now ×
    🔥