TutorialsJSVariables & Data Types
Share:

Variables & Data Types

beginner

Part of JavaScript Fundamentals

Theory

Variables are containers for storing data values. JavaScript provides three keywords for declaring variables: var, let, and const. Understanding their differences is crucial for writing predictable code.

var was the original variable keyword. It has function scope (not block scope) and is hoisted to the top of its scope. var can be redeclared and updated, which can lead to bugs. Modern JavaScript discourages its use.

let was introduced in ES6 and has block scope. It can be updated but not redeclared in the same scope. let is the preferred choice for variables that will change.

const also has block scope but cannot be updated or redeclared. It must be initialized at declaration. For objects and arrays, const prevents reassignment of the variable but does not make the value immutable — you can still modify object properties or array elements.

let count = 5;
count = 10; // OK
// let count = 15; // Error: redeclaration
 
const PI = 3.14;
// PI = 3.15; // Error: assignment to constant
const person = { name: "John" };
person.name = "Jane"; // OK — object properties can change

Primitive data types are the building blocks of JavaScript:

  • string — text enclosed in quotes (', ", or `)
  • number — integers and floating-point numbers (IEEE 754)
  • booleantrue or false
  • null — intentional absence of any object value
  • undefined — variable declared but not assigned
  • symbol — unique, immutable value used as object keys
  • bigint — integers larger than 2^53 - 1

The typeof operator returns the type of a value. It is useful for debugging and type checking.

typeof "hello"; // "string"
typeof 42;      // "number"
typeof true;    // "boolean"
typeof null;    // "object" (this is a known JavaScript bug)

Type coercion is JavaScript's automatic conversion of values from one type to another. It happens in contexts like string concatenation and comparisons. While coercion can be convenient, it often leads to unexpected behavior.

Template literals (backtick strings) allow embedded expressions with ${} syntax and multi-line strings. They are more readable than string concatenation.

String methods like length, toUpperCase(), toLowerCase(), slice(), includes(), replace(), and trim() help manipulate text. Number methods like toFixed(), parseInt(), and parseFloat() help work with numeric values.

Practical Examples

Example 1: Variables and Scoping
javascript
Example 2: Data Types and typeof
javascript

Exercises

Variable Declaration Quiz

easy

Create three variables: one using const for your birth year, one using let for your current age, and one using var for your name. Print all three using console.log(). Then try to reassign the const variable and observe the error.

Starter Code:

// Declare your variables here

Expected Output:

1990\n35\nJohn

String Template Practice

easy

Create variables for a product name, price, and quantity. Use a template literal to print: 'You bought [quantity] [product](s) for $[total].' Calculate the total price.

Starter Code:

const product = 'Coffee';\nconst price = 5.99;\nconst quantity = 3;\n// Your code here

Expected Output:

You bought 3 Coffee(s) for $17.97.

Type Coercion Detective

medium

Write code that demonstrates at least 4 different type coercion scenarios. Print each result along with its type using typeof. Include examples of both string concatenation and numeric conversion.

Starter Code:

// Demonstrate type coercion below

Expected Output:

5 + '5' = 55 (string)\n'10' - 5 = 5 (number)\ntrue + 1 = 2 (number)\n'5' * '2' = 10 (number)

Mini Quiz

Mini Quiz

Mini Project

Mini Project: Personal ID Card Generator

Create a JavaScript program that stores a person's details using variables of different types and prints a formatted ID card to the console.

Requirements:

    Bonus Challenge

    Add an array of hobbies and print them as a comma-separated list.