How do you use data types in JavaScript with an example?

In JavaScript, data types are essential for defining the kind of data that can be stored and manipulated within a program. JavaScript supports several data types, each serving different purposes. The primary data types in JavaScript include:

  • String: A sequence of characters used for text.
  • Number: Represents both integer and floating-point numbers.
  • Boolean: Holds either true or false values.
  • Object: A collection of properties and values.
  • Array: A special type of object used to store ordered collections.
  • Undefined: Indicates a variable that has been declared but has not yet been assigned a value.
  • Null: Represents a deliberate non-value or empty variable.

Here’s a simple example demonstrating various data types in JavaScript:

// Example of different data types in JavaScript let name = "John Doe"; // String let age = 25; // Number let isEmployed = true; // Boolean let address = { // Object street: "123 Main St", city: "Anytown" }; let hobbies = ["reading", "traveling", "swimming"]; // Array let notDefined; // Undefined let emptyValue = null; // Null console.log(name); // Output: John Doe console.log(age); // Output: 25 console.log(isEmployed); // Output: true console.log(address); // Output: { street: '123 Main St', city: 'Anytown' } console.log(hobbies); // Output: [ 'reading', 'traveling', 'swimming' ] console.log(notDefined); // Output: undefined console.log(emptyValue); // Output: null

JavaScript data types programming