Variables & Data Types in JavaScript

Variables are containers for storing data values. In JavaScript, there are several ways to declare variables, and understanding data types is crucial for effective programming.

Declaring Variables in JavaScript

JavaScript provides three ways to declare variables: var, let, and const. Each has different scoping rules and behaviors.

1. Using var (Pre-ES6)

The var keyword was traditionally used to declare variables in JavaScript before ES6 (2015). Variables declared with var are function-scoped or globally-scoped, not block-scoped.

// Function-scoped variable
function exampleFunction() {
var x = 10; // Only accessible within this function
console.log(x); // 10
}

// Global variable
var y = 20; // Accessible throughout the script

// var variables can be redeclared
var y = 30; // This is allowed

// var variables are hoisted
console.log(z); // undefined (not an error)
var z = 40;

2. Using let (ES6+)

The let keyword was introduced in ES6 and provides block-scoped variables. This means variables declared with let are only accessible within the block they are defined in.

// Block-scoped variable
if (true) {
let x = 10; // Only accessible within this block
console.log(x); // 10
}
// console.log(x); // Error: x is not defined

// let variables cannot be redeclared in the same scope
let y = 20;
// let y = 30; // This would cause an error

// let variables are not hoisted in the same way as var
// console.log(z); // Error: Cannot access 'z' before initialization
let z = 40;

3. Using const (ES6+)

The const keyword also provides block-scoped variables, but with one important difference: variables declared with const cannot be reassigned after they are initialized.

// Constant variable
const PI = 3.14159;
// PI = 3.14; // Error: Assignment to constant variable

// Block-scoped like let
if (true) {
const x = 10;
console.log(x); // 10
}
// console.log(x); // Error: x is not defined

// Objects and arrays declared with const can still be modified
const person = { name: "John" };
person.name = "Jane"; // This is allowed

const numbers = [1, 2, 3];
numbers.push(4); // This is allowed
// numbers = [5, 6]; // Error: Assignment to constant variable

Best Practices for Variable Declaration

  • Use const by default for all variables that don't need to be reassigned
  • Use let for variables that need to be reassigned
  • Avoid using var in modern JavaScript code
  • Always declare variables before using them
  • Use descriptive variable names that explain their purpose

JavaScript Data Types

JavaScript is a dynamically typed language, which means you don't need to specify the data type when declaring a variable. However, understanding the different data types is essential.

Primitive Data Types

JavaScript has 7 primitive data types:

// 1. String - for text values
let name = "John Doe";
let greeting = 'Hello, world!';
let template = `My name is ${name}`; // Template literals (ES6+)

// 2. Number - for numeric values (integers and floating-point)
let age = 25;
let price = 19.99;
let infinity = Infinity;
let notANumber = NaN; // Result of invalid calculations

// 3. Boolean - true or false
let isActive = true;
let hasPermission = false;

// 4. Undefined - variable declared but not assigned a value
let undefinedVar;
console.log(undefinedVar); // undefined

// 5. Null - intentional absence of any object value
let emptyValue = null;

// 6. Symbol (ES6+) - unique and immutable value
let uniqueKey = Symbol("description");
let anotherKey = Symbol("description"); // Different from uniqueKey

// 7. BigInt (ES2020) - for integers larger than Number can represent
let bigNumber = 9007199254740991n; // The 'n' suffix creates a BigInt

Reference Data Types

JavaScript also has reference data types, which are objects that store collections of data:

// 1. Object - collection of key-value pairs
let person = {
firstName: "John",
lastName: "Doe",
age: 30,
isEmployed: true
};

// Accessing object properties
console.log(person.firstName); // John
console.log(person["lastName"]); // Doe

// 2. Array - ordered collection of values
let colors = ["red", "green", "blue"];
let mixed = [1, "hello", true, { id: 1 }]; // Arrays can hold different types

// Accessing array elements
console.log(colors[0]); // red
console.log(mixed[3].id); // 1

// 3. Function - callable object
function greet(name) {
return `Hello, ${name}!`;
}

// Functions can be assigned to variables
let sayHello = greet;
console.log(sayHello("Alice")); // Hello, Alice!

// 4. Date - for working with dates and times
let today = new Date();
console.log(today); // Current date and time

// 5. RegExp - for pattern matching
let pattern = /^\d{3}-\d{2}-\d{4}$/; // Social Security Number pattern
console.log(pattern.test("123-45-6789")); // true

Type Checking and Conversion

Since JavaScript is dynamically typed, it's often useful to check the type of a variable or convert between types.

// Checking types with typeof operator
console.log(typeof "hello"); // string
console.log(typeof 42); // number
console.log(typeof true); // boolean
console.log(typeof undefined); // undefined
console.log(typeof null); // object (this is a known JavaScript quirk)
console.log(typeof {}); // object
console.log(typeof []); // object (arrays are objects in JavaScript)
console.log(typeof function(){}); // function

// Type conversion
// String to Number
let numStr = "42";
let num1 = Number(numStr); // 42
let num2 = parseInt(numStr); // 42
let num3 = parseFloat("42.5"); // 42.5
let num4 = +numStr; // 42 (unary plus operator)

// Number to String
let num = 42;
let str1 = String(num); // "42"
let str2 = num.toString(); // "42"
let str3 = num + ""; // "42" (concatenation with empty string)

// To Boolean
let bool1 = Boolean(1); // true
let bool2 = Boolean(0); // false
let bool3 = Boolean(""); // false
let bool4 = Boolean("hello"); // true
let bool5 = !!num; // true (double negation)

Practice Exercise

Try creating a JavaScript file that declares different types of variables and performs various operations on them. For example:

  1. Declare variables using let, const, and var
  2. Create variables of each primitive data type
  3. Create an object with nested properties
  4. Convert between different data types
  5. Use typeof to check the type of each variable

Common Pitfalls

  • Equality operators: == performs type conversion, while === checks both value and type
  • NaN: Use isNaN() to check if a value is NaN, as NaN === NaN returns false
  • Undefined vs Null: undefined means a variable has been declared but not assigned a value, while null is an intentional absence of value
  • Object comparison: Objects are compared by reference, not by value
  • Temporal Dead Zone: Variables declared with let and const cannot be accessed before declaration