๐Ÿง  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. ๐Ÿš€