Js 3
Js 3
1.
Declaration:
2.
1. Variables in JavaScript can be declared using the keywords var, let, or const.
2. The way you declare a variable affects its scope, reassignability, and behavior.
3.
Initialization:
4.
5.
Naming Rules:
6.
1. Variable names must start with a letter, underscore (_), or dollar sign ($).
2. The rest of the name can contain letters, digits, underscores, or dollar signs.
3. JavaScript variable names are case-sensitive, so myVariable and myvariable
would be considered different.
1.
var:
2.
3.
let:
4.
1. let was introduced in ES6 (ECMAScript 2015) and is the preferred way to declare
variables that can change (mutable).
2. It has block scope, which means it is limited to the block of code (e.g., within {}) in
which it is declared.
3. Unlike var, let does not allow access to the variable before its declaration (no
hoisting of initialization).
5.
const:
6.
1. const is used to declare constants, which are variables that cannot be reassigned
after their initial value is set.
2. Like let, const has block scope.
3. It is used when you want to make sure that a variable's value remains constant
throughout the program.
4. However, if the const variable holds an object or an array, the properties or
elements within that object or array can still be modified.
Scope of Variables
1.
Global Scope:
2.
3.
Function Scope:
4.
1. Variables declared with var inside a function have a function scope, meaning they
can only be accessed within that function.
5.
Block Scope:
6.
1. Variables declared with let or const have block scope, which limits their
accessibility to the block in which they are defined.
2. Block scope helps prevent accidental changes to variables from outside the
intended code block.
Hoisting
Hoisting is a JavaScript mechanism where variable declarations are moved to the top of their
scope before code execution.
Only the declarations are hoisted, not the initializations.
Variables declared with var are hoisted, but those declared with let and const are not
fully hoisted and remain in a "temporal dead zone" until the line where they are declared.
Mutability
Mutable Variables: Variables declared with let or var can be reassigned new values.
Immutable Variables: Variables declared with const cannot be reassigned to a different
value.
1. Use const by default: This makes your intentions clear that the variable should not be
reassigned, providing more predictable code.
2. Use let when reassignment is needed: If you know the value of a variable will change, use
let.
3. Avoid using var: Due to its lack of block scope and the potential for unintentional bugs, it is
generally better to avoid using var in modern JavaScript.