JavaScript Basics
JavaScript Data Types
- Primitive Data Types:
- Numbers: e.g., 123, 120.50
- Strings: e.g., "This text string"
- Boolean: e.g., true or false
- Trivial Data Types:
- Composite Data Type:
- Object (to be covered in detail later)
JavaScript Variables
- Variables: Named containers for data.
- Declaration: Must use the
var keyword.- e.g.,
var money; or var money, name;
- Initialization: Storing a value in a variable.
- Can occur at creation or later.
- Example:
var name = "Ali";, money = 2000.50;
- Scope:
- Global Variables: Accessible anywhere in the code.
- Local Variables: Accessible only within the function it's defined.
Variable Scope in JavaScript
- Local vs Global:
- A local variable can have the same name as a global variable, but it hides the global one.
- Example:
javascript
var myVar = "global";
function checkscope() {
var myVar = "local";
document.write(myVar);
}
Naming Conventions
- Do not use reserved keywords (e.g.,
break, boolean). - Names must start with a letter or underscore, not a numeral.
- Valid:
_123test | Invalid: 123test
- Variable names are case-sensitive (e.g.,
Name vs name).
Reserved Words in JavaScript
- Reserved words cannot be used as variable names:
abstract, boolean, break, byte, case, catch, char, class, const, continue, debugger, default, delete, do, double, else, enum, export, extends, false, final, finally, float, for, function, goto, if, implements, import, instanceof, int, interface, long, native, new, null, package, private, protected, public, return, short, static, super, switch, synchronized, this, throw, throws, transient, true, try, typeof, var, void, volatile, while, with.