Basics
JS Variables
Declaring JavaScript Variables
JavaScript variables use var, let, or const, preferring let/const for scope.
Introduction to JavaScript Variables
Variables in JavaScript are fundamental to storing and manipulating data. They act as containers for values and are essential for performing operations and controlling logic flow in your code. JavaScript provides three keywords to declare variables: var
, let
, and const
.
Declaring Variables with var
var is the oldest way to declare a variable in JavaScript. Variables declared with var
are function-scoped, meaning they are accessible within the function they are declared in or globally if declared outside of any function. However, var
has some issues with block-level scope which can lead to unexpected behavior.
Using let for Block Scope
let was introduced in ES6 (ECMAScript 2015) to address the shortcomings of var
. Variables declared with let
are block-scoped, meaning they are only accessible within the block they are declared in, such as within a pair of curly braces { }
.
Defining Constants with const
const is also block-scoped like let
, but it is used to declare constants, or variables whose value should not change once assigned. Attempting to reassign a const
variable will result in a TypeError. However, if the const
variable is an object or array, its properties or elements can still be modified.
Choosing Between var, let, and const
In modern JavaScript development, it is recommended to use let
and const
instead of var
. Use let
when you expect the variable to change over time, and use const
when you want to ensure that the variable should not be reassigned after its initial value is set. This helps in maintaining better code clarity and reduces the risk of runtime errors.
Basics
- Introduction
- Where To
- Output
- Syntax
- Comments
- Variables
- Scope
- Hoisting
- Errors
- Data Types
- Operators
- Ternary Operator
- Short-Circuit Evaluation
- If Else
- Switch
- Loops
- For...Of/For...In
- Functions
- this Keyword
- Objects
- Arrays
- Strings
- Template Literals
- Numbers
- Number Properties
- Dates
- Math
- Booleans
- Type Conversion
- Destructuring
- Spread/Rest
- RegExp
- Strict Mode
- Modules
- Security Basics
- Debugging
- Best Practices
- Mistakes
- Performance
- Reserved Words
- Sets
- Maps
- Bitwise
- Array Const