Curriculum
JavaScript mein variables declare karne ke liye teen tareeke hain: var, let, aur const. Inka use samajhna ReactJS ke liye zaroori hai kyunki yeh code ko clean aur bug-free banate hain. Is section mein hum inke differences ko simple language mein, chhote examples ke saath samjhenge.
var JavaScript ka pehla variable declaration method hai. Yeh flexible hai lekin isme kuch issues hain.
undefined
milta hai.Example:
function example() { var x = 10; if (true) { var x = 20; // Yeh same x ko overwrite karta hai console.log(x); // Output: 20 } console.log(x); // Output: 20 (block scope nahi hai) } example(); console.log(y); // Output: undefined (hoisting) var y = 30;
Issue: var ke saath block scope nahi hota, isliye if
block ke andar wala x
bahar wale x
ko change kar deta hai. Yeh React mein bugs create kar sakta hai.
let ES6 (2015) mein aaya aur var ke issues ko fix karta hai.
{}
ke andar limited rehta hai.Example:
function example() { let x = 10; if (true) { let x = 20; // Yeh alag x hai, bahar wale x pe asar nahi console.log(x); // Output: 20 } console.log(x); // Output: 10 (block scope kaam karta hai) } example(); // console.log(y); // Error: y is not defined (Temporal Dead Zone) let y = 30;
Advantage: let block scope ke wajah se React components mein safe hai, kyunki variables unintentionally overwrite nahi hote.
const bhi ES6 ka hissa hai aur variables ko constant banata hai.
Example:
function example() { const x = 10; // x = 20; // Error: Assignment to constant variable console.log(x); // Output: 10 const arr = [1, 2, 3]; arr.push(4); // Yeh allowed hai kyunki array ka content change ho sakta hai console.log(arr); // Output: [1, 2, 3, 4] } example(); // console.log(y); // Error: y is not defined (Temporal Dead Zone) const y = 30;
Advantage: const React mein state ya props ke liye perfect hai jab aap ensure karna chahte ho ki variable ki value change na ho.
React mein, let aur const ka zyada use hota hai kyunki yeh block scope dete hain aur bugs kam karte hain. var avoid karo kyunki iska function scope aur re-declaration issues code ko complex bana sakte hain.
React Example:
import React, { useState } from 'react'; function App() { const title = 'ReactJS Domination'; // const kyunki title change nahi hoga let count = 0; // let kyunki count baad mein change ho sakta hai const [likes, setLikes] = useState(0); // const kyunki state variable reassign nahi hota function handleClick() { count = count + 1; // let isliye kaam karta hai setLikes(likes + 1); // State update ke liye console.log(<code>${title}: ${count} clicks, ${likes} likes</code>); } return ( <div> <h1>{title}</h1> <button>Click Karo</button> </div> ); } export default App;
Key Points:
Not a member yet? Register now
Are you a member? Login now