JavaScript(JS) Variables
In JavaScript, variables are used to store data that can be used throughout a program. A variable is a named container that holds a value. You can think of a variable as a box that has a label on it and that contains a value.
To declare a variable in JavaScript, you use the var
, let
, or const
keyword, followed by the name of the variable, and optionally, an initial value. Here's an example:
var message = "Hello, world!"; let count = 42; const PI = 3.14159;Source:www.theitroad.com
In this example, we've declared three variables:
message
is a variable of type string that has an initial value of "Hello, world!"count
is a variable of type number that has an initial value of 42.PI
is a constant that has a value of 3.14159. Constants cannot be changed once they are initialized.
You can also declare a variable without initializing it:
let name;
In this example, we've declared a variable called name
without giving it an initial value. If you try to use this variable before giving it a value, you'll get an undefined
error.
You can assign a new value to a variable at any time by using the assignment operator (=
):
count = 10;
In this example, we've assigned a new value of 10 to the count
variable.
JavaScript is a dynamically typed language, which means that you don't have to specify the data type of a variable when you declare it. The data type of a variable is determined dynamically based on the type of the value that is assigned to it.