Learn JavaScript Data Types | JavaScript Data Types Deep Dive: Learn Primitives and References Data Types in JS
When we create variables in JavaScript, each one has a type. These types fall into two main groups: primitive types and reference types. The main difference between them is how they are stored and accessed in memory.
- Primitive Types - Stored directly in the location that the variable is accessed.
- Reference Types (Objects) - Accessed by reference.
Primitive Data Types In JavaScript
There are 7 primitive data types in JavaScript:
- String - A sequence of characters, written with single or double quotes.
- Number - Represents both whole numbers and decimals.
- Boolean - Represents true or false values.
- Null - Represents an intentional absence of any object value.
- Undefined - A variable without a value is considered undefined.
- Symbol - A unique identifier.
- BigInt - Used for numbers larger than what the regular
Number
type can handle.
Example Code
const city = 'Tokyo'; // String
const height = 180; // Number
const isStudent = false; // Boolean
const officeRoom = null; // Null
let age; // Undefined
const uniqueKey = Symbol('uniqueKey'); // Symbol
const largeValue = 987654321123456789n; // BigInt
Dynamic vs Static Types
JavaScript is a dynamically-typed language. This means that we don’t have to set the type of variable—it’s set automatically based on the value. For example, a variable might be a string, but you can change it to a number later.
Some other languages, like Java, are statically-typed, where you must set the type of a variable when creating it. TypeScript, an extension of JavaScript, also allows you to set types like this:
const salary: number = 50000;
This makes code more secure but also requires more effort.
Using the typeof
Operator In JavaScript
To check a variable’s type, you can use the typeof
operator:
console.log(typeof city); // Output: 'string'
Note: typeof
returns object
for null
due to an early design error in JavaScript.
Reference Data Types (Objects)
In JavaScript, reference types include arrays, objects, and functions. These types are stored by reference, meaning the variable holds a reference to the location in memory, not the actual value.
Arrays In JavaScript
Arrays are lists of values, for example:
const grades = [90, 85, 92];
Objects In JavaScript
Objects contain data with key-value pairs:
const vehicle = {
type: 'car',
color: 'blue'
};
Functions In JavaScript
Functions are blocks of code that perform a specific task:
const greet = function() {
return 'Hello, World!';
};
greet(); // Outputs: 'Hello, World!'
Note: In JavaScript, functions are also considered objects, but they have the special ability to be called or invoked.
0 Response to JavaScript Data Types Deep Dive: Learn Primitives and References Data Types in JS | Data Types in Js
Post a Comment