මේකෙන් අපි ආරම්භ කරනවා අපේ ReactJS Bootcamp එකේ පළවෙනි දවස. මෙහිදී අපි JavaScript fundamentals ගැන කතා කරමු, විශේෂයෙන් variables සහ scope ගැන. මේක ඔබට ගොඩක් වැදගත් වෙනවා React වලදී state සහ props හරියට manage කරන්න. මම මේක ඔබට කියලා දෙන්නේ ගුරුවරයෙක් student කෙනෙක්ට ගොඩක් ලේසියෙන් තේරෙන විදියට, boring නොවෙන්නෙ ගමනක් යන ගමන් කතාවක් කියන feeling එකෙන්.
1. Theory: Variables සහ Scope ගැන තේරුම
JavaScript වලදී variables declare කරන්න තියෙනවා තුනක්: var, let, සහ const.
Scope කියන්නේ variable එකකට access කරන්න පුළුවන් තැන:
Hoisting කියන්නේ code එක run වෙන්න කලින් variable declarations scope එකේ උඩට ගෙනියන එක. var එක්ක එන්නේ undefined විදියට, ඒත් let සහ const එක්ක error එකක් දෙනවා declare කරන්න කලින් use කළොත්.
2. Code Examples: උදාහරණ බලමු
අපි දැන් මේ ටික practical විදියට බලමු:
// Hoisting with var console.log(x); // undefined var x = 10; console.log(x); // 10 // Hoisting with let console.log(y); // ReferenceError: y is not defined let y = 20; console.log(y); // 20 // Scope in loops for (var i = 0; i < 5; i++) { console.log(i); // 0 to 4 } console.log(i); // 5 (loop එකෙන් එළියටත් access වෙනවා) for (let j = 0; j < 5; j++) { console.log(j); // 0 to 4 } console.log(j); // ReferenceError: j is not defined
React වලදී බලමු:
import React from 'react'; function MyComponent() { const name = 'Alice'; let age = 30; return <div>{name} is {age} years old.</div>; }
මෙතන name සහ age block scope එකේ තමයි තියෙන්නේ, component එකෙන් එළියට leak වෙන්නේ නෑ.
3. Use Cases: Real-World Scenarios
React වලදී scope ගොඩක් වැදගත්. උදාහරණයක් විදියට, loop එකක event listeners දානකොට let use කළොත් හැම listener එකටම correct value එක capture වෙනවා:
for (let index = 0; index < 3; index++) { document.getElementById(`button${index}`).addEventListener('click', () => { console.log(index); }); }
var use කළොත් හැම එකම එකම value එක log වෙනවා, ඒක bug එකක් වෙන්න පුළුවන්.
4. Troubleshooting: Common Pitfalls
Beginner ලාට ගොඩක් වෙන ගැටලු:
Solutions:
6. Best Practices: කවදා Use කරන්නේ/අඩුවෙන් Use කරන්නේ