Variables & Data Types
Dieser Inhalt ist noch nicht in deiner Sprache verfügbar.
Prerequisites:
Variables are containers for storing data values. JavaScript has three ways to declare variables.
Variable Declarations
Section titled “Variable Declarations”let - Block-scoped, reassignable
Section titled “let - Block-scoped, reassignable”let message = "Hello";message = "World"; // OK - can be reassignedconst - Block-scoped, not reassignable
Section titled “const - Block-scoped, not reassignable”const PI = 3.14159;// PI = 3; // Error! Cannot reassign constvar - Function-scoped (legacy)
Section titled “var - Function-scoped (legacy)”var oldStyle = "Avoid using var";Data Types
Section titled “Data Types”Primitive Types
Section titled “Primitive Types”// Stringconst name = "JavaScript";
// Numberconst age = 25;const price = 99.99;
// Booleanconst isActive = true;
// Undefinedlet notAssigned;
// Nullconst empty = null;
// Symbol (ES6)const id = Symbol("id");
// BigInt (ES2020)const bigNumber = 9007199254740991n;Checking Types
Section titled “Checking Types”typeof "hello" // "string"typeof 42 // "number"typeof true // "boolean"typeof undefined // "undefined"typeof null // "object" (historical bug)typeof Symbol() // "symbol"typeof {} // "object"typeof [] // "object"Type Coercion
Section titled “Type Coercion”JavaScript automatically converts types in certain situations:
// String concatenation"5" + 3 // "53" (number becomes string)
// Numeric operations"5" - 3 // 2 (string becomes number)"5" * "2" // 10
// Boolean contextBoolean("") // falseBoolean("hi") // trueBoolean(0) // falseBoolean(1) // true// Global scopeconst global = "I'm everywhere";
function example() { // Function scope const local = "I'm local";
if (true) { // Block scope let blockScoped = "Only here"; const alsoBlock = "Also only here"; } // blockScoped is not accessible here}Next Steps
Section titled “Next Steps”With variables mastered, learn about Functions to write reusable code.