Variables and Data Types
Learn about variables, their declaration, and different data types in JavaScript, including strings, numbers, booleans, null, and undefined.
JavaScript Essentials: Variables and Data Types
Introduction
This section provides an overview of variables and data types, fundamental concepts in JavaScript programming.
Variables in JavaScript
Variables are containers for storing data values. In JavaScript, you can declare variables using the var
, let
, and const
keywords.
Variable Declaration
var
: The oldest way to declare a variable. It has function scope, meaning it's accessible within the function it's declared in (or globally if declared outside any function).
var myVariable = "Hello, world!";
console.log(myVariable); // Output: Hello, world!
let
: Similar to var
but with block scope. This means it's only accessible within the block (e.g., inside an if
statement or loop) where it's defined. Preferred over `var` for more predictable scoping.
let myLetVariable = 42;
console.log(myLetVariable); // Output: 42
if (true) {
let myLetVariable = "Inside the block!";
console.log(myLetVariable); // Output: Inside the block!
}
console.log(myLetVariable); // Output: 42 (the original variable)
const
: Declares a constant variable. Its value cannot be reassigned after it's initially defined. However, if the `const` variable holds an object or array, the *contents* of that object/array can still be modified.
const myConstVariable = 3.14;
console.log(myConstVariable); // Output: 3.14
// myConstVariable = 5; // This will cause an error!
const myArray = [1, 2, 3];
myArray.push(4); // This is allowed! (modifying the *contents* is ok)
console.log(myArray); // Output: [1, 2, 3, 4]
// myArray = [5, 6, 7]; // This would cause an error! (reassigning the array)
Variable Naming Conventions
- Variable names can contain letters, digits, underscores, and dollar signs.
- Variable names must begin with a letter, an underscore (_), or a dollar sign ($).
- Variable names are case-sensitive (
myVar
andmyvar
are different variables). - Use descriptive and meaningful names.
- Use camelCase for variable names (e.g.,
firstName
,userAge
).
Data Types in JavaScript
JavaScript is a dynamically typed language, which means you don't have to explicitly specify the data type of a variable when you declare it. The JavaScript engine determines the type at runtime.
Primitive Data Types
These data types hold a single value directly.
- String: Represents textual data.
- Number: Represents numeric data (integers and floating-point numbers).
- Boolean: Represents a logical value, either
true
orfalse
. - Null: Represents the intentional absence of a value.
- Undefined: Represents a variable that has been declared but has not been assigned a value.
String
Strings are sequences of characters enclosed in single quotes ('
), double quotes ("
), or backticks (`
).
let myString1 = 'This is a string.';
let myString2 = "This is also a string.";
let myString3 = `This is a template literal (string).`;
// Template literals allow variable interpolation:
let name = "Alice";
let greeting = `Hello, ${name}!`; // greeting will be "Hello, Alice!"
console.log(greeting);
Number
Numbers can be integers or floating-point numbers.
let myInteger = 10;
let myFloat = 3.14;
let myNegative = -5;
console.log(myInteger + myFloat); // Output: 13.14
Boolean
Booleans represent truthy or falsy values, commonly used in conditional statements.
let isTrue = true;
let isFalse = false;
if (isTrue) {
console.log("This will be printed.");
} else {
console.log("This won't be printed.");
}
Null
null
is an assignment value. It means a variable is intentionally empty. It's different from `undefined`.
let myNullValue = null;
console.log(myNullValue); // Output: null
Undefined
undefined
means a variable has been declared but not assigned a value yet.
let myUndefinedVariable;
console.log(myUndefinedVariable); // Output: undefined
Complex Data Types
These data types can hold multiple values or more complex structures.
- Object: A collection of key-value pairs.
- Array: An ordered list of values.
Object
Objects are collections of properties, where each property has a name (key) and a value. Values can be any data type, including other objects and arrays.
let myObject = {
firstName: "Bob",
lastName: "Smith",
age: 30,
address: {
street: "123 Main St",
city: "Anytown"
}
};
console.log(myObject.firstName); // Output: Bob
console.log(myObject.address.city); // Output: Anytown
Array
Arrays are ordered lists of values, indexed starting from 0.
let myArray = [10, "hello", true, { name: "Charlie" }];
console.log(myArray[0]); // Output: 10
console.log(myArray[1]); // Output: hello
console.log(myArray[3].name); // Output: Charlie
typeof Operator
You can use the typeof
operator to determine the data type of a variable.
console.log(typeof "Hello"); // Output: string
console.log(typeof 42); // Output: number
console.log(typeof true); // Output: boolean
console.log(typeof null); // Output: object (historical quirk)
console.log(typeof undefined); // Output: undefined
console.log(typeof { name: "David" }); // Output: object
console.log(typeof [1, 2, 3]); // Output: object