JavaScript uses variables as containers to store data values and is a dynamically typed language, meaning variable types are determined at runtime. Data is categorized into primitive and non-primitive types.
Variables in JavaScript
Variables are declared using one of three keywords, each with different scoping and reassignment rules:
var: Function-scoped (or globally-scoped) and can be updated and re-declared within the same scope. It is generally recommended to avoidvarin modern JavaScript development in favor ofletandconst.let: Block-scoped and can be updated but not re-declared within the same scope. This is the preferred way to declare variables whose values may change.const: Block-scoped and creates a read-only "constant" that cannot be reassigned after its initial declaration. It must be initialized when declared. Note that while the variable itself cannot be reassigned, the properties of an object or elements of an array assigned to aconstvariable can still be modified.
Naming Rules
- Names must begin with a letter, underscore (
_), or dollar sign ($). - Names cannot begin with a number.
- Names are case-sensitive (
Boyandboyare different variables). - Reserved keywords (like
if,for,let,const) cannot be used as variable names.
Data Types in JavaScript
JavaScript has eight data types, which are divided into two main categories:
Primitive Data Types
These represent single, immutable values.
String: Represents textual data, enclosed in single quotes ('...'), double quotes ("..."), or backticks (`...`).Number: Represents numeric values, including integers and floating-point numbers. It also includes special values likeInfinityandNaN(Not-a-Number).Boolean: Represents a logical entity with only two possible values:trueorfalse.Undefined: A variable that has been declared but not assigned a value automatically has the valueundefined.Null: Represents an intentional absence of any object value. It is a special value that a programmer explicitly assigns.Symbol: A unique and immutable primitive value, often used as an object key to avoid naming conflicts.BigInt: Represents integers of arbitrary precision, larger than the maximum value aNumbercan safely hold.
Non-Primitive Data Type (Reference Type)
The
Object type is the only non-primitive type and is used for more complex data structures. When assigned to a variable, the variable holds a reference to the object's memory location, not the value itself.Object: Collections of key-value pairs used to store structured data. E.g.,let person = { name: "John", age: 30 };.Array: A specialized type of object used to store ordered lists of values, accessed by an index (starting from zero). E.g.,let fruits = ["Apple", "Banana"];.Function: Functions are first-class objects in JavaScript and can be stored in variables, passed as arguments, and returned from other functions.
No comments:
Post a Comment