learn-javascript

๐Ÿงฎ Variables & Data Types in JavaScript

Variables are the building blocks of any programming language. They store data that your code can use and manipulate.

JavaScript is a dynamically typed language, meaning you donโ€™t need to declare the data type of a variable explicitly โ€” it is determined at runtime.


๐Ÿ“ฆ What is a Variable?

A variable is a container for storing data values.

let message = "Hello, world!";

๐Ÿ› ๏ธ Declaring Variables in JavaScript

JavaScript provides three ways to declare variables:

Keyword Scope Reassignment Hoisting Use Case
var Function-scoped โœ… Yes โœ… Hoisted (initialized as undefined) Legacy code
let Block-scoped โœ… Yes โœ… Hoisted (not initialized) Recommended for variables that change
const Block-scoped โŒ No โœ… Hoisted (not initialized) Recommended for constants

๐Ÿ” Example:

var name = "Ajay";
let age = 23;
const country = "India";

๐Ÿงช JavaScript Data Types

JavaScript has two main categories of types:

๐Ÿ”น 1. Primitive Types

Type Example Description
String "Hello" Textual data
Number 42, 3.14 Integer or floating point numbers
Boolean true, false Logical true or false
Null null Intentionally empty value
Undefined undefined Declared but not assigned
Symbol Symbol("id") Unique and immutable identifier
BigInt 123n Large integers

๐Ÿ”น 2. Non-Primitive (Reference) Types

๐Ÿง  Typeof Example:

console.log(typeof 123);         // "number"
console.log(typeof "JS");        // "string"
console.log(typeof null);        // "object" (quirk in JS)
console.log(typeof undefined);   // "undefined"

๐Ÿ—บ๏ธ Mermaid Diagram โ€“ Variable Declaration Flow

flowchart TD
  A[Declare Variable] --> B[Assign Value]
  B --> C{Which Keyword?}
  C --> D[var]
  C --> E[let]
  C --> F[const]
  D --> G[Function Scope]
  E --> H[Block Scope]
  F --> I[Block Scope, Immutable]

๐Ÿ’ก Best Practices


โ“ Interview Questions & Answers

1. What is the difference between var, let, and const?

2. What are primitive and non-primitive data types?

3. Why is typeof null an object?

Itโ€™s a legacy bug in JavaScriptโ€™s original implementation. Technically, null is a primitive.

4. Can we change the value of a const variable?

No, const variables cannot be reassigned. However, for objects and arrays, their contents can be mutated.

const person = { name: "Ajay" };
person.name = "Dhangar"; // โœ… Allowed
person = { name: "Someone" }; // โŒ Error

5. What does dynamically typed mean in JavaScript?

It means data types are assigned at runtime, and the same variable can hold values of different types during execution.


๐Ÿ”— Reference & Learn More

Visit CodeHarborHub for projects, interactive demos, and more JavaScript practice.


โœ… Summary

๐ŸŽฏ Mastering variables and data types is crucial to writing clean, bug-free JavaScript code.


โญ๏ธ Next Up

Continue your learning in the next section: Operators in JavaScript