14. Can you explain the different data types available in JavaScript and their characteristics?
In JavaScript, there are several built-in data types, including:
- Undefined: Represents a variable that has not yet been assigned a value.
- Null: Represents a deliberate absence of any object value, but is still considered a data type.
- Boolean: Represents a logical true or false value.
- Number: Represents a floating-point or integer value.
- String: Represents a sequence of characters enclosed in quotation marks.
- Object: Represents any object or data structure that is not a primitive type.
- Array: Represents an ordered collection of values.
- Function: Represents a block of code that can be executed.
Here's a brief overview of each data type:
- Undefined: An undefined variable has no value and is often used to indicate that a variable has not yet been assigned a value. It can be checked using the
typeof
operator, like this: typeof x; // undefined
.
Null: Null is used to represent a deliberate absence of any object value. It can also be checked using the typeof
operator: typeof null; // object
String: Strings are sequences of characters enclosed in quotation marks. They can be created using literal string syntax or template literals. Object: An object is a collection of properties and methods that represent data or functionality. There are several ways to create objects in JavaScript, including using object literal syntax and constructor functions. // Using object literal syntax
const person = {
name: "John",
age: 30,
isStudent: false
};
console.log(person); // Output: { name: 'John', age: 30, isStudent: false }
// Using a constructor function
function Person(name, age, isStudent) {
this.name = name;
this.age = age;
this.isStudent = isStudent;
}
const john = new Person("John", 30, true);
console.log(john); // Output: { name: 'John', age: 30, isStudent: true }