JavaScript Data Types

Heart
Heart

In JavaScript, Data Types Are Crucial For Defining And Manipulating Data. Let’s Dive Into The Different Types And How To Use Them Effectively.

Arrow
Heart

Introduction To Data Types 

Heart

JavaScript Has Dynamic Typing, Meaning Variables Can Hold Any Data Type.  Data Types Are Categorized As Primitive Or Composite.

Arrow
Heart
Heart

Data Type Examples

let name = "John"; // String let age = 30; // Number let isActive = true; // Boolean let user = { name: "John", age: 30 }; // Object let numbers = [1, 2, 3]; // Array

Arrow
Heart
Heart

Primitive Data Types

Number: Represents Numeric Values. String: Represents Text Enclosed In Quotes. Boolean: Represents True Or False.

Arrow
Heart
Heart

Primitive Data Types Example

let count = 42; // Number let greeting = "Hello, World!"; // String let isJavaScriptFun = true; // Boolean

Arrow

Composite Data Types

Heart
Heart
Arrow

Object: A Collection Of Key-Value Pairs. Array: An Ordered List Of Values.

Composite Data Types Example

Heart
Heart
Arrow

let person = { name: "Alice", age: 25 }; //  Object let fruits = ["apple", "banana", "cherry"]; // Array

Special Data Types 

Heart
Heart
Arrow

– Undefined: A Variable That Has Been Declared But Not Assigned A Value. – Null: Represents No Value Or An Empty Value. – Symbol: Unique And Immutable Values, Used For Object Property Keys.

Special Data Types Example

Heart
Heart
Arrow

let notAssigned; // Undefined let emptyValue = null; // Null let uniqueId = Symbol("id"); // Symbol

Type Conversion 

Heart
Heart
Arrow

JavaScript Allows Automatic (Implicit) And Manual (Explicit) Type Conversion.  Use Functions Like Number(), String(), And Boolean() To Convert Types.

Type Conversion Example 

Heart
Heart
Arrow

let num = "42"; // String let convertedNum = Number(num); // Explicit conversion to Number let implicitConversion = "5" * "2"; // Implicit conversion to Number

Checking Data Types 

Heart
Heart
Arrow

typeof: Returns The Data Type Of A Variable (E.G., typeof 42 Is "Number"). instanceof: Checks If An Object Is An Instance Of A Class Or Constructor (E.G., Arr Instanceof Array).

Differences Between var, let, and const 

Heart
Heart
Arrow

– var: Function-Scoped, Can Be Re-Declared And Updated. – let: Block-Scoped, Cannot Be Re-Declared But Can Be Updated. – const: Block-Scoped, Cannot Be Re-Declared Or Updated (Immutable).

Best Practices for Working with Data Types 

Heart
Heart
Arrow

– Avoid Using var Due To Its Function Scope And Potential Hoisting Issues. – Always Initialize Variables To Avoid undefined. – Perform Type Checks To Ensure Data Integrity. – Use Strict Equality (===) To Avoid Type Coercion Pitfalls.