JavaScript is a dynamically typed language, meaning variables are not bound to a specific data type. Instead, they can hold values of various types. Here's an explanation of JavaScript data types with examples:
1. Primitive Data Types
a. Number
Represents both integers and floating-point numbers.
Example:
let age = 30; // integer
let temperature = 98.6; // floating-point number
b. String
Represents text enclosed in single or double quotes.
Example:
let name = 'John Doe';
let message = "Welcome to JavaScript!";
c. Boolean
Example:
let isLogged = true;
let isExpired = false;
d. Undefined
Represents a variable that has been declared but not assigned a value.
Example:
let x;
console.log(x); // Outputs: undefined
e. Null
Represents an intentional absence of any value.
Example:
let score = null;
f. Symbol
Introduced in ES6, represents a unique and immutable data type.
Example:
const KEY = Symbol('unique key');
2. Complex Data Types
These are also known as reference types and can hold collections of data or complex entities:
a. Object
Represents a collection of key-value pairs where the keys are strings.
Example:
let person = {
name: 'Alice',
age: 25,
isAdmin: false
};
b. Array
Represents a list-like object of elements.
Example:
et colors = ['red', 'green', 'blue'];
c. Function
Represents a reusable block of code.
Example:
function greet(name) {
console.log(`Hello, ${name}!`);
}
3. Data Type Checking
JavaScript provides operators and methods for checking the data type of a variable:
a. typeof Operator
Returns a string indicating the type of a variable.
Example:
console.log(typeof 'hello'); // Outputs: "string"
console.log(typeof true); // Outputs: "boolean"
b. instanceof Operator
Checks whether an object is an instance of a specific object type.
Example:
let fruits = ['apple', 'banana', 'orange'];
console.log(fruits instanceof Array); // Outputs: true
4. Type Coercion
JavaScript performs implicit type coercion, converting values between types during operations:
a. String Concatenation
Numbers are coerced into strings when concatenated with strings.
Example:
let num = 42;
let str = 'The answer is ' + num; // Result: "The answer is 42"
b. Numeric Operations
Strings containing numeric characters are coerced into numbers during arithmetic operations.
Example:
let total = '10' - 5; // Result: 5 (string "10" coerced into number)
5. NaN and Infinity
JavaScript has special values for representing "not a number" (NaN) and infinity:
a. NaN (Not a Number)
Represents an invalid or unrepresentable value resulting from arithmetic operations.
Example:
console.log(0 / 0); // Outputs: NaN
b. Infinity
Represents positive infinity.
Example:
console.log(1 / 0); // Outputs: Infinity
JavaScript supports various data types, including primitive types like numbers, strings, booleans, and reference types like objects, arrays, and functions.
Practice Excercise Practice now