var let const use cases

When to use var, let and const.

In JavaScript, the keywords var, let, and const are used for variable declarations, but they have different scoping rules and behaviors. Here's when to use each:

1. var (Function-scoped)

When to use: Historically used in JavaScript, but now it is mostly replaced by let and const.

Scope: var is function-scoped, meaning it is available throughout the function where it is defined.

Hoisting: Variables declared with var are hoisted to the top of their scope, meaning they can be accessed before their declaration but will be undefined.

Re-declaration: You can re-declare a variable with var in the same scope without errors.

Best Practice: Avoid using var in modern JavaScript because it can lead to unexpected behaviors due to hoisting and scope issues.

function example() {

    var x = 10;

    if (true) {

        var x = 20; // Same variable as the one declared earlier

    }

    console.log(x); // 20

}

2. let (Block-scoped)

When to use: Use let when you need to declare a variable that may be reassigned and should only exist within a specific block of code (e.g., inside a loop, if statement).

Scope: let is block-scoped, meaning it is only available within the nearest {} brackets (blocks).

Hoisting: Variables declared with let are hoisted, but they are not initialized until the declaration is encountered in the code. Accessing them before initialization will result in a ReferenceError.

Re-declaration: You cannot re-declare the same variable using let in the same block scope.

Best Practice: Use let when you expect the value of a variable to change.

let x = 10;
if (true) {
    let x = 20; // This x is a separate variable from the outer one
    console.log(x); // 20
}
console.log(x); // 10

3. const (Block-scoped, Immutable reference)

When to use: Use const for variables that should not be reassigned after their initial assignment.

Scope: const is block-scoped, just like let.

Hoisting: Variables declared with const are hoisted, but like let, they are not initialized until their declaration is reached.

JavaScript variables

Re-declaration and Re-assignment: You cannot re-declare or reassign a const variable. However, if the value is an object or array, its properties or elements can be changed (the reference is constant, but the data it points to can be mutated).

Best Practice: Use const by default for variables, especially when the value should remain constant. Only use let if you know the value will change.

const x = 10;
x = 20; // Error: Assignment to constant variable.
const arr = [1, 2, 3];
arr.push(4); // This is allowed, since we're not reassigning the array
console.log(arr); // [1, 2, 3, 4]

Summary:

Use const by default for variables that won’t be reassigned.

Use let if the variable will change over time.

Avoid var in modern JavaScript unless maintaining older code.


Operator in javascript

JavaScript has several other operators that are used to interact with objects, properties, methods, and values, just like the dot (.) operator. Here are some of the most common ones:

1. Bracket Notation [ ]

Bracket notation is an alternative to dot notation for accessing properties and methods of an object.

It is especially useful when the property name is dynamic (e.g., stored in a variable) or when the property name contains special characters that aren't valid in dot notation.

Example:

const person = {
    name: "John",
    age: 30
};

console.log(person["name"]); // Access 'name' property using brackets
console.log(person["age"]); // Access 'age' property using brackets

// Dynamic property access
const prop = "name";
console.log(person[prop]); // Access 'name' using a variable

2. Optional Chaining ?.

The optional chaining operator (?.) allows you to safely access deeply nested properties without worrying about whether an intermediate property is null or undefined. If any part of the chain is null or undefined, it returns undefined instead of throwing an error.

Example:

const user = {
    profile: {
        name: "Alice"
    }
};

console.log(user.profile?.name); // "Alice"
console.log(user.address?.city); // Undefined, no error thrown

3. Nullish Coalescing ??

The nullish coalescing operator (??) is used to provide a default value when the value on the left-hand side is null or undefined. It is different from the || (OR) operator because || also treats false, 0, and "" as falsy values, but ?? only checks for null or undefined.

Example:
let name = null;
let defaultName = "Guest";

console.log(name ?? defaultName); // "Guest", because name is null

4. Spread ...

The spread operator (...) is used to spread out the elements of an array, object properties, or function arguments.

It is useful for copying, merging, and manipulating arrays and objects.
Example (Arrays):

const arr1 = [1, 2, 3];
const arr2 = [...arr1, 4, 5]; // Spread elements of arr1 into arr2
console.log(arr2); // [1, 2, 3, 4, 5]

Example (Objects):

