Data Types - Exercise 2
The symbol data type in JavaScript represents a unique identifier. Symbols are immutable and unique. Two symbols with the same description are still different values.
const firstId = Symbol("id");
const secondId = Symbol("id");
console.log(firstId === secondId); // false
In JavaScript, you can declare a symbol variable using the Symbol() function. Its optional description is useful when inspecting the value.
const userId = Symbol("userId");
console.log(typeof userId); // "symbol"
var sym = Symbol();
The object data type in JavaScript represents a collection of properties, where each property has a key and a value. Properties may hold any data type, and methods are functions stored as values.
const user = { name: "Ada", active: true };
console.log(user.name);
In JavaScript, you can declare an object variable using curly braces {}.
var person = { name: 'John', age: 30 };
The typeof operator is used to
determine the data type of a value or an expression in
JavaScript. It is useful for simple runtime checks, but
arrays also report "object", so use
Array.isArray when that distinction matters.
console.log(typeof 42); // "number"
console.log(typeof "42"); // "string"
console.log(typeof []); // "object"
Type coercion in JavaScript refers to the automatic conversion of data types during the evaluation of expressions. For example, the plus operator can convert a number to a string when the other operand is a string.
console.log("2" + 3); // "23"
console.log("2" * 3); // 6
Implicit type coercion in JavaScript occurs when the data type of a value is automatically converted during the evaluation of an expression.
Explicit type coercion in JavaScript occurs when the data type of a value is manually converted using built-in functions or operators.
The == operator in JavaScript performs type coercion, while the === operator does not perform type coercion and checks both value and type.
You can convert a string to a number in JavaScript using the parseInt() or parseFloat() functions.