JavaScript Syntax

JavaScript Syntax

Let and Const

let can be reassigned but cannot be redeclared in same scope. Should be used when you plan to reassignnew value(s) to a variable.

const cannot be reassigned. It must be declared with an initial value. Should be used as default - when you will not reassign value(s) to a variable or don't know if you will yet. If you need to reassgin the variable, refactor code by changing the variable from const to let

var should not typically be used. It may be used to globally define variables but is often considered bad practice.

Template Literals

Prior to ES6, to concatenate strings was by alternating strings with concatenation operator (+)

Note: As an alternative to using the string concatenation operator (+), you can use the String's concat()> method, but both options are rather clunky for simulating true string interpolation.

Template literals are essentially string literals that include embedded expressions.
Denoted with backticks instead of single or double quotes.
Template literals can contain placeholders which are represented using `${expression}`.

Exmaple:
instead of
let message = `${person.name} is ${person.age} years old!`;

With template literals, there is no need for "quotes" and + to concatenate. There is no need for special characters for string behavior like \n for new lines. You simply type the string how it needs to be written.

Tip: Embedded expressions inside template literals can do more than just reference variables. You can perform operations, call functions and use loops inside embedded expressions!

Destructuring

Example: (not destructured)
const scores = [8, 28, 10];
const score1 = scores[0];
const score2 = scores[1];
const score3= scores[2];
console.log(score1, score2, score3);


Example: (destructured)
const scores = [8, 28, 10];
const [score1, score2, score3] = scores;
console.log(score1, score2, score3);

Destructuring allows you to specify elements to extract from an array or object on the left side of an assignment. When destructuring, indexes are implied. To ignore values when destructuring, leave the destructured index empty: const [score1, , score 3] = scores;

Destructuring values from an object

Example:
const person = {
name: "John",
age: 27,
employed: true
};
const {name, age, employed} = person;

{curly braces} represents an object being destructured. name, age, and employed represent the variables to store the properties from the object.

Tip: To specify the value to pull from an object, let {employed} = person only pulls the employed property from the person object.

Iteration

Iteration is the process of getting to the next item in a loop.

Iterable interface allows us to customize how objects are iterated.
A loop, for...of loop, loops exclusively over iterable objects - an object that has implemented the iterable interface.

Example:
const names = ["James", "Kavita", "Richard"];
for (const oneName of names){
console.log(oneName);
}

For...of Loops

For...of loops can iterate over any type of data that is iterable; following the iterable protocol. By default, this includes the following data types: string, array, map, and set
Note: Object data types are not iterable by default.

Unlike the traditonal for loop, for...in loops eliminate the counting logic and exit condition; Indexing still needs to be used to access the values of the array and can sometimes make it more conusinf.

for...of looks identical to for...in. for...of is the most concise version of all for loops.

Tip: It's good practice to use plural names for objects that are collections of values. That way, when you loop over the collection, you can use the singular version of the name when referencing individual values in the collection. For example:
for (const number of numbers){...}

Traditional for loop

traditional for loop

for...in loop

for...in loop

for...of loop

for...of loop

Unlike the for...in loop, with for...of loops, you can stop or break the loop anytime. Also there is no need to worry about new properties to objects. The for...of loop will only iterate over the values in the object.

A downside of the for...of loop is there is no access to a specific index which may be needed.

Spread... Operator

The spread... operator allows you to expand, or spread iterable objects into multiple elements

Combing arrays with Concat()

You can combine multiple arrays using concat():
const fruits = ["apples", "bananas", "oranges"];
const vegetables = ["lettuce", "carrots", "corn"];
const produce = fruits.concat(vegetables);

Although it works, there is a shorthand way to write this code:
const fruits = ["apples", "bananas", "oranges"];
const vegetables = ["lettuce", "carrots", "corn"];
const produce = [...fruits, ...vegetables];

Rest Parameter

The rest parameter allows you to represent an indefinite number of elements as an array.

Rest parameter example

This takes the values of the order array and assigns them to individual variables using destructuring. Each element is assigned an individual variable name except items. Using the rest parameter, items is assigned the rest of the values in the array (as an array).

Variadic functions

Another use case for rest parameter is when working with Variadic functions.

Varidic functions are functions that take an indefinite number of arguments. For example, a function called sum() calculates the sum of an indefinite amount of numbers like a calculator. There's an endless number of ways sum() may be called. Regardless of the amount of numbers passed to the function, it should always return the sum total.

To accomplish this:

  • function sum(...nums) {
    let total = 0;
    for (const eachNum of nums){
    total += eachNum;
    }
    return total;
    }

    sum(5, 1, 38, 0);
    sum(3, 5);
    sum(8, 293, 10, 20, 4, 6, 28, 63);

function sum(...nums) {...} makes the code more conciese and easier to read. Remember, the for...of loop is used to loop over any iterable data.

Arrow Funcitons

Similar to regular functions, arrow functions are syntactially different

Convert function to arrow function

Converting a regular function to an arrow function:

  • Remove the function keyword
  • Remove the parantheses
  • Remove the opening/closing curly braces
  • Remove the return keyword
  • Remove the semicolon
  • Add an arrow ( => ) between the parameter list and the function body

Regular functions can be either function declarations OR Function expressions.
Arrow functions are ALWAYS expressions. They can only be used where an expression is valid:

  • stored in a variable
  • passed as an argument to a function
  • stored in an object's property

If there is only one parameter in the list, you can write the arrow function without Parentheses.

If there is zero, two or more items in the parameter list, then you MUST wrap the list of the parameters in parentheses

Arrow Function Syntax

The format for arrow functions with a single expression is called concise body syntax. Two things to remember about concise syntax:

  • It has no curly braces surrounding the function body
  • It automatically returns the expression

If more than one line of code with an arrow function is needed, use block body syntax. Two important things to remember about block syntax:

  • It uses curly braces to wrap the function body
  • A return statement must be used to return something from the function
  • Arrow function syntax is a lot short
  • It's easier to write and read short, single-line functions
  • They automatically return when using the concise body syntax