Variables in Js | 02
What are Variables?
Variables are containers for storing data in JavaScript. Variables can be used to store reusable values, such as numbers, strings, arrays, objects, functions, etc. The values of the variables are assigned using the assignment operator (\=).
How to Declare variables?
Variables in JavaScript can be declared in 3 ways by using var, let and const keyword.
Var: The oldest way to declare variables. It has function scope and can be re-declared and updated.
Let: Introduced in ES6 (ECMAScript 2015). It has block scope and can be updated but not re-declared within the same scope.
Const: Also introduced in ES6. It has block scope, and the value it holds cannot be reassigned. However, if the variable holds an object, the properties of the object can still be modified.
const name = "Abhishek"
var age = "18"
let lazy = true
Here, name, age and lazy are the example of variables.
Rules for naming variables?
Must start with a letter, underscore (_), or dollar sign ($).
Cannot start with a number or digit (0-9).
Subsequent characters can also be digits (0-9).
Cannot be reserved words (e.g. for, if, let).
Variables are case sensitive i.e. cat and CAT are two different variables.
Resigning Variables
- Variables declared with
var
orlet
can be reassigned.
let price = 999
price = 799 // Allowed
var age = 18
age = 19 // Allowed
Variables declared with
const
cannot be reassigned. However, objects and arrays declared withconst
can have their contents modified.\const city = "New York"; city = "Los Angeles"; // Error: Assignment to constant variable. const user = { name: "Alice" }; user.name = "Bob"; // Allowed, modifying object property
Best Practices
Prefer
const
for variables that shouldn't change. This makes the code more predictable and easier to debug.Use
let
for variables that will change.Avoid using
var
unless you need its specific behavior (function scope and hoisting).Use meaningful variable names that describe the data they hold.
Follow consistent naming conventions, like camelCase for variable names.
Data types variable can hold?
Note: JavaScript is dynamically typed, meaning variables can hold values of any type and the type can change at runtime.
Common types include:
Number: For both integers and floating-point numbers.
String: For text.
Boolean: For
true
orfalse
.Object: For collections of properties.
Array: For ordered lists of values.
Function: For executable code blocks.
Null: For a variable that explicitly has no value.
Undefined: For variables that are declared but not yet assigned a value.
Symbol: For unique identifiers (introduced in ES6).
let count = 10; // Number
let name = "Alice"; // String
let isActive = true; // Boolean
let user = { name: "Alice", age: 25 }; // Object
let items = [1, 2, 3]; // Array
let greet = function() { console.log("Hello"); }; // Function
let nothing = null; // Null
let notAssigned; // Undefined
let sym = Symbol("unique"); // Symbol