DEV Community

Veera Ganapathi
Veera Ganapathi

Posted on

JavaScript Basics: Variables and Data Types

What is Variables ?

JavaScript variables are containers for data. JavaScript variables can be declared in 3 ways:

  1. Using let(Modern JavaScript)
  2. Using const(Modern JavaScript)
  3. Using var (Not Recommended)

1.Let:
The let keyword is introduced in ES6(Version), has block scope and cannot be re-declared in the same scope.

let  n= 10;
n = 20; // Value can be updated
// let n = 15; //can not redeclare
console.log(n)
Enter fullscreen mode Exit fullscreen mode

2. const

The const keyword declares variables that cannot be reassigned. It's block-scoped as well.

const n = 100;
// n = 200; This will throw an error
console.log(n)
Enter fullscreen mode Exit fullscreen mode

3.var
The var keyword is used to declare a variable. It has a function-scoped or globally-scoped behaviour.

var n = 5;
console.log(n);

var n = 20; // reassigning is allowed
console.log(n);
Enter fullscreen mode Exit fullscreen mode

What is Data Type ?

A data type defines the type of value that a variable can store. JavaScript supports various datatypes, which can be broadly categorized into primitive and non-primitive types.

Primitive Data Types:

They can hold a single simple value. String, Number, BigInt, Boolean, undefined, null, and Symbol are primitive data types.

1. Number: Represents numeric values (integers and decimals).

let n = 42;
let pi = 3.14;
Enter fullscreen mode Exit fullscreen mode

2. String: Represents text enclosed in single or double quotes.

let s = "Hello World!";
let a = 'Hello World!';
Enter fullscreen mode Exit fullscreen mode

3. Boolean: Represents a logical value (true or false).

let bool= true;
Enter fullscreen mode Exit fullscreen mode

4. Undefined: A variable that has been declared but not assigned a value.

let notAssigned;
console.log(notAssigned);
Enter fullscreen mode Exit fullscreen mode

5. Null: Represents an intentional absence of any value.

let empty = null;
Enter fullscreen mode Exit fullscreen mode

6. Symbol: Represents unique and immutable values, often used as object keys.

let sym = Symbol('unique');
Enter fullscreen mode Exit fullscreen mode

7. BigInt: A number representing a large integer

let bigNumber = 123456789012345678901234567890n;
Enter fullscreen mode Exit fullscreen mode

Importance of Data Types in JavaScript

Data types are used to identify the type of value stored in a variable. They help JavaScript store, process, and manipulate data correctly.

Top comments (0)