Basic Variables
In JavaScript, variables act as containers for storing data values. Understanding the foundational data types and how to store them is critical for managing state in any application.
Data Types
Some of the most common primitive variable types in JavaScript include:
- number: Represents both integer and floating-point numbers.
- boolean: A true or false value.
- string: A sequence of characters representing text.
- undefined: Indicates that a variable has been declared but has not yet been assigned a value.
The var Keyword
Historically, the var keyword was the primary way to declare a variable in JavaScript.
var limit = 100; // number
var isAdmin = true; // boolean
var username = "eddie_cabot"; // string
var nothing = undefined; // undefined
While you will frequently encounter var in legacy codebases, modern JavaScript offers improved methods for declaring variables that provide better scoping rules, which we will explore next.
Practical Example
When a script runs, logging variables allows you to verify the application’s state.
var username = "eddie_cabot";
var isAdmin = true;
var sendingLimit = 100;
var costPerItem = 0.05;
console.log("username:", username);
console.log("isAdmin:", isAdmin);
console.log("sendingLimit:", sendingLimit);
console.log("costPerItem:", costPerItem);