Basic Types:

```ruby
"Hello"                     # String
42                          # Integer
3.14                        # Float
true                        # TrueClass
```
```javascript
"Hello"                     // string
42                          // number
3.14                        // number
true                        // boolean
```

Checking types:

```ruby
"Boris".class   # => String
42.class        # => Integer
```
```javascript
typeof("Boris");    // => 'string'
typeof(42);         // => 'number'
```

Casting types:

```ruby
"42".to_i   # => 42
42.to_s     # => "42"
```
```javascript
JavaScript
Number.parseInt('42', 10);   // => 42

(42).toString();             // => '42'
```

Data structures:

```ruby
[ "Hello", "Le", "Bob", 42 ]    # Array

{ name: "bob", age: 42 }          # Hash with symbol as keys
{ "name" => "bob", "age" => 42 }  # Hash with string as keys
```
```javascript
[ 'Hello', 'Le', 'Bob', 42 ]    // Array

{ name: 'bob', age: 42 }          // Object
{ 'name': 'bob', 'age': 42 }      // Object (the exact same)
```

Arrays

```ruby
fruits = []
fruits << "Apple"     # Create (fruits.push("Apple") works as well)
fruits[0]             # Read
fruits[0] = "Banana"  # Update
fruits.delete_at(0)   # Delete
```
```javascript
const fruits = [];
fruits.push("Apple"); // Create
fruits[0];            // Read
fruits[0] = "Banana"; // Update
fruits.splice(0, 1);  // Delete (1 item at index 0)
```

Interpolation:

```ruby
first_name = "Ringo"
last_name = "Starr"
message = "#{first_name} #{last_name} is a drummer"
# => "Ringo Starr is a drummer";
```
```javascript
const firstName = "Ringo";
const lastName = "Starr";
const message = `${firstName} ${lastName} is a drummer`;
// => "Ringo Starr is a drummer";
```

Finding elements

```javascript
document.getElementById("some-id")
// `querySelector` returns the first element having this class
document.querySelector(".class-name")
// `querySelectorAll` returns all the elements having this class
document.querySelectorAll(".class-name")
```

Insert HTML

```javascript
Using insertAdjacentHTML():
// Select a `<ul>` element
const list = document.getElementById("some-list-id");
// Append an `<li>` using `.insertAdjacentHTML`
list.insertAdjacentHTML("beforeend", "<li>Luke</li>");
```
```javascript
Using appendChild():
// Select a `<ul>` element
const list = document.getElementById("some-list-id");
// Create a `Node` object
const listItem = document.createElement("li"); // => <li></li>
// Sets inner text to "Luke"
listItem.innerHTML = "Luke";
// Append it to the list
list.appendChild(listItem);
```

Accessing content

```html
<a id="link-id" data-sample="hello" href="https://www.lewagon.com/fr">Le Wagon</a>
```
```javascript
const element = document.getElementById("link-id");
// Get the text inside the `element`
element.innerText
element.innerHTML
// => "Le Wagon"
// Get the link (href) of `element`
element.attributes.href.value
element.dataset.sample
// => "hello"
// You can also change or add data to the `element`
element.dataset.sample = "new value";
```

Styling

```javascript
element.style.display = "none";
element.style.display = "";
element.classList.add("red");
element.classList.remove("red");
element.classList.toggle("red");
element.classList.contains("red");
```

Iterations

```javascript
const menu = ['Rice', 'Chicken', 'Burger', 'Pizza', 'Cheese cake'];
```

will return the following result:

I will eat Rice I will eat Chicken I will eat Burger I will eat Pizza I will eat Cheese cake

The While Loop

The while statement creates a loop that executes a specified statement as long as the test condition evaluates to true. The condition is evaluated before executing the statement.

```javascript
let i = 0;
while(i < menu.length) {
   console.log('I will eat' + menu[i])
   i++;
}
```

The Do While Loop

The do…while statement creates a loop that executes a specified statement until the test condition evaluates to false. The condition is evaluated after executing the statement, resulting in the specified statement executing at least once.

```javascript
let i = 0;
do {
   console.log('I will eat' + menu[i]);
   i++;
}
while(i < menu.length);
```

The For Loop

The for statement creates a loop with 3 optional expressions: _for (expression 1; expression 2; expression 3) { … }__

  • Expression 1 is executed (one time) before the execution of the code block.
  • Expression 2 defines the condition for executing the code block.
  • Expression 3 is executed (every time) after the code block has been executed.
```javascript
for(let i = 0; i < menu.length; i++;) {
   console.log('I will eat' + menu[i]);
}
```

The For In Loop

The for…in statement iterates over all enumerable string properties of an object (ignoring properties keyed by symbols), including inherited enumerable properties.

```javascript
for(const index in menu) {
   console.log('I will eat' + menu[index]);
}
```

The For Of Loop

The for…of statement executes a loop that operates on a sequence of values sourced from an iterable object. It lets you loop over iterable data structures such as Arrays, Strings, Maps, NodeLists, and more.

```javascript
for(const item of menu) {
   console.log('I will eat' + item);
}
```

The For Each Loop

The forEach() method executes a provided function once for each array element.

```javascript
menu.forEach(item => {
   console.log('I will eat' + item);
})
```

Event Listeners

```javascript
button.addEventListener("click", (event) => {
  // do something on click of an element
})
input.addEventListener("blur", (event) => {
  // do something when leaving an input
})
form.addEventListener("submit", (event) => {
  // do something on submit of a form
})
document.addEventListener("DOMContentLoaded", (event) => {
  // do something when page is loaded
})
```

Alternatively, you can also store the callback in a variable:

```javascript
const callback = (event) => {
  // do something
}
element.addEventListener("click", callback)
// See all referenced events
```

Trigger an event

```javascript
const eventSubmit = new Event("submit")
element.dispatchEvent(eventSubmit)
```

Ask for confirmation

```javascript
if (confirm("Are you sure you want to delete?")) {
  // do something
} else {
  // do something else
}
```
```javascript
const bindConfirm = (element) => {
  element.addEventListener("click", (event) => {
    if (!confirm("Are you sure you want to delete?")) {
      event.preventDefault()
    }
  })
}
```

AJAX

  • GET request:
```javascript
fetch("SOME_URL")
  .then(response => response.json())
  .then((data) => {
    // do something with the json
  })
```
  • POST request:
```javascript
fetch("https://reqres.in/api/register", {
  method: "POST",
  headers: {"Content-Type": "application/json"},
  body: JSON.stringify({"email": "eve.holt@reqres.in", "password": "pistol"})
})
  .then(response => response.json())
  .then((data) => {
    console.log(data)
  })
```