J

Variáveis & Tipos de Dados

JavaScript Syntax Guide

Variáveis e tipos de dados em JavaScript

Variáveis & Tipos de Dados

Variáveis e tipos de dados em JavaScript

JavaScript variáveis & tipos de dados (javascript)
        
          // 1. Variable Declarations - Modern approach
let userName = "Alice";        // Block-scoped, can be reassigned
const PI = 3.14159;           // Block-scoped, cannot be reassigned
const CONFIG = {              // Object properties can be modified
  apiUrl: "https://api.example.com",
  timeout: 5000
};
CONFIG.timeout = 10000;        // ✅ This works

// 2. Data Types
let string = "Hello World";    // String
let number = 42;               // Number (all numbers are floats)
let boolean = true;            // Boolean
let array = [1, 2, 3, 4];      // Array
let object = {                 // Object
  name: "John",
  age: 30,
  isActive: true
};

// 3. Special Values
let nothing = null;            // Intentional absence of value
let notDefined;                // undefined (default value)
let bigNumber = 1234567890123456789012345678901234567890n; // BigInt
let uniqueId = Symbol('user_id'); // Unique identifier

// 4. Type Checking
console.log(typeof userName);   // "string"
console.log(typeof number);     // "number"
console.log(typeof boolean);    // "boolean"
console.log(typeof array);      // "object" (arrays are objects)
console.log(typeof nothing);    // "object" (historical bug)
console.log(typeof notDefined); // "undefined"
console.log(typeof bigNumber);  // "bigint"
console.log(typeof uniqueId);   // "symbol"

// 5. Type Conversion
let num = 42;
let str = String(num);         // "42"
let backToNum = Number(str);   // 42
let boolStr = Boolean(1);      // true
let emptyStr = Boolean("");    // false

// 6. Common Pitfalls
// ❌ Don't do this:
if (userName = "Bob") {        // Assignment instead of comparison
  console.log("This always runs!");
}

// ✅ Do this instead:
if (userName === "Bob") {
  console.log("Name matches!");
}
        
      

Explanation

JavaScript usa let, const e var para declarar variáveis. let e const têm escopo de bloco, enquanto var tem escopo de função.

Common Use Cases

  • Armazenar entrada do usuário
  • Cálculos temporários
  • Configurações

Related JavaScript Syntax

Master Variáveis & Tipos de Dados in JavaScript

Understanding Variáveis & Tipos de Dados is fundamental to writing clean and efficient JavaScript code. This comprehensive guide provides you with practical examples and detailed explanations to help you master this important concept.

Whether you're a beginner learning the basics or an experienced developer looking to refresh your knowledge, our examples cover real-world scenarios and best practices for using Variáveis & Tipos de Dados effectively in your JavaScript projects.

Key Takeaways

  • Armazenar entrada do usuário
  • Cálculos temporários
  • Configurações