Variables are containers that hold values of different types, such as numbers, strings (or text), or boolean values (logical values of
false). You can think of them as named locations for storing data. For example,
x = 10 where
x is a variable and it stores the value
10 currently. These values can be used and manipulated throughout your code, making it more flexible and dynamic.
const keywords. Each of these keywords has a different scope and behavior, which we'll explore in more detail later in this post.
To declare a variable, you simply need to use one of the keywords (
const) followed by the variable name. For example, to declare a variable named
age, you can use the following code:
Once you've declared a variable, you can assign a value to it using the
= operator. For example, to assign the value
30 to the
age variable, you can use the following code:
age = 30;
You can also assign a value to a variable at the time of declaration, like this:
var name = "John";
You can even use a variable to assign value to another variable.
var greeting = "Hello World!"; var hello = greeting;
Similarly, you can also use the
let keyword to create variable. For example:
let age = "30"; let name; name = "John";
let x, y; let a, b = 4, 6; x, y = true, true;
There's a slight difference between the scopes of the variables created by
let. However, we'll cover that in a future post. For now, you can assume that you can use them interchangeably.
Sometimes you may have a value that you don't want to change throughout your code. That's where constants come in.
const keyword followed by the variable name and the initial value:
const pi = 3.14;
In this example,
pi is a constant that is initialized with the value
3.14. You must always assign a value at the time of declaring a constant. Once
pi is defined, you cannot change its value.
pi = 3; // Uncaught TypeError: Assignment to constant variable. const x; // Uncaught SyntaxError: Missing initializer in const declaration
Constants are useful for storing values that should not be changed throughout your code, such as mathematical constants like pi, or configuration values like URLs and API keys.
constfor values that should not change throughout your code, and use
varfor values that can change.
camelCasefor variable names. This means that the first word is lowercase and subsequent words are capitalized. For example,
I hope you found this post helpful!