1e959d2107eb08fa0d9a3392edd308e2

7 posts by leyaim-jimenez

.forEach .map() loop JavaScript

For Each .forEach iterates the elements of an array but does not return a value.

const a = [1, 2, 3];
const newArray = a.forEach((num, index) => {
  //do something 
});

// newArray = undefined

Map .map iterates the elements of an array but return a new array.

const a = [1, 2, 3];
const newArray = a.map(num => {
  return num * 2;
});

// newArray = [2, 4, 6]

Numberic separators JavaScript

Numberic separators is a new JavaScript feature that allows you to use underscores as separators to help to improve readability using a visual separation between groups of digits.

// A billion
const amount = 1_000_000_000;

// Hundreds of millions     
const amount = 1_475_938.38;

// 6234500 cents (62345 dollars)
const amount = 62345_00;

// 1,734,500
const amount = 1_734_500; 

// 20^30000
const amount = 2e30_000;

Javascript event loop

The event loop is the secret behind JavaScript's asynchronous programming. JS executes all operations on a single thread, but using a few smart data structures, it gives us the illusion of multi-threading but first we have to understand the Call Stack.

Call Stack

The call stack works based on the LIFO principle(last in first out) When you execute a script, the JavaScript engine creates a Global Execution Context and pushes it on top of the call stack.

function multiply(a, b) {
    return a * b
}

function squere(n) {
    return multiply(n, n)
}

function printSquere(n) {
    var result = squere(n)
    console.log(result)
}

printSquere(4)

**Stack**
4- multiply
3- squere
2- printSquere
1- main

Result: 16

Call Stack with async callbacks (Even loop)

The event loop facilitates this process; it constantly checks whether or not the call stack is empty. If it is empty, new functions are added from the event queue. If it is not, then the current function call is processed.

An example of this is the setTimeout method. When a setTimeout operation is processed in the stack, it is sent to the corresponding API which waits till the specified time to send this operation back in for processing.

console.log('hi')

setTimeout(()=> {
  console.log('there')
},5000)

console.log('bye')

**Stack**
3- there
2- bye
1- hi

**webapis**
setTimeout callback(cb)

**taskqueue**
callback(cb)

**evenloop**
move cb to stack

In the example the setTimeout Callback enters the webapi stack executes and then goes to the task queue and waits for the stack to become empty and the event loop moves the callback to the stack.

Truthy and Falsy Values

If JavaScript's built-in type coercion makes it true, thats mean that the values is a truthy.

  true
  {}
  []
  42
  "0"
  "false"
  new Date()
  -42
  12n
  3.14
  Infinity
  -Infinity

and in Javascript a falsy value is a value that is considered false

  false
  0
  0n: 0 as a BigInt
  '': Empty string
  null
  undefined
  NaN

JavaScript null vs undefined

In JavaScript null and undefined are rather strange values, both serve a very similar purpose, which is to indicate the absence of a value.

Null

Null is used to assign a reference to an object that you will no longer need or, directly, you want to have the variable declared but initialize it with a value that you still do not know what it will be exactly. In all these cases the best thing to do is to assign a null value.

  var miVariable = null;
  console.log(miVariable);

//log null

undefined

For undefined means that the variable is declared but its value has not yet been defined.

  var miVariable
  console.log(miVariable);

//log null

Both values are values of type false, so if you do a non-strict comparison you will get true undefined, which means that the variable is declared but its value has not yet been defined.

if (null == undefined) {
  return true
 }
//log true

and if you do a strict comparison, because they are not really the same, it returns a false:

if (null === undefined) {
   return true
 }
return false
//log false

Javascript Hoisting

This means that variable and function declarations are physically moved to the beginning of the code and are allocated in memory during the compilation phase.

function welcomeTo(name) {
  console.log("Welcome to " + name);
}

welcomeTo("Magmalabs");
//returns welcome to magmalabs

As you can see hoisting allows you to use a function before declaring it in the code.

welcomeTo("Magmalabs");

function welcomeTo(name) {
  console.log("Welcome to " + name);
}
//returns welcome to magmalabs

And also allows you to use a function after declaring it in the code.

For variables, hoisting only applies to the declaration, not to their assignment. example:

We declare the variable name but we got an undefined

console.log(name); 
var name = magmalabs;
//return undefined

That’s because JavaScript only hoist the declaration

var name;

console.log(name); 
name = magmalabs;
//return undefined

To avoid these errors, it is very important to keep in mind that hoisting only applies to the declaration.

Optional Chaining Operator (?) and Nullish Coalescing Operator (??)

Optional Chaining Operator(?) (**)

//Car object
const car = {
  attributes: {
   year: 2021,
   model: "Ferrari"
  }
}

Before in javascript to validate that the attributes of an object exist, it was necessary to use the And operator (&&) to validate if the attributes of the object existed.

See the following example:

if (car && car.attributes && car.attributes.model) {
  console.log('Exist',  car.attributes.model)
} else {
  console.log('Do not exist')
}

# => "Exist Ferrari"

Now with Optional Chaining Operator (?) We can validate if the property exit will return undefined if the property attributes or model doesn’t exist.

if (car?.attributes?.model) {
  console.log('Exist',  car.attributes.model)
} else {
  console.log('Do not exist')
}

# => "Exist Ferrari"

Nullish Coalescing Operator(??) (**)

//Car object
const car = {
  attributes: {
   year: 2021,
   model: "Ferrari"
  }
}

If we want to get the car model then we would like below:


console.log(car.attributes.model);
# => "Ferrari"

Now the new car object does not have the model property, so we get an undefined value

//Car object
const car = {
  attributes: {
   year: 2021,
  }
}
console.log(car.attributes.model);
# => "undefined"

To avoid the undefined value the OR (| |) operator can be used, It will now return the value BMW because the property model is undefined. But what if the name property is empty like below example

console.log(car.attributes.model | | "BMW" );
# => "BMW"

Now the problem is when the property model exists but has an empty, undefined or null value we will get the BMW value and this is not right.

//Car object
const car = {
  attributes: {
   year: 2021,
   model: ""
  }
}
console.log(car.attributes.model | | "BMW" );
# => "BMW"

The solution for this problem is to use the Nullish Coalescing Operator (??), Which will print the result as an empty string.

console.log(car.attributes.model ?? "BMW" );
# => ""