A variable is a placeholder that stores some data or information. In programming, variables are used all the time to store and manipulate data. JavaScript variables are pretty easy because you don't have to worry about types. You can assign variables the same way in JavaScript regardless of the data type.
var
keyword, followed by the variable name. To assign a value to a variable, use the equal sign =
. The syntax for declaring and assigning a variable looks like this:var myVariable = "value";
Note that the value can be of any data type. Once a variable is declared and assigned, it can be used anywhere else in the code.
JavaScript variables can hold different types of data, such as strings, numbers, arrays, and objects. Data types are not explicitly declared in JavaScript, and variables can hold any type of data. Here are some examples:
var myName = "Chris";
var myFavNum = 24;
A Boolean variable can have one of two values: true or false. This type of variable is useful when you need to check if something is true or false, such as whether an app has started or a counter has started.
To declare a Boolean variable, use thevar
keyword followed by the variable name and either true or false. For example:var isAppStarted = true;
var counterStarted = false;
var myArray = [1, "two", 3];
var myObject = {
name: "Chris",
age: 34
};
var
keyword followed by the variable name and null
. For example:var myVariable = null;
var
keyword followed by the variable name without assigning a value. For example:var myVariable;
=
.
=
.var myName = "Chris";
myName = "Bob";
In addition, JavaScript can convert data types automatically, also known as coercion. For example, if you concatenate a string and a number, JavaScript will convert the number to a string.
var myString = "Hello";
var myNum = 1;
var myStringNum = myString + myNum;
// Output: "Hello1"
In JavaScript, variables can have different scopes. A variable's scope determines where the variable can be accessed in your code.
A variable declared outside of a function has global scope. This means it can be accessed from anywhere in your code, including inside functions.
For example:
var myName = "Bob";
function sayName() {
console.log(myName);
}
sayName(); // Outputs "Bob"
A variable declared inside a function has local scope. This means it can only be accessed within that function.
For example:
function sayName() {
var myName = "Bob";
console.log(myName);
}
sayName(); // Outputs "Bob"
console.log(myName); // Throws an error because myName is not defined
It's important to note that it is not a good practice to re-declare variables with the same name. This can lead to confusion and errors in your code.
There are several keywords in JavaScript that are reserved and cannot be used as variable names. These include:
class
const
let
var
true
false
null
undefined
If you try to declare a variable with one of these reserved keywords, your code will throw an error.
In JavaScript, variable names can only contain letters, numbers, underscores, and dollar signs. Variable names cannot start with a number, and they cannot be a reserved keyword.
For example, the following variable names are valid:
var myName = "Bob";
var _myName = "Bob";
var $myName = "Bob";
var myName123 = "Bob";
And the following variable names are invalid:
var 123myName = "Bob"; // Invalid: cannot start with a number
var class = "Bob"; // Invalid: reserved keyword
In ES5 and earlier versions of JavaScript, variables are function-scoped. This means that no matter where you declare your variable inside your function, you always have access to that variable even if you shouldn't. This can cause headaches down the road, especially if you have a complicated function with nested if statements or accidentally reassign the variable.
var
to declare the variable:function sayHi() {
var shouldSayHi = true;
if (shouldSayHi) {
var myName = 'Chris';
console.log('Hi ' + myName);
}
console.log('This should be out of scope: ' + myName);
}
sayHi();
myName
outside of the if statement, it still works even though it shouldn't. This is because variables declared with var
are function-scoped.let
and const
. let
is similar to var
but is block-scoped, meaning that the variable is only accessible within the block it is declared in. Let's rewrite the above function using let
:function sayHi() {
let shouldSayHi = true;
if (shouldSayHi) {
let myName = 'Chris';
console.log('Hi ' + myName);
}
console.log('This should be out of scope: ' + myName);
}
sayHi();
myName
is out of scope. This is because we declared myName
with let
, which is block-scoped.const
is similar to let
in that it is also block-scoped. However, it cannot be reassigned once it is declared. This makes it useful for storing data that you don't ever want to reassign. Here's an example of using const
:const myName = 'Chris';
console.log('My name is ' + myName);
myName = 'Bob'; // This will throw an error
myName
, it will throw an error because it is a constant.const
variables cannot be reassigned, the data inside a const
variable can be mutated. This means that we can modify the properties of an object or the elements in an array that is stored in a const
variable. This is because the variable is pointing to the memory location of the data structure, rather than the data structure itself.Let's take a look at an example:
const myArray = [1, 2, 3];
myArray.push(4);
console.log(myArray); // Output: [1, 2, 3, 4]
const myObject = { name: "Chris" };
myObject.name = "Bob";
console.log(myObject); // Output: { name: "Bob" }
const
variable, we cannot reassign the variable to a new value. This is because const
variables are assigned to a fixed memory location, which cannot be changed.However, it's important to exercise caution when using const
variables, especially with complex data structures such as objects and arrays. Modifying the properties of an object or elements in an array can lead to unexpected behavior if not done carefully.For example, consider the following code:
const person = { name: 'John', age: 30 };
person.age = 31;
console.log(person); // Output: { name: 'John', age: 31 }
const
variable person
and initialize it with an object containing name
and age
properties. We then modify the age
property of the object to 31
. This works because we are not reassigning the person
variable, but rather modifying the data structure it points to.However, if we try to reassign the person
variable to a new object, it will throw an error:const person = { name: 'John', age: 30 };
person = { name: 'Jane', age: 25 }; // Error: Assignment to constant variable.
person
variable to a new object. Since person
is a const
variable, we cannot do this and it will throw an error.In general, it is good practice to use const
for variables that should not be reassigned, and let
for variables that may need to be reassigned. By following this convention, we can write more maintainable and less error-prone code.