Value types in JavaScript

Introduction Link to heading

In JavaScript, there are two main types of values: primitive values and object values.

Primitive values Link to heading

  • They are simple and immutable values.
  • They have no properties or methods.
  • The types of primitive values are:
    • Number: Represents numerical values, such as integers or decimals.
    • Text string: Represents a sequence of characters.
    • Boolean: Represents a true or false value.
    • Null: Represents an intentionally empty value.
    • Undefined: Represents a value that has not been defined.

Examples of primitive values Link to heading

40; // Number
"hello world"; // String
true; // Boolean
false; // Boolean
null; // Null
undefined; // Undefined

Object type values: Link to heading

  • They are complex and mutable values.
  • They have properties and methods.
  • The types of object-type values are:
    • Arrays: They are ordered collections of values.
    • Objects: They are collections of properties that can be of different types.

Examples of object type values Link to heading

[1, 2, 3]; // Array
{ name: "john", age: 30 }; // Object

typeof function: Link to heading

The typeof function allows you to get the type of a value.

Example: Link to heading

typeof 40; // "number"
typeof "hello world"; // "string"
typeof true; // "boolean"
typeof null; // "object"
typeof undefined; // "undefined"

In summary Link to heading

  • It is important to understand the different types of values in JavaScript.
  • Primitive values are simple and immutable, while object-type values are complex and mutable.
  • The typeof function allows you to get the type of a value.

Keep learning about value types in JavaScript to improve your programming skills!

Additional Tips: Link to heading

  • Pay attention to the type of value you need for each variable.
  • Use the typeof function to check the type of a value.
  • Note that some values, such as null, are of type “object”.

Example of using different types of values: Link to heading

// Number
const age = 30;

// String
const name = "john";

// Boolean
const isLoggedIn = true;

// Array
const hobbies = ["read", "programming", "travel"];

// Object
const person = {
    nombre: "john",
    edad: 30,
    hobbies: ["read", "programming", "travel"],
};

// function `typeof`
console.log(typeof age); // "number"
console.log(typeof name); // "string"
console.log(typeof isLoggedIn); // "boolean"
console.log(typeof hobbies); // "object"
console.log(typeof person); // "object"

Take advantage of understanding value types to write more efficient and effective JavaScript code!

<< Variables in JavaScript >>