WEB Programming
JavaScript
02-Modern Syntax

Modern Syntax

  • JavaScript has evolved with new features like arrow functions, destructuring, and template literals that simplify code and improve readability.

Arrow Functions

  • Arrow functions solve the issue of lexical "this" by using the "this" value of their parent scope, eliminating the need for workarounds like using a separate variable.
// Traditional function
function traditionalFunction() {
  console.log(this); // Logs the global object (window in browsers)
}
 
// Arrow function
const arrowFunction = () => {
  console.log(this); // Logs the 'this' value from the parent scope
};
 
// In a method, arrow functions inherit 'this' from their parent scope
const obj = {
  name: 'Example',
  regularFunction: function() {
    setTimeout(function() {
      console.log(this.name); // undefined, 'this' refers to global object
    }, 1000);
  },
  arrowFunction: function() {
    setTimeout(() => {
      console.log(this.name); // 'Example', 'this' refers to the obj scope
    }, 1000);
  }
};
 
obj.regularFunction();
obj.arrowFunction();

Arrow functions don't have their own this; they inherit this from their parent scope, making them useful for preserving context.


Destructuring

  • Destructuring allows for extracting values from objects and arrays in a more concise and readable way, making code more efficient and reducing the need for multiple lines of assignment.
// Object destructuring
const user = { name: 'John', age: 30 };
const { name, age } = user; 
console.log(name); // John
console.log(age); // 30
 
// Array destructuring
const numbers = [1, 2, 3];
const [first, second, third] = numbers;
console.log(first); // 1
console.log(second); // 2
console.log(third); // 3

Destructuring simplifies the process of extracting values from objects and arrays, improving code readability and reducing the need for repetitive assignments.


Spread Syntax

  • Spread syntax is a useful feature for merging arrays or objects, providing a simple way to create new copies or combine values.
// Merging arrays
const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
const mergedArray = [...arr1, ...arr2];
console.log(mergedArray); // [1, 2, 3, 4, 5, 6]
 
// Copying objects
const obj1 = { a: 1, b: 2 };
const obj2 = { b: 3, c: 4 };
const mergedObject = { ...obj1, ...obj2 };
console.log(mergedObject); // { a: 1, b: 3, c: 4 }

The spread operator (...) allows for easy copying and merging of arrays and objects, making code cleaner and more efficient.


Template Literals

  • Template literals provide a more flexible and readable way to create strings in JavaScript, allowing for embedded expressions and multi-line strings.
const name = 'Alice';
const age = 25;
 
// Using template literals
const greeting = `Hello, my name is ${name} and I am ${age} years old.`;
console.log(greeting); // Hello, my name is Alice and I am 25 years old.

Template literals use backticks (`) and placeholders (${}) for embedding expressions within strings, enhancing readability and ease of use.


Iterating Over Arrays

  • Iterating over arrays has become easier with features like the for...of loop and the forEach method, providing more options for iterating and processing array elements.
const array = [1, 2, 3, 4, 5];
 
// Using for...of loop
for (const item of array) {
  console.log(item); // 1 2 3 4 5
}
 
// Using forEach method
array.forEach(item => {
  console.log(item); // 1 2 3 4 5
});

Error Handling

  • Error handling is crucial in programming, and JavaScript provides mechanisms like try/catch blocks and the ability to throw custom errors to handle and respond to errors gracefully.
// Basic try/catch example
try {
  // Code that might throw an error
  let result = riskyOperation();
  console.log(result);
} catch (error) {
  console.error('An error occurred:', error.message);
} finally {
  console.log('This will run regardless of an error');
}
 
function riskyOperation() {
  throw new Error('Something went wrong!');
}
 
// output:
//  An error occurred: Something went wrong!
//  This will run regardless of an error

The try/catch block handles errors by executing code that might throw an error inside the try block. If an error occurs, it is caught in the catch block, where you can handle it gracefully. The finally block runs code regardless of whether an error occurred. throw new Error('message') creates and throws a new error with a specified message, interrupting normal code execution and passing control to the nearest catch block.