002_Javascript-Variables
A variable is a "named storage" location for data.
1.Creating a variable in JS (Declaring a variable).
let myVariable;
2.Use assignment operator ( = ) to store data into the variable.
myVariable = 5;
Now the value 5 is stored in variable "myVariable", we can access it using the variable name.
3.Accessing value stored in Variable.
console.log(myVariable);
We could combine the variable declaration and assignment into a single line as well.
let message = "Hello";
// also
let var1=5, var2="string", var3="second string";
Variable Naming
Rules for variable names in JS:
- Must contain only letters, digits or symbols $ and _ (underscore).
- First character must not be a digit.
// valid variable names let userName; let test_123;
Note: Case matters (apple and Apple are two different variables).
Keywords
Keywords are the reserved words that cannot be used as a variable name because they are used by the language itself. Example: let, class, return etc.
Usually, we need to define a variable before using it. But in earlier versions of JS it was possible to declare a variable by just assigning a value to it. But if we put "use strict" it would cause an error.
num = 5; // works
"use strict"
num2 = 10; // throws an error ( num2 is not defined)
Constants
The value of a variable could be changed at any point, but in the case of constants once declared they cannot be reassigned. Any attempt to do so would cause an error. To declare a constant variable we use "const" instead of "let".
const myConstant = 100;
Naming Practices
- When the name contains multiple words, camelCase is commonly used.
- Constants are named using capital letters and underscores.
- Use human-readable name.