~/
hackweb.dev
JavaScript Variables & Data Types
Quiz
⌘K
...
~/
/tutorials
/js/js-variables/edit
~ Contribute
Suggest a correction or improvement. The author reviews it before it goes live.
Loading...
Comment
0 / 300
Typo
Grammar
Broken link
Clarify
Code
en/tutorials/js/1js-variables
Write
Preview
Diff
# JavaScript Variables & Data Types Variables store data values. JavaScript has multiple ways to declare variables and many data types. ## Declaring Variables ### `var` — Old Way (Avoid) ```javascript var name = "John"; var age = 25; ``` Function-scoped, can be redeclared, and hoisted. Use `let` or `const` instead. ### `let` — When Reassigning ```javascript let name = "John"; name = "Jane"; // OK ``` Block-scoped and can be reassigned. ### `const` — Default Choice ```javascript const PI = 3.14159; // PI = 3; // Error! ``` Block-scoped, cannot be reassigned. Must initialize immediately. **Rule:** Use `const` by default. Use `let` only when reassignment is needed. ## Naming Rules ```javascript let userName = "John"; // camelCase let _private = true; // underscore OK let $element = "div"; // dollar sign OK // let 123abc = "bad"; // Error: can't start with number // let my-name = "bad"; // Error: no hyphens ``` **Convention:** Use camelCase for variables and functions. ## Primitive Data Types ```javascript let name = "John"; // String let age = 25; // Number let isActive = true; // Boolean let x; // undefined let data = null; // null let id = Symbol('id'); // Symbol let big = 9007199254740991n; // BigInt ``` **Remember:** `null` is intentional emptiness. `undefined` means no value assigned. ## Checking Types ```javascript typeof "John" // "string" typeof 25 // "number" typeof true // "boolean" typeof undefined // "undefined" typeof null // "object" (known JS bug) typeof {} // "object" typeof [] // "object" ``` ## Type Conversion ```javascript // String → Number Number("123") // 123 parseInt("123abc") // 123 +"123" // 123 // Number → String String(123) // "123" (123).toString() // "123" `${123}` // "123" // To Boolean Boolean(0) // false Boolean("") // false Boolean(null) // false Boolean("hello") // true Boolean({}) // true Boolean([]) // true ``` ## Best Practices 1. **Use `const` by default** — `let` only when needed 2. **Use descriptive names** — `userName` not `x` 3. **Use camelCase** — `myVariable` not `my_variable` 4. **Initialize variables** — Avoid `undefined` 5. **Use template literals** — Instead of string concatenation ## Common Mistakes 1. **Using `var`** — Use `let`/`const` instead 2. **Redeclaring with `let`** — Not allowed 3. **Confusing `null` and `undefined`** — Different meanings 4. **Using `typeof null`** — Returns `"object"` (bug in JS) 5. **Confusing `=` and `===`** — Assignment vs comparison
No changes yet
Reset to original
Submit suggestion
cancel