Type Casting

Introduction

जब हम JavaScript में काम करते हैं, तो कई बार हमें एक data type को दूसरे data type में बदलने की जरूरत पड़ती है।

सोचिए—अगर user form में number की जगह text डाल दे, या हमें string को number में convert करके calculation करनी हो, तो क्या करेंगे?

यहीं पर Type Casting काम आती है। यह हमें एक data type को दूसरे type में convert करने की सुविधा देती है।

Web Development में यह बहुत जरूरी है, खासकर form validation और calculations में।

Definition

Type Casting वह प्रक्रिया है जिसमें एक data type को दूसरे data type में convert किया जाता है।

Concept

1. Types of Type Casting

JavaScript में Type Casting दो प्रकार की होती है:

  • Implicit Type Casting
  • Explicit Type Casting

2. Implicit Type Casting (Automatic)

जब JavaScript खुद से data type change कर देती है, तो उसे implicit casting कहते हैं।

Example:

<script>
let result = "5" + 2;
console.log(result);
</script>

Output:
52

Explanation:
यहाँ number 2 string में convert हो गया और concatenation हो गया।

Example 2:

<script>
let result = "5" - 2;
console.log(result);
</script>

Output:
3

Explanation:
यहाँ string “5” number में convert हो गई।

3. Explicit Type Casting (Manual)

जब programmer खुद data type convert करता है, तो उसे explicit casting कहते हैं।

(a) String to Number

<script>
let num = Number("10");
console.log(num);
</script>

Output:
10

(b) Number to String

<script>
let str = String(100);
console.log(str);
</script>

Output:
100

(c) Using parseInt()

<script>
let x = parseInt("25");
console.log(x);
</script>

Output:
25

(d) Using parseFloat()

<script>
let y = parseFloat("10.5");
console.log(y);
</script>

Output:
10.5

4. Boolean Conversion

<script>
let value = Boolean(1);
console.log(value);
</script>

Output:
true

Real-Life Example

मान लीजिए user ने form में age “18” (string) के रूप में डाली है।

अगर हमें calculation करनी है, तो हमें उसे number में convert करना पड़ेगा।

ठीक इसी तरह Type Casting real-world applications में काम आती है।

Important Points

Type Casting data type change करने की प्रक्रिया है
Implicit casting automatic होती है
Explicit casting manually की जाती है
Number(), String(), Boolean() commonly use होते हैं
parseInt() और parseFloat() useful functions हैं

निष्कर्ष

Type Casting JavaScript का एक महत्वपूर्ण concept है, जो different data types के बीच conversion को आसान बनाता है। यह form handling, calculations और data processing में बहुत उपयोगी होता है।

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top