Variables in JavaScript are containers used to store data values. Unlike other programming languages like Java or C, JavaScript is a dynamically-typed language, meaning you don't need to declare a variable's data type explicitly. Here's an overview of variables in JavaScript:
Variable Declaration:
var
, let
, or const
keywords.javascriptvar name = "John"; // Using var (old way)
let age = 30; // Using let (preferred for block-scoped variables)
const PI = 3.14; // Using const (immutable constant)
Variable Naming Rules:
javascriptvar firstName = "John"; // Valid variable name
var 1stName = "John"; // Invalid variable name (cannot start with a digit)
Var, Let, and Const:
var
: Declares a variable globally or locally to an entire function regardless of block scope. It's considered outdated and is mostly replaced by let
and const
.let
: Declares a block-scoped variable. It's preferred over var
for declaring variables with block scope.const
: Declares a block-scoped variable that cannot be reassigned. It's used for defining constants.Assigning Values:
=
. JavaScript is dynamically typed, so you don't need to specify the data type when declaring a variable.javascriptvar age = 30; // Assigning a number
var name = "John"; // Assigning a string
Updating Variables:
javascriptvar count = 10;
count = count + 1; // Incrementing the value of count by 1
Thanks for learning