🧠 JavaScript Basics – Data Types, Variables, Constants & Type Conversion

JavaScript is a flexible and dynamic scripting language used in web development. To work effectively with JavaScript, it's important to understand its basic building blocks: data types, variables, constants, and how to convert between data types. 🧱


🔢 JavaScript Data Types

JavaScript supports a variety of data types, broadly categorized into primitive and non-primitive types.

✅ Primitive Data Types:

  • Number: Represents both integers and floating-point numbers. e.g., 42, 3.14
  • String: Represents text enclosed in quotes. e.g., "Hello", 'World'
  • Boolean: Represents logical values: true or false
  • Undefined: A variable that has been declared but not assigned a value
  • Null: Represents an intentional absence of value
  • Symbol: A unique and immutable primitive value (used for unique identifiers)
  • BigInt: For working with very large integers

📦 Non-Primitive Data Types:

  • Object: A collection of properties. e.g., { name: "John", age: 30 }
  • Array: A special type of object for storing ordered collections. e.g., [1, 2, 3]

📌 Variables in JavaScript

Variables are used to store data values. In JavaScript, you can declare variables using var, let, or const.

✨ let and var

  • let is block-scoped and is recommended for modern code.
  • var is function-scoped and considered outdated.

🔒 const

Used to declare constants, which cannot be reassigned after being set.

let name = "Alice";
const pi = 3.14;
var age = 25;

🔄 Type Conversion in JavaScript

JavaScript is dynamically typed, so variables can hold any type of data. Sometimes, you need to convert one type to another.

📤 Implicit Type Conversion (Type Coercion):

JavaScript automatically converts types when necessary.

console.log("5" + 2); // "52" (number 2 is converted to string)
console.log("5" - 2); // 3 (string "5" is converted to number)

📥 Explicit Type Conversion:

Use built-in functions to convert data types.

  • Number("123") ➝ Converts string to number
  • String(123) ➝ Converts number to string
  • Boolean(1) ➝ Converts number to boolean (true)
let str = "456";
let num = Number(str); // num becomes 456

let n = 123;
let s = String(n); // s becomes "123"

📌 Summary

  • JavaScript supports various data types including numbers, strings, booleans, and objects. 🧩
  • Use let, const, or var to declare variables and constants. 🧾
  • Understand implicit and explicit type conversions to avoid bugs. 🛠️

Mastering these basics will help you build powerful, dynamic web applications using JavaScript. 🚀