DEV Community

Hiral
Hiral

Posted on

Understanding Variables and Data Types in JavaScript

Think of variables as box that stores information,so it you multiple box then you need to label the box to understand what is stored inside.

In programming varibale stores data and vairable name is label

let name = "John";
Enter fullscreen mode Exit fullscreen mode

Here name is label and John is value

How to declare varaibles

we can use let,var & const to declare variable

let age = 25;
const country = "USA"
var isStudent=true
Enter fullscreen mode Exit fullscreen mode

Primitives data type

  • String
let name = "Alice";
Enter fullscreen mode Exit fullscreen mode
  • number
let age = 20;
Enter fullscreen mode Exit fullscreen mode
  • Boolean
let isStudent = true;
Enter fullscreen mode Exit fullscreen mode
  • null
let middleName = null;
Enter fullscreen mode Exit fullscreen mode
  • undefined
let score;
Enter fullscreen mode Exit fullscreen mode

When to user var,let & const:
var : declares function-scoped or globally-scoped variables
let : declares a block-scoped variable
const: declares a block-scoped variable, assigning a value that cannot be re-assigned.

What is block-scopewhere
Scope means where your variable is used.

Think of variable as scope in your room:

  • if you put your box in living room everyone can see it
  • if you put your box in your bedroom only you can see it
{
  let message = "Hello";
  console.log(message); // ✅ Works here
}

console.log(message); // ❌ Error (not accessible outside)
Enter fullscreen mode Exit fullscreen mode

Declare Variables

let name = "Emma";
let age = 22;
let isStudent = true;
Enter fullscreen mode Exit fullscreen mode

Try Changing

age = 23; // ✅ Allowed
isStudent = false; // ✅ Allowed
Enter fullscreen mode Exit fullscreen mode

Now try with const:

const country = "Canada";
country = "USA"; // ❌ What happens?
Enter fullscreen mode Exit fullscreen mode

Scope Visulization

Global Scope
  ├── name
  ├── age
  └── Block Scope
        └── message
Enter fullscreen mode Exit fullscreen mode

Top comments (0)