const obj1 = { name: "Alice", age: 25 };
const obj2 = { ...obj1, city: "New York" }; // Spread properties of obj1 into obj2
console.log(obj2); // { name: "Alice", age: 25, city: "New York" }

5. Rest ...

The rest operator (also ...) is used to collect multiple values into an array. It is the inverse of the spread operator, and it is used in function parameters or array destructuring.

Example:

function sum(...numbers) {
    return numbers.reduce((acc, num) => acc + num, 0);
}

console.log(sum(1, 2, 3)); // 6

6. Delete Operator delete

The delete operator is used to remove a property from an object.


Example:

const car = {
    brand: "Toyota",
    model: "Corolla"
};

delete car.model; // Deletes the 'model' property
console.log(car); // { brand: "Toyota" }

7. Typeof Operator typeof

The typeof operator is used to determine the data type of a variable or value.

Example:

let x = 42;
console.log(typeof x); // "number"

let y = "hello";
console.log(typeof y); // "string"

8. Instanceof Operator instanceof

The instanceof operator checks whether an object is an instance of a specific class or constructor function.

Example:
const date = new Date();
console.log(date instanceof Date); // true

console.log([] instanceof Array); // true
console.log({} instanceof Array); // false

9. In Operator in

The in operator checks whether a property exists in an object (including properties in the prototype chain).

Example:
const person = {
    name: "Alice",
    age: 25
};

console.log("name" in person); // true
console.log("city" in person); // false

10. Ternary Operator ? :

The ternary operator is a shorthand for if-else statements and is used for conditional expressions. The syntax is condition ? value_if_true : value_if_false.

Example:
const age = 18;
const canVote = age >= 18 ? "Yes" : "No";
console.log(canVote); // "Yes"

11. Dot (.)

In JavaScript, the dot (.) is used as the member access operator. It allows you to access properties and methods of objects. Here’s a breakdown of why and how it is used:

1. Accessing Object Properties

The dot is used to access the properties of an object. The object can be any value that stores multiple properties, such as an object literal, array, or class instance.

Example:

const person = {
    name: "John",
    age: 30
};

console.log(person.name); // Accessing the 'name' property
console.log(person.age); // Accessing the 'age' property

Here, person.name uses the dot operator to access the value of the name property of the person object.

2. Calling Object Methods

The dot is also used to call methods (functions that belong to an object) of an object.

Example:

const calculator = {
    add: function(a, b) {
        return a + b;
    }
};

console.log(calculator.add(5, 3)); // Calls the 'add' method of the 'calculator' object

Here, calculator.add(5, 3) uses the dot operator to call the add method of the calculator object.

3. Accessing Built-in Methods and Properties

The dot is used to access methods and properties of built-in objects in JavaScript, like Math, String, Array, etc.

Examples:

console.log(Math.PI); // Accessing the 'PI' property of 'Math'
console.log(Math.sqrt(16)); // Calling the 'sqrt' method of 'Math'

const text = "Hello, World!";
console.log(text.length); // Accessing the 'length' property of the string
console.log(text.toUpperCase()); // Calling the 'toUpperCase' method of the string

4. Accessing Nested Objects

The dot operator can be chained to access properties of objects within objects, or to call methods that return objects.

Example:

const company = {
    name: "TechCorp",
    address: {
        street: "123 Main St",
        city: "Tech City"
    }
};

console.log(company.address.street); // Accessing nested 'street' property
console.log(company.address.city); // Accessing nested 'city' property

Here, company.address.street uses multiple dot operators to access the street property inside the address object of company.

Conclusion:

The dot operator (.) is used to access properties and call methods on objects in JavaScript.

It's widely used in JavaScript programming to work with objects, nested objects, and built-in object methods or properties.

11. New Operator new

The new operator is used to create an instance of a constructor function or class.

Example:

function Person(name) {
    this.name = name;
}

const john = new Person("John");
console.log(john.name); // "John"

12. Await Operator await

The await operator is used inside async functions to wait for a promise to resolve.


Example:

async function fetchData() {
    const response = await fetch('https://api.example.com/data');
    const data = await response.json();
    console.log(data);
}

Conclusion:

These operators, like the dot operator (.), help you work with objects, functions, properties, and more, making JavaScript a flexible and powerful language.

Post a Comment

Previous Post Next Post

Ad01

Ad02