What is variable?
A variable is a container for storing data. It holds values that can be used and changed in your program.
Ways to declare Variables?
JavaScript has 3 keywords
- var
- let
- const
Var = old way, function scoped, can be redeclared, can be updated, hoisted (value is undefined)
let = modern way, blocked scoped, cannot be redeclared, can be updated, hoisted (TDZ)
const = modern way, blocked scoped, cannot be updated, cannot be redeclared, hoisted (TDZ)
Scope types?
- 1. Global = Declard outside all blocks
- 2. Function = var is a function scope
- 3. Block Scope = variables inside {} blocks
What is hoisting?
JavaScript moves declaration to the top is called hoisting.
var is undefined
let & const hoisted in TDZ
What is Initialization?
Giving value to a variable
let x = 10;
What is declaration?
Creating a variable without value
let x;
What is Reassign/ Updating value?
let age = 20;
age = 21;
What is redeclaration?
var names = ‘deepak’;
var names = ‘durgesh’;
var is allowed
let cannot allowed
const also not allowed
Naming rules?
Names can contain letters, digits, underscores, and dollar signs.
Names must begin with a letter, a $ sign or an underscore (_).
Cannot use keywords
Naming conventions?
UPPERCASE
camelCase(Recommend)
Data types stored in variables?
- String
- Number
- Boolean
- Null
- Undefined
- Bigint
- Symbol
- Object
- Array
- Function
JavaScript is dynamic typing?
Yes, JavaScript is a dynamically typed language.
let x = 10;
x = ‘hello’;
It means that same variable hold different value during run time.
Memory concept
When you create a variable:
1. JavaScript create Memory
2. Gives it a name
3. Stores value
const with objects
const user = {name: ‘deepak’};
user.name = ‘rahul’;
user = {} not allowed❌
const with array
const arr = [1, 2];
arr.push(3);✔️
arr = []; ❌
Variables Shadowing
Inner block variables with same name overrides outer variable.
let a = 10;
{
let a = 20; // Shadowing // a = 20
}
Global variable
To many global variables is not a good practice❌
Use limited global scope✔️
Strict Mode
Enables strict mode:
‘use strict’
Prevents creating accidental global variables
Good practices
1. Use const by default✔️
2. Use let only if value changes✔️
3. Avoid var❌
4. Use descriptive names✔️
Variable types
1. Mutable => changeable (let)
2. Immutable => that cannot be change (const)
Types of operator
check variable type
typeof ‘deepak’ // string
typeof 10 // number
typeof true // boolean
typeof undefined // undefined
undefined vs null
undefined => variable declare but no value
null => Intentionally empty value
Variable declaration best pattern
Always declare at top is the best practice.
Default value
If not given, value becomes undefined
Lifetime of variable
Global => entire program
Function scope => till function runs
Block => till block ends
Variables in loops
only let blocks each loop separately
Temporal Dead Zone Example
consle.log(a);
let a = 10;
Garbage collection
JavaScript removes data automatically for you