Chapter 1 Cheatsheet: Variables & Basics

This cheatsheet summarizes the fundamental concepts of JavaScript variables, data types, and syntax. Use it as a quick reference when building your projects!

Variables

  • let: Used for variables that can be reassigned. (Block-scoped)
  • const: Used for variables that should never be reassigned. (Block-scoped)
  • var: The legacy way to declare variables. Avoid using it in modern code unless necessary. (Function-scoped)
let username = "dengar";
username = "boba"; // valid

const maxLimit = 1000;
// maxLimit = 2000; // Error! Cannot reassign a const

Pro Tip: You can declare multiple variables on a single line:

let a = 1, b = 2, c = 3;

Data Types (Primitives)

JavaScript is dynamically and weakly typed. The primary primitive types include:

  • number: Handles both integers and decimals (42, 3.14, -10).
  • string: Textual data, wrapped in quotes ("Hello", 'World').
  • boolean: Logical values (true or false).
  • undefined: A variable that has been declared but has no value yet.
  • null: The intentional, explicit absence of any object value.

Numbers & Math

All numeric data is handled by the number type.

  • Arithmetic: +, -, *, /
  • Shorthand Assignment: +=, -=
  • Increment/Decrement: ++ (adds 1), -- (subtracts 1)
let score = 10;
score++; // 11
score += 5; // 16

Strings & Template Literals

Strings are zero-indexed and represent UTF-16 code units.

  • Length: Get the number of units using .length ("boots".length // 5).
  • Indexing: Access characters with brackets ("cat"[0] // 'c').

Template Literals: Use backticks (`) to easily insert variables and logic directly into strings using ${}.

const user = "Saul";
const rate = 30.5;
console.log(`Hi ${user}, your rate is ${rate}%!`);

Syntax & Conventions

  • Comments:
    • Single-line: // comment
    • Multi-line: /* comment */
  • Semicolons: Optional due to Automatic Semicolon Insertion (ASI), but highly recommended to avoid bugs.
  • Casing: The JavaScript standard for naming variables and functions is camelCase.

Key Concepts

  • Dynamic Typing: Variables can change type at runtime (e.g., a number can later hold a string).
  • Weak Typing (Coercion): JavaScript will try to automatically convert types when they clash (e.g., "50" + 10 becomes "5010").
  • JavaScript vs. Java: They are entirely different languages. Java is to JavaScript as car is to carpet.
  • Performance: JavaScript is garbage-collected, single-threaded, and Just-In-Time (JIT) compiled.