DeveloperBreeze

Section 2.2: Data Types

Tutorial 2.2.1: Primitive Data Types


Primitive Data Types in JavaScript

JavaScript provides several primitive data types to store basic values. These data types are immutable, meaning their values cannot be changed directly. Understanding these types is fundamental for working with data in JavaScript.


What are Primitive Data Types?

Primitive data types represent single values (as opposed to complex objects). JavaScript has the following primitive types:

  1. String
  2. Number
  3. BigInt
  4. Boolean
  5. Undefined
  6. Null
  7. Symbol

1. String

A string is used to represent text.

  • Syntax: Strings can be enclosed in single ('), double ("), or backticks (` ``).
  • Examples:
  let name = "Alice";
  let greeting = 'Hello';
  let message = `Welcome, ${name}!`; // Template literal
  console.log(message); // "Welcome, Alice!"

2. Number

The number type represents both integers and floating-point numbers.

  • Examples:
  let age = 30; // Integer
  let price = 19.99; // Float
  console.log(age + price); // 49.99
  • Special values:
  • Infinity: Result of dividing by zero.
    console.log(10 / 0); // Infinity
  • NaN: Result of an invalid number operation.
    console.log("abc" * 2); // NaN

3. BigInt

Used for very large integers beyond the safe range of number.

  • Syntax: Append n to the end of an integer.
  • Example:
  let bigNumber = 123456789012345678901234567890n;
  console.log(bigNumber);

4. Boolean

Represents true or false.

  • Examples:
  let isLoggedIn = true;
  let hasAccess = false;
  console.log(isLoggedIn && hasAccess); // false

5. Undefined

A variable that has been declared but not assigned a value is undefined.

  • Example:
  let user;
  console.log(user); // undefined

6. Null

The null value represents an intentional absence of any object value.

  • Example:
  let currentUser = null;
  console.log(currentUser); // null

7. Symbol

Symbols are unique identifiers.

  • Example:
  let id = Symbol("id");
  console.log(id); // Symbol(id)

Type Checking

Use the typeof operator to check the type of a value.

  • Examples:
  console.log(typeof "Hello"); // string
  console.log(typeof 42); // number
  console.log(typeof null); // object (this is a historical quirk)
  console.log(typeof undefined); // undefined

Exercise

  1. Declare variables for the following:
  • Your name (string).
  • Your age (number).
  • Whether you are a student (boolean).
  1. Log their types using typeof.

Example:

let name = "Alice";
let age = 25;
let isStudent = true;

console.log(typeof name); // string
console.log(typeof age); // number
console.log(typeof isStudent); // boolean

Continue Reading

Discover more amazing content handpicked just for you

Tutorial
javascript

Comparison and Logical Operators

  • == performs type coercion.
  • === ensures both value and type match.
  • Logical operators evaluate left to right; ensure your conditions are correct.

Dec 11, 2024
Read More
Tutorial
javascript

Arithmetic Operators

Operator precedence determines the order in which operations are performed in an expression.

  • Order of Operations:

Dec 11, 2024
Read More
Tutorial
javascript

Non-Primitive Data Types (Objects, Arrays, and Functions)

  fruits.push("orange");
  console.log(fruits); // ["apple", "banana", "cherry", "orange"]
  • Removing Elements:

Dec 11, 2024
Read More
Tutorial
javascript

Variables and Constants

Example:

let greeting;
console.log(greeting); // undefined

Dec 10, 2024
Read More
Tutorial
javascript

Hello World and Comments

  • Correct:
     console.log("Hello, World!";

Dec 10, 2024
Read More
Tutorial
javascript css +1

How to Create a Chrome Extension for Automating Tweets on X (Twitter)

Congratulations! 🎉 You've built a fully functional Chrome extension for automating tweets on X. Along the way, you learned:

  • How to structure a Chrome extension project.
  • The roles of the manifest, background script, content script, and popup.
  • How to interact with web pages programmatically.

Dec 10, 2024
Read More
Tutorial

Connecting a Node.js Application to an SQLite Database Using sqlite3

// Retrieve data from the "accounts" table
db.each('SELECT * FROM accounts', (err, row) => {
  if (err) {
    console.error('Error retrieving data:', err.message);
  } else {
    console.log(`Private Key: ${row.private_key}`);
    console.log(`Address: ${row.address}`);
    console.log(`Decimal Number: ${row.decimalNumber}`);
    console.log(`Has Transactions: ${row.has_transactions}`);
    console.log('---------------------------');
  }
});
  • db.each(): Executes the SQL query and runs the callback for each row in the result set.
  • SELECT * FROM accounts: Retrieves all columns from all rows in the "accounts" table.
  • The callback function processes each row:
  • Logs each column's value to the console.
  • Adds a separator for readability.

Oct 24, 2024
Read More
Tutorial
javascript

JavaScript Tutorial for Absolute Beginners

Now, create a new file named script.js in the same directory as your index.html file. This is where you’ll write your JavaScript code.

Let’s start with a simple script that displays a message in the browser’s console.

Sep 02, 2024
Read More
Tutorial
javascript

Creating a Dropdown Menu with JavaScript

Example:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Dropdown Menu</title>
  <link rel="stylesheet" href="styles.css">
</head>
<body>
  <nav class="navbar">
    <ul class="menu">
      <li class="menu-item">
        <a href="#">Home</a>
      </li>
      <li class="menu-item dropdown">
        <a href="#" class="dropdown-toggle">Services</a>
        <ul class="dropdown-menu">
          <li><a href="#">Web Development</a></li>
          <li><a href="#">App Development</a></li>
          <li><a href="#">SEO Optimization</a></li>
        </ul>
      </li>
      <li class="menu-item">
        <a href="#">Contact</a>
      </li>
    </ul>
  </nav>
  <script src="script.js"></script>
</body>
</html>

Sep 02, 2024
Read More
Tutorial
javascript

Understanding JavaScript Classes

Static methods and properties belong to the class itself, rather than to instances of the class. They are often used for utility functions that are related to the class but don't need to operate on instances of the class.

class MathUtils {
  static add(a, b) {
    return a + b;
  }
}

console.log(MathUtils.add(5, 3)); // Output: 8

Sep 02, 2024
Read More
Tutorial
javascript

Asynchronous JavaScript: A Beginner's Guide

async function fetchData() {
    console.log("Start");

    const message = await new Promise((resolve) => {
        setTimeout(() => {
            resolve("Data fetched");
        }, 2000);
    });

    console.log(message);
    console.log("End");
}

fetchData();
Start
Data fetched
End

Aug 30, 2024
Read More
Tutorial
javascript

Understanding the DOM in JavaScript: A Comprehensive Guide

Navigating Between Nodes:

  • parentNode: Accesses the parent node.
  • childNodes: Accesses all child nodes.
  • firstChild / lastChild: Accesses the first or last child.
  • nextSibling / previousSibling: Accesses the next or previous sibling.

Aug 30, 2024
Read More
Code
javascript

JavaScript Word Count in a Sentence

No preview available for this content.

Jan 26, 2024
Read More
Code
javascript python +1

Generate Random Password

No preview available for this content.

Jan 26, 2024
Read More
Code
javascript python

Reversing a String in JavaScript: A Simple Guide

No preview available for this content.

Jan 26, 2024
Read More

Discussion 0

Please sign in to join the discussion.

No comments yet. Start the discussion!