let count = 10;
count = 20;
const name = "React";
// name = "JS"; ❌ Error
//Normal function
function add(a, b) {
return a + b;
}
//Arrow function
const add = (a, b) => a + b;
const name = "Shree";
//Using double quotes
const msg1 = "Welcome " + name;
//Using template literals
const msg2 = `Welcome ${name}`;
//Object destructuring
const user = { name: "Rahul", age: 25 };
const { name, age } = user;
//Array destructuring
const colors = ["Red", "Blue"];
const [first, second] = colors;
//Original user object
const user = {
id: 101,
name: "Shree",
age: 30,
city: "Pune",
isActive: true
};
//Creating a new object by copying existing values
//and updating only the age
const updatedUser = {
...user,
age: 31
};
console.log(updatedUser);
In the above example, the spread operator copies all properties of the user object. Only the age property is updated, while other values remain unchanged.
//Rest operator collects all arguments into an array
const sum = (...numbers) => {
//numbers will be an array
//Example: [10, 20, 30]
return numbers.reduce((total, n) => total + n, 0);
};
//Function call
const result = sum(10, 20, 30);
console.log(result);
In this example:
const numbers = [1, 2, 3, 4];
//map
const squares = numbers.map(n => n * n);
//filter
const even = numbers.filter(n => n % 2 === 0);
//find
const value = numbers.find(n => n === 3);
//config.js
export const apiUrl = "https://api.example.com";
export const appName = "ReactApp";
//app.js
import { apiUrl, appName } from "./config.js";
console.log(apiUrl);
console.log(appName);
<script type="module" src="app.js" > </script >
const isLoggedIn = true;
//&& operator renders content only if condition is true
isLoggedIn && console.log("User Logged In");
//Ternary operator
const message = isLoggedIn ? "Welcome User" : "Please Login";
const items = [1, 2, 3];
//Wrong (mutates original array)
// items.push(4);
//Correct (creates new array)
const newItems = [...items, 4];