๐ง 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
orfalse
- 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 numberString(123)
โ Converts number to stringBoolean(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
, orvar
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. ๐