JavaScript(JS) Data Types

JavaScript String

In JavaScript, a string is a sequence of characters that is used to represent text. Strings are typically enclosed in single quotes ('...') or double quotes ("..."). Here are some examples:

const greeting = "Hello, world!";
const name = 'John Doe';
‮w:ecruoS‬ww.theitroad.com

In these examples, we declared two variables (greeting and name) and assigned them string values.

Strings in JavaScript are immutable, which means that once a string is created, its value cannot be changed. However, you can create new strings by concatenating (joining together) existing strings. There are several ways to concatenate strings in JavaScript:

  1. Using the + operator:
const firstName = "John";
const lastName = "Doe";
const fullName = firstName + " " + lastName;
console.log(fullName); // Output: John Doe

In this example, we concatenated the firstName and lastName variables by using the + operator and adding a space between them.

  1. Using template literals (introduced in ES6):
const firstName = "John";
const lastName = "Doe";
const fullName = `${firstName} ${lastName}`;
console.log(fullName); // Output: John Doe

In this example, we used template literals to concatenate the firstName and lastName variables. Template literals are enclosed in backticks (```) and allow you to embed variables and expressions directly in the string by using ${...} syntax.

Strings in JavaScript have several built-in methods that you can use to manipulate them. Some of the most commonly used string methods include toUpperCase(), toLowerCase(), charAt(), substring(), split(), replace(), and trim().

JavaScript Number

In JavaScript, numbers are used to represent numeric data. Numbers in JavaScript can be integers or floating-point numbers. Here are some examples:

const age = 30;
const height = 1.75;

In these examples, we declared two variables (age and height) and assigned them numeric values.

JavaScript supports all the basic arithmetic operators, including addition (+), subtraction (-), multiplication (*), and division (/). Here are some examples:

const x = 10;
const y = 5;

console.log(x + y); // Output: 15
console.log(x - y); // Output: 5
console.log(x * y); // Output: 50
console.log(x / y); // Output: 2

In addition to these basic operators, JavaScript also provides several built-in math functions, such as Math.round(), Math.ceil(), Math.floor(), and Math.random(). Here are some examples:

const num = 3.14159;

console.log(Math.round(num)); // Output: 3
console.log(Math.ceil(num)); // Output: 4
console.log(Math.floor(num)); // Output: 3
console.log(Math.random()); // Output: a random number between 0 and 1

JavaScript also provides some special numeric values, such as Infinity, -Infinity, and NaN (Not a Number). Infinity represents the mathematical concept of infinity, and -Infinity represents negative infinity. NaN is returned when a mathematical operation cannot be performed (such as dividing by zero).

console.log(1 / 0); // Output: Infinity
console.log(-1 / 0); // Output: -Infinity
console.log(0 / 0); // Output: NaN

Numbers in JavaScript can be represented using binary, octal, or hexadecimal notation. Here are some examples:

const binary = 0b1010; // Binary: 10
const octal = 0o777; // Octal: 511
const hex = 0xFF; // Hexadecimal: 255

JavaScript BigInt

JavaScript BigInt is a built-in object introduced in ES2020 that provides a way to represent integers that are larger than the maximum safe integer (2^53-1) that can be represented using the Number type.

A BigInt is created by appending the letter n to the end of an integer literal or by calling the BigInt() constructor function. Here are some examples:

const a = 123456789012345678901234567890n;
const b = BigInt("123456789012345678901234567890");

In these examples, we created two BigInt values (a and b) that represent very large integers.

BigInt values can be used in mathematical operations, just like regular numbers. However, you cannot mix BigInt values and regular numbers in the same operation. Here are some examples:

const x = 123n;
const y = 456n;

console.log(x + y); // Output: 579n
console.log(x - y); // Output: -333n
console.log(x * y); // Output: 56088n
console.log(x / y); // Output: 0n (division of BigInts returns a BigInt rounded towards zero)

BigInt values also support several built-in methods, such as toString(), valueOf(), and toExponential(). Here are some examples:

const num = 123456789012345678901234567890n;

console.log(num.toString()); // Output: "123456789012345678901234567890"
console.log(num.valueOf()); // Output: 123456789012345678901234567890n
console.log(num.toExponential(5)); // Output: "1.23457e+29"

JavaScript Boolean

In JavaScript, the Boolean data type is used to represent a logical value that can be either true or false. Booleans are commonly used in conditional statements and logical expressions. Here are some examples:

const isRaining = true;
const isSunny = false;

if (isRaining) {
  console.log("Bring an umbrella");
} else if (isSunny) {
  console.log("Wear sunscreen");
} else {
  console.log("Enjoy the weather");
}

In this example, we declared two variables (isRaining and isSunny) and assigned them Boolean values. We then used a conditional statement to check whether it is raining or sunny, and printed a message based on the value of the variables.

In addition to true and false, JavaScript also has a concept of "truthy" and "falsy" values. A value is considered "truthy" if it evaluates to true in a Boolean context, and "falsy" otherwise. Here are some examples of falsy values:

  • false
  • 0 (zero)
  • "" (an empty string)
  • null
  • undefined
  • NaN (Not a Number)

All other values are considered "truthy". Here are some examples:

const a = true;
const b = 1;
const c = "hello";

if (a) {
  console.log("a is truthy");
}

if (b) {
  console.log("b is truthy");
}

if (c) {
  console.log("c is truthy");
}

In this example, we declared three variables (a, b, and c) and checked whether they are truthy. Since a, b, and c all have non-falsy values, all three if statements will be executed.

JavaScript undefined

In JavaScript, undefined is a primitive data type that represents a value that is not yet assigned a value. Variables that are declared but not initialized have a value of undefined. For example:

let x;
console.log(x); // Output: undefined

In this example, we declared a variable x but did not initialize it. When we print the value of x, it will be undefined.

undefined is also used as the default return value of functions that do not explicitly return a value. For example:

function add(a, b) {
  const result = a + b;
  // No return statement
}

const sum = add(2, 3);
console.log(sum); // Output: undefined

In this example, we defined a function add that calculates the sum of two numbers, but does not explicitly return a value. When we call the function and assign the result to a variable sum, the value of sum will be undefined.

undefined is a distinct value from null. While undefined represents a value that is not yet assigned a value, null represents a deliberate non-value. In other words, null is used to indicate the absence of a value, while undefined is used to indicate the absence of an assigned value.

JavaScript null

In JavaScript, null is a primitive data type that represents an intentional absence of any object value. It is often used to indicate that a variable or property intentionally does not contain any valid value. For example:

let x = null;
console.log(x); // Output: null

In this example, we assigned the value null to the variable x, indicating that it intentionally does not contain any valid value.

Note that null is distinct from undefined. While undefined is used to indicate a variable or property that has not been initialized, null is used to indicate a variable or property that intentionally does not contain any valid value.

null is often used in conditional statements to check whether a variable or property has a valid value. For example:

let x = null;

if (x === null) {
  console.log("x is null");
} else {
  console.log("x is not null");
}

In this example, we checked whether the value of the variable x is null. Since we assigned the value null to x earlier, the first branch of the if statement will be executed.

JavaScript Symbol

In JavaScript, Symbol is a primitive data type that represents a unique and immutable value. Symbols are often used as keys in objects to avoid naming conflicts with other properties. Here are some examples:

const sym1 = Symbol();
const sym2 = Symbol("description");

const obj = {
  [sym1]: "value 1",
  [sym2]: "value 2"
};

console.log(obj[sym1]); // Output: "value 1"
console.log(obj[sym2]); // Output: "value 2"

In this example, we declared two symbols (sym1 and sym2) and used them as keys in an object. When we access the values of the properties using the symbols as keys, we get the corresponding values.

Symbols are unique and immutable, which means that two symbols with the same description are not equal:

const sym1 = Symbol("description");
const sym2 = Symbol("description");

console.log(sym1 === sym2); // Output: false

In this example, we declared two symbols (sym1 and sym2) with the same description. Despite having the same description, the symbols are not equal because they are distinct values.

Symbols can also be used as method names in objects and classes:

const mySymbol = Symbol();

class MyClass {
  [mySymbol]() {
    console.log("Hello from Symbol method");
  }
}

const obj = new MyClass();
obj[mySymbol](); // Output: "Hello from Symbol method"

In this example, we declared a symbol mySymbol and used it as a method name in a class. When we create an instance of the class and call the method using the symbol as the property name, we get the output "Hello from Symbol method".

JavaScript Object

In JavaScript, an object is a collection of key-value pairs, where the key is a string or symbol (in ECMAScript 6) and the value can be any data type, including other objects. Objects can be created using object literals or using the new keyword with a constructor function.

Here's an example of creating an object using an object literal:

const person = {
  name: "Alice",
  age: 30,
  hobbies: ["reading", "swimming"],
  address: {
    street: "123 Main St",
    city: "Anytown",
    state: "CA",
    zip: "12345"
  }
};

In this example, we created an object person with four properties: name, age, hobbies, and address. The address property is itself an object with four properties: street, city, state, and zip.

We can access properties of an object using either dot notation or bracket notation:

console.log(person.name); // Output: "Alice"
console.log(person["age"]); // Output: 30
console.log(person.address.city); // Output: "Anytown"

In this example, we accessed the name property using dot notation, the age property using bracket notation, and the city property of the address property using dot notation with bracket notation.

We can also add and modify properties of an object:

person.email = "[email protected]"; // Add a new property
person.age = 31; // Modify an existing property

In this example, we added a new property email to the person object and modified the value of the age property.

JavaScript Type

In JavaScript, there are several data types that values can belong to. These include:

  • Primitive types: These are basic data types that are immutable (cannot be changed) and are not objects. There are six primitive types in JavaScript:
    - `string`: represents textual data. - `number`: represents numeric data, including integers and floating-point numbers. - `boolean`: represents a logical value (either `true` or `false`). - `undefined`: represents the value of a variable that has not been assigned a value. - `null`: represents a deliberate non-value or absence of any object value. - `symbol`: represents a unique and immutable value.

    Object types: These are complex data types that can store multiple values and are mutable (can be changed). Objects are created using object literals or using the new keyword with a constructor function.

JavaScript uses dynamic typing, which means that the data type of a value can change at runtime. For example, a variable that initially holds a number value can later be assigned a string value:
let myVariable = 123; // number type
myVariable = "hello"; // string type

JavaScript also provides several built-in functions for converting values between different types. For example, the Number() function can be used to convert a value to a number:

const myString = "123";
const myNumber = Number(myString);
console.log(myNumber); // Output: 123

JavaScript typeof

In JavaScript, the typeof operator is used to determine the data type of a value. It returns a string that indicates the type of the operand. Here are some examples:

console.log(typeof "hello"); // Output: "string"
console.log(typeof 123); // Output: "number"
console.log(typeof true); // Output: "boolean"
console.log(typeof undefined); // Output: "undefined"
console.log(typeof null); // Output: "object"
console.log(typeof {}); // Output: "object"
console.log(typeof []); // Output: "object"
console.log(typeof function(){}); // Output: "function"
console.log(typeof Symbol()); // Output: "symbol"

In this example, we used the typeof operator to determine the type of various values, including a string, number, boolean, undefined, null, object, function, and symbol.

Note that typeof null returns "object", which is a quirk of JavaScript and is considered a historical mistake. It is recommended to use an === comparison with null instead.