---
tags: ironhack, lecture,
---
<style>
.markdown-body img[src$=".png"] {background-color:transparent;}
.alert-info.lecture,
.alert-success.lecture,
.alert-warning.lecture,
.alert-danger.lecture {
box-shadow:0 0 0 .5em rgba(64, 96, 85, 0.4); margin-top:20px;margin-bottom:20px;
position:relative;
ddisplay:none;
}
.alert-info.lecture:before,
.alert-success.lecture:before,
.alert-warning.lecture:before,
.alert-danger.lecture:before {
content:"👨🏫\A"; white-space:pre-line;
display:block;margin-bottom:.5em;
/*position:absolute; right:0; top:0;
margin:3px;margin-right:7px;*/
}
</style>

# JS | Data Types in JavaScript - number & string
## Learning Goals
After this lesson you will:
- Know what are the two main kinds of data types in JavaScript based on their values
- Be able to use the number data type
- Be able to use the string data type
- Become more familiar with some string methods
## Two Main Kinds of Data Types
:::info lecture
Dans la leçon précédente, nous avons déjà manipulé les nombres (`Number`) ainsi que les textes (`String`).
:::
There are two kinds of data types in JavaScript:
1. **primitives** or **primitive values** and
2. **objects** or **non-primitive values**.
:::info
According to MDN, a primitive (a.k.a. primitive value or primitive data type) is **any data that is not an object and has no methods**.
:::
This being said, in JavaScript, there are 6 primitive data types:
- number,
- string,
- boolean,
- null,
- undefined,
- symbol (latest added in ECMAScript2015)
We will come back to the concept of immutability but, for now, keep in mind that **all primitive data types are immutable**.
Let's talk a bit about numbers as data types 🔢
## A number as data type
:::info lecture
Entiers ou décimaux, pour JavaScript c'est un nombre !
:::
Using numbers, we can represent **integers** and **floating-point numbers** in JavaScript.
```javascript
const age = 34;
const price = 12.99;
```
:::info lecture
`Infinity` est une valeur spéciale, de type `Number` valant l'infini, ex :
```jsx
console.log(Infinity + 1); // Infinity
console.log(Infinity - 999999999) // Infinity
console.log(Infinity * 2) // Infinity
console.log(Infinity * -1) // -Infinity
```
:::
Number as a data type also supports **special numeric values**:
`NaN` and `Infinity`. We really don't have to go in details here but `NaN` is something that you'll see throughout this course so let's explain a bit.
:::info lecture
`NaN` est l'accronyme de `Not A Number`.
C'est là encore une valeur spéciale d'un `Number`, indiquant une erreur de calcul, comme par ex la multiplication d'un nombre avec un texte :
```jsx
console.log(3.7 * "Jacques Chirac"); // NaN
```
🙃 ce que l'interpréteur ne sait pas calculer et nous le signifie par cette valeur spéciale : `NaN`.
:::
`NaN` stands for **Not a Number** and it represents a **computational error**. It is a result of an incorrect mathematical operation, such as:
```javascript
const name = "Sandra"; // <== string data type
const whatIsThis = name/2;
console.log(whatIsThis); // ==> NaN
```
*NaN* is not normal number, it just belongs to this data type. If you get *NaN* and you expected to get a number after some mathematical operation, you are problably performing the operation on a string or some other data type that isn't a number.
### Number expressions
:::info lecture
Les opérateurs arythmétiques classiques : `+`, `-`, `*`, `/`
---
<span style="font-size:300%">🧮</span>
Pas de surprise ici
:::
If you're familiar with math or other sciences, the term `operator` is well known to you. When we're doing basic addition, in the example `2 + 2`, `+` is the `operator`, and the operation exectuted here is `addition`.
Let's recap some basic math operations:
- `+` addition
- `-` subtraction
- `*` multiplication
- `/` division
Everyone is familiar with these operators, but in case you want to play a bit with them, here's a codepen:
<iframe height='265' scrolling='no' src='//codepen.io/ironhack/embed/WGRbGO/?height=265&theme-id=0&default-tab=js,result&embed-version=2' frameborder='no' allowtransparency='true' allowfullscreen='true' style='width: 100%;'>See the Pen <a href='http://codepen.io/ironhack/pen/WGRbGO/'>JavaScript - Simple Math</a> by Ironhack (<a href='http://codepen.io/ironhack'>@ironhack</a>) on <a href='http://codepen.io'>CodePen</a>.
</iframe>
### Advanced Operators
#### Exponentiation
:::info lecture
`**` ou `Math.pow`
:::
In math, there is a very useful concept called [exponentiation](http://mathworld.wolfram.com/Exponentiation.html). Exponentiation is the process of taking a quantity `b` (the base) to the power of another quantity `e` (the exponent).
In JavaScript, we can easily use exponentiation by using the `**` (exponentiation) operator:
```javascript
console.log(2**5);
// 2 * 2 * 2 * 2 * 2
// => 32
```
#### Modulo
:::info lecture
`%` ‒ reste de la division euclidienne
ex:
```jsx
console.log(23 % 5); // 3
```

:::
Modulo (`%`) is the remainder operator. Think of this as saying *If I divide the first number by the second, what is the remainder?*
This is very handy for finding multiples of a particular number, and many other use cases:
<iframe height='385' scrolling='no' src='//codepen.io/ironhack/embed/ozBgrX/?height=385&theme-id=0&default-tab=js,result&embed-version=2' frameborder='no' allowtransparency='true' allowfullscreen='true' style='width: 100%;'>See the Pen <a href='http://codepen.io/ironhack/pen/ozBgrX/'>JavaScript - Modulo Operator</a> by Ironhack (<a href='http://codepen.io/ironhack'>@ironhack</a>) on <a href='http://codepen.io'>CodePen</a>.
</iframe>
:::info lecture
Pratique par ex pour détecter si un nombre est pair :
```
Un nombre est pair ssi le reste de la division euclidienne par 2 vaut 0.
```
:::
#### Assigment Operators
:::info lecture
`=` est l'opérateur d'assignation.
:::
Previously we learned how to assign values to variables. We use `=` sign to do this. To make sure we are all on the same page:
:::info
The basic assignment operator is equal (=), which assigns the value of its right operand to its left operand. That is, x = y assigns the value of y to x. (source: [Assignment operators](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Assignment_Operators))
:::
Very commonly used assignment operator is `+=` and here is example how to use it:
<iframe height='265' scrolling='no' src='//codepen.io/ironhack/embed/jryEGk/?height=265&theme-id=0&default-tab=js,result&embed-version=2' frameborder='no' allowtransparency='true' allowfullscreen='true' style='width: 100%;'>See the Pen <a href='http://codepen.io/ironhack/pen/jryEGk/'>JavaScript - +=</a> by Ironhack (<a href='http://codepen.io/ironhack'>@ironhack</a>) on <a href='http://codepen.io'>CodePen</a>.
</iframe>
:::info lecture
`+=` est l'opérateur d'incrémentation.
```jsx=
let age = 29;
age += 1;
age += 3;
console.log(age); // 33
```
La ligne 2 est équivalente à :
```jsx=2
age = age + 1; // j'assigne age à sa valeur + 1
```
:::
`+=` is the equivalent of saying `myAge = myAge + 1`. Adding `myAge` and `1` on its own *does not* change the value of myAge, it simply adds the two together and `returns` you the value computed. (**Remember this when we talk about immutability a bit later in the lesson.**)
##### Basic Assignment Operators Table
These are the most used assignment operators:
| Name | Operator | Equivalent
|--------------|----------|-----------
|**Assignment**: `=`|`x = y` | N / A
|**Addition assignment**: `+=`| `x += y` | `x = x + y`
|**Subtraction assignment**: `-=`| `x -= y` | `x = x - y`
|**Multiplication assignment**: `*=`| `x *= y` |`x = x * y`
|**Division assignment**: `/=`| `x /= y` |`x = x / y`
|**Remainder assignment**: `%=`| `x %= y` | `x = x % y`
|**Exponentiation assignment**: `**=`| `x **= y` | `x = x ** y`
:::info lecture
Tous ces opérateurs arythmétiques ont leur équivalent d'opérateur d'assignation, ex:
```jsx
let age = 12;
age *= 2; // 24
age -= 4; // 10
age **= 2; // 100
```
:::
To see the full list, visit [Assignment Operators - Overview](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Assignment_Operators#Overview).
### Expressions
:::info lecture
Une expression en JavaScript sera constituée de différentes valeurs et d'opérateurs. Elle sera évaluée au résultat des différents opérateurs sur ses différentes valeurs.
Plus simplement :
```jsx
2 + 4 - 1 // expression évaluée à 5
```
:::
An expression is a combination of any `value` (number, string, array, object) and set of `operators` that result in another value.
So we can say that the following is an example of an *expression*:
```javascript
2 + 4
```
And this is its correspondent [parse tree](https://en.wikipedia.org/wiki/Parse_tree):

*Take the number two and add four to it.*
Another example is this:
```javascript
const result = ((7 + 5) / 3) - 8;
console.log(result);
// => -4
```
- Take the number 7, add it to 5
- Divide this new value by 3
- Take that value and then subtract 8
- Assign that value to `result`
*Parantheses* are known as a [grouping operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Grouping).
:::info lecture
Comme en Maths, on peut mettre des parenthèses autour des valeurs ou de l'expression entière :
```jsx
(1 + 8) - 5
(1 + 8 - 5)
(((1))) + (((8))) - (((5))) // c'est gratuit les (), FPH 😉
```
Cela sera surtout utile pour faire respecter les priorités.
:::
It seems JavaScript knows in what order to put the numbers together. How does it do this?
Well it literally follows the basic mathematic rules - let's refresh our memory.
### Operator Precedence
:::info lecture
Comme en Maths, les opérateurs ont des priorités, par ex : `*` est prioritaire sur `-` :
```jsx
console.log(2 * 4 - 7); // 1 et non -6
```
implicitement, c'est comme si on avait écrit avec des parenthèses :
```jsx
console.log((2 * 4) - 7); // pas hésiter si plus clair
```
:::
:::success
In mathematics and computer programming, the order of operations (or operator precedence) is a collection of rules that define which procedures to perform first in order to evaluate a given mathematical expression.
:::
Expressions in math have a particular order in which they get evaluated, based on the operators they use.
`2 + 2 = 4`
`2 + 2 * 2 = 6`
`(2 + 2) * 2 = 8`
As we said, in JavaScript, the same as in math, we have to follow **PEMDAS** rules.
:::info lecture
Voici du plus ou moins prioritaire la liste des opérateurs arythmétiques :
:::
Precedence | Operator | Name
:---:|-------|------
1 | `()` | **P**arantheses
2 | `**` | **E**xponents
3 | `*` | **M**ultiplication
4 | `/` | **D**ivision
5 | `+` | **A**ddition
6 | `-` | **S**ubtraction
In the numerical order, anything that comes first will be executed first (**1** for **Parentheses**, **2** for **Exponents**, etc.), meaning that anything in parantheses will be executed first, exponents second, multiplication third, etc.
```javascript
const i = 10 + 5 * 2 ** 3 / 4 - 6
// === 10 + 5 * 8 / 4 - 6 <== start with the exponents (2 ** 3)
// === 10 + 40 / 4 - 6 <== then multiplication (5 * 8)
// === 10 + 10 - 6 <== then division (40 / 4)
// === 20 - 6 <== then addition (10 + 10 )
// ==> 14 <== and finally finish with subtraction (20 - 6)
```
:::info lecture
Voici comment le JS évalue cette expression :
:::
This Parse Tree diagram may help you understand it more visually :)

You can find a list of these operators, and the order in which they are executed [here at MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence).
### Exercise: Guess the Expression Result!
Take a solid guess at what the result of the expression is going to be!
:::info
**Tip:** To see the actual result, uncomment the `console.log` by pressing `⌘` + `/`
:::
<iframe height='475' scrolling='no' src='//codepen.io/ironhack/embed/qaRJab/?height=475&theme-id=0&default-tab=js,result&embed-version=2' frameborder='no' allowtransparency='true' allowfullscreen='true' style='width: 100%;'>See the Pen <a href='http://codepen.io/ironhack/pen/qaRJab/'>qaRJab</a> by Ironhack (<a href='http://codepen.io/ironhack'>@ironhack</a>) on <a href='http://codepen.io'>CodePen</a>.
</iframe>
## A string as data type
:::info lecture
Le type texte, aka. chaîne de caractères.
<span style="font-size:300%">📖</span>
:::
### What is a string?
A `string` is simply **a sequence of characters**. A `character` can be a letter, number, punctuation, or even things such as new lines and tabs.
### Creating a String
:::info lecture
Voici 3 façons strictement équivalentes de créer du texte.
En entourant notre texte de :
- **double** quotes :
```jsx
let bambi = "Il était une fois, dans une forêt majestueuse...";
```
- **simple** quotes :
```jsx
let bambi = 'Il était une fois, dans une forêt majestueuse...';
```
- **back**quotes :
```jsx
let bambi = `Il était une fois, dans une forêt majestueuse...`;
```
:::
To create a string in JavaScript you have to use one of these **quotes**:
- `""` double quotes,
- `''` single quotes or
- ` `` ` backticks (grave accents).
:::info lecture
` `` ` présentent par contre des avantages par rapport aux 2 autres :
- on peut écrire le texte **sur plusieurs lignes** :
```jsx
const poeme = `
Bras en sang Gai comme les sainfoins
L'hyperbole retombe Les mains
Les oiseaux sont des nombres
L'algèbre est dans les arbres
C'est Rousseau qui peignit sur la portée du ciel
Cette musique à vocalises
`;
```
- on peut "imprimer" certaines valeurs ici du programme à l'intérieur du texte, comme par ex ici la valeur de la variable `benef` :
```jsx
let benef = 35000;
let bilan = `Bénéfice NET: ${benef} €`;
```
:::
There's no real difference between double and single quotes, so it's matter of preference.
**Backticks**, however, have **"extra" functionality**. Using backticks we can **embed variables and expressions inside the strings**:
```javascript
let name = "Ana";
console.log(`Hello there, ${name}!`);
// ==> Hello there, Ana!
console.log(`${name} walks every day at least ${1+2} km 👏🏻`);
// ==> Ana walks every day at least 3km 👏🏻
```
Another great functionality of backticks is being able to easily add **new lines** in the same string (meaning the string can span multiple lanes):
```javascript
const fruits = `
1. banana 🍌
2. apple 🍎
3. orange 🍊
4. cherry 🍒
`;
console.log(fruits);
// 1. banana 🍌,
// 2. apple 🍎,
// 3. orange 🍊,
// 4. cherry 🍒
```
As we can see, each fruit is on its own line ✅. With other kinds of strings that would cause a syntax error.
<!-- **to take out:**
<iframe height='265' scrolling='no' src='//codepen.io/ironhack/embed/ALjZxV/?height=265&theme-id=0&default-tab=js,result&embed-version=2' frameborder='no' allowtransparency='true' allowfullscreen='true' style='width: 100%;'>See the Pen <a href='http://codepen.io/ironhack/pen/ALjZxV/'>JavaScript - Creating strings</a> by Ironhack (<a href='http://codepen.io/ironhack'>@ironhack</a>) on <a href='http://codepen.io'>CodePen</a>.
</iframe> -->
#### Special characters
:::info lecture
Le seul cas où l'on préfèrera les doubles guillemets aux simples, c'est quand le texte contient un apostrophe :
```jsx
let perrier = "c'est fou"; // apostrophe
```
Autrement on devrait "protéger" l'apostrophe par un caractère spécial `\` pour signifier au JS de ne pas l'interprêter comme la fin de la chaine :
```jsx
let perrier = 'c\'est fou'; // on anti-slashe l'apostrophe
```
---
Il en va de même dans le cas où un texte comprendrais des guillemets, on préfèrerait alors les simples quotes pour éviter d'avoir à "protéger" les guillemets.
:::
Some strings are special because they contain special characters. This means that we have to use **`escape sequences`** to make everything work.
For example, when you want to have double quotes in the middle of your string (sentence), you will have to use some "magic" 🎩.
```javascript
const favBook = "My favorite book is "Anna Karenina".";
console.log(favBook); // <== error: Unexpected token
```
If you can use single quotes, no problem:
```javascript
const favBook = "My favorite book is 'Anna Karenina'.";
console.log(favBook); // <== My favorite book is 'Anna Karenina'.
```
If you, however, for some reason have to use double quotes, your way around this would be using **backslash escape** character.
```javascript
const favBook = "My favorite book is \"Anna Karenina\".";
console.log(favBook); // <== My favorite book is "Anna Karenina".
```
The same applies for apostrophes inside single quote strings:
```javascript
const mood = 'I\'m OK.';
console.log(mood); // <== I'm OK.
```
:::info
So, to conclude, you should use `\` (backslash) when there's a need to escape a special character in a string.
:::
It's still possible to create **multilane strings** with double or single quotes but with a help of "new line character" `\n`.
```javascript
const fruits = " 1. banana 🍌\n 2. apple 🍎\n 3. orange 🍊\n 4. cherry 🍒";
console.log(fruits);
// 1. banana 🍌,
// 2. apple 🍎,
// 3. orange 🍊,
// 4. cherry 🍒
```
To summarize - these are different ways of doing the same thing:
:::info
```javascript
console.log("Web Dev \nUX/UI");
console.log(`Web Dev
UX/UI`);
// both consoles are the same:
// Web Dev
// UX/UI
```
:::
<!-- **to take out:**
<iframe height='265' scrolling='no' src='//codepen.io/ironhack/embed/ozgKqV/?height=265&theme-id=0&default-tab=js,result&embed-version=2' frameborder='no' allowtransparency='true' allowfullscreen='true' style='width: 100%;'>See the Pen <a href='http://codepen.io/ironhack/pen/ozgKqV/'>JavaScript - Escaped strings</a> by Ironhack (<a href='http://codepen.io/ironhack'>@ironhack</a>) on <a href='http://codepen.io'>CodePen</a>.
</iframe> -->
:::info
:star: You can see a full list of these special characters at the [Mozilla Developer Network](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Grammar_and_types#Using_special_characters_in_strings).
:::
#### String length
:::info lecture
On peut demander au programe la longueur d'une chaîne (ie: son nombre de caractères) grâce à la propriété `.length` disponible sur toute chaîne. Par ex:
```jsx
console.log("papa".length); // 4
const mot = "anticonstitutionnellement";
console.log(mot.length); // 26
```
NB: ☝️ Cela ne fonctionne que sur les chaîne, pas sur les nombres par ex.
:::
`.length` is a numeric property of a string.
```javascript
const name = "Ana";
console.log(name.length); // <== 3
```
`length` is not a method of a string so don't try to get it by putting parentheses after 👎 `name.length()` ❌
### Methods for string manipulation
Manipulating and modifying strings in code are common operations. Simple things such as capitalizing a name, or checking to see if a word starts with some letter are very common.
JavaScript includes a **String library of methods** to simplify some of the most common tasks on strings. Let's look at how to perform some of these operations.
#### Adding To Strings
:::info lecture
On peut "fusionner" 2 chaînes ensemble, grâce à l'opérateur `+`.
Quand la première valeur à laquelle il s'applique est de type `String`, ce dernier ne s'appelle alors plus l'opérateur d'addition mais l'opérateur de concaténation, permettant de réunir 2 chaînes :
```jsx
console.log(1+2); // 3
console.log("a"+"b"); // "ab"
console.log("a"+2); // "a2"
console.log(1+"b"); // NaN
```
:::
We can easily `concatenate` or add characters to strings with the ```+``` or ```+=``` operator.
<iframe height='265' scrolling='no' src='//codepen.io/ironhack/embed/EgaqRZ/?height=265&theme-id=0&default-tab=js,result&embed-version=2' frameborder='no' allowtransparency='true' allowfullscreen='true' style='width: 100%;'>See the Pen <a href='http://codepen.io/ironhack/pen/EgaqRZ/'>JavaScript - String Concatenation</a> by Ironhack (<a href='http://codepen.io/ironhack'>@ironhack</a>) on <a href='http://codepen.io'>CodePen</a>.
</iframe>
:::info lecture
Idem pour l'opérateur `+=` appliqué à une chaîne :
```jsx
let pseudo = "a";
pseudo += "ber";
pseudo += "nier";
console.log(pseudo); // "abernier"
```
:::
#### Accessing characters
:::info lecture
```jsx
const school = "Ironhack";
console.log("la 1ère lettre est :");
console.log(school[0]); // "I"
console.log("la 5ème lettre est :");
console.log(school[4]); // "h"
console.log("la 100ème lettre est :");
console.log(school[99]); // undefined
```
NB : ☝️ on commence à l'index 0
:::
One of the ways to access the characters inside the string is using **`charAt(n)`** method.
:::success
**`charAt(n)`** shows the character on the `n`th position in the string but keep in mind, the first character is indexed with zero (0).
:::
```javascript
const greeting = "Hello there!";
console.log(`"${greeting}" is a string and it's length is ${greeting.length}.`);
// "Hello there!" is a string and it's length is 12.
console.log(greeting.charAt(0)); // <== H
console.log(greeting.charAt(1)) // <== e
console.log(greeting.charAt(5)); // <== " "
console.log(greeting.charAt(11)); // <== !
console.log(greeting.charAt(12)); // <== "" as an empty string
```
We can also access characters inside of strings with square brackets and their **`index`** number. As we said, the index **starts at 0**.
```javascript
const greeting = "Hello there!";
console.log(greeting[0]); // <== H
console.log(greeting[3]); // <== l
console.log(greeting[9]); // <== r
console.log(greeting[-2]); // undefined
```
<!-- **to be taken out**
<iframe height='265' scrolling='no' src='//codepen.io/ironhack/embed/XjJvxB/?height=265&theme-id=0&default-tab=js,result&embed-version=2' frameborder='no' allowtransparency='true' allowfullscreen='true' style='width: 100%;'>See the Pen <a href='http://codepen.io/ironhack/pen/XjJvxB/'>JavaScript - Accessing characters</a> by Ironhack (<a href='http://codepen.io/ironhack'>@ironhack</a>) on <a href='http://codepen.io'>CodePen</a>.
</iframe> -->
#### Finding a substring
:::info lecture
On peut faire une recherche dans un texte grâce à la méthode `.indexOf`:
```jsx
const message = "Hello you.";
// 0123456789
console.log(message.indexOf("you")); // 6
console.log(message.indexOf("ll")); // 2
console.log(message.indexOf("huitre")); // -1
```
qui retournera :
- `-1` si non-trouvée
- la position de la chaîne si trouvée
:::
JavaScript has a cool **`.indexOf(substr)`** method that returns the index where a particular character/substring occurs. If the substring was not found, it returns `-1`.
```javascript
const message = "Don't be sad, be happy!";
console.log(message.indexOf("Don't")); // <== 0
console.log(message.indexOf("t")); // <== 4
console.log(message.indexOf("Be")); // <== -1 (capitalized Be ≠ lowercased be)
console.log(message.indexOf("py")); // 20
```
The substring `be` appears more than once. To see the next occurance, we need to tell somehow our .indexOf() method to skip the first one.
```javascript
const message = "Don't be sad, be happy!";
console.log(message.indexOf("be")); // <== 6
console.log(message.indexOf("be", 7)); // <== 14
```
What we did was passing a second parameter, which represents a value where the first occurence appeared (it was 6) + 1. So we are telling the method to skip the positions from `0 to 7` and keep looking for the occurence of the first parameter (in our case: *"be"*).
If we need to look for a substring but from the end to its beginning, you can use **`str.lastIndexOf(substr)`**. It shows occurences in the reverse order.
```javascript
const message = "Don't be sad, be happy!";
console.log(message.lastIndexOf("be"));
// The index of the first "be" from the end is 14
```
<!-- **to be taken out**
<iframe height='265' scrolling='no' src='//codepen.io/ironhack/embed/bwdbNR/?height=265&theme-id=0&default-tab=js,result&embed-version=2' frameborder='no' allowtransparency='true' allowfullscreen='true' style='width: 100%;'>See the Pen <a href='http://codepen.io/ironhack/pen/bwdbNR/'>bwdbNR</a> by Ironhack (<a href='http://codepen.io/ironhack'>@ironhack</a>) on <a href='http://codepen.io'>CodePen</a>.
</iframe> -->
#### 📝Practice
:::info lecture
Exercice
:::
Write code that finds the index of the letter "j" in `My favorite dessert is jello`.
#### .repeat()
:::info lecture
A tester dans Codepen
:::
Repeat does exactly what it sounds like. Call repeat on a specific string, and pass it an argument of the times it is to be repeated.
<iframe height='265' scrolling='no' src='//codepen.io/ironhack/embed/WGvZwX/?height=265&theme-id=0&default-tab=js,result&embed-version=2' frameborder='no' allowtransparency='true' allowfullscreen='true' style='width: 100%;'>See the Pen <a href='http://codepen.io/ironhack/pen/WGvZwX/'>JavaScript - Handy String Methods</a> by Ironhack (<a href='http://codepen.io/ironhack'>@ironhack</a>) on <a href='http://codepen.io'>CodePen</a>.
</iframe>
<!-- #### .includes(), .startsWith(), .endsWith()
**`.includes()`** is a case sensitive search to see if a particular pattern exists inside of a string.
<iframe height='265' scrolling='no' src='//codepen.io/ironhack/embed/ORVLWg/?height=265&theme-id=0&default-tab=js,result&embed-version=2' frameborder='no' allowtransparency='true' allowfullscreen='true' style='width: 100%;'>See the Pen <a href='http://codepen.io/ironhack/pen/ORVLWg/'>ORVLWg</a> by Ironhack (<a href='http://codepen.io/ironhack'>@ironhack</a>) on <a href='http://codepen.io'>CodePen</a>.
</iframe>
The methods **`str.startsWith()`** and **`str.endsWith()`** do exactly what you think 😌:
```javascript
const message = "Don't be sad, be happy!";
console.log(message.startsWith("Do")); // <== true
console.log(message.endsWith("happy")); // <== false
console.log(message.endsWith("!")); // <== true
``` -->
#### Getting a substring
:::info lecture
Extraire une partie du texte.
:::
In JavaScript, we can use
- **.substring()**,
- **.substr()** and
- **.slice()**
to get a substring from a string. Each of these methods is used for **getting the part of the string between start and end** but they have slight differences.
```javascript
const message = "Don't be sad, be happy!";
let withSubstring = message.substring(0,3);
console.log(withSubstring); // <== Don
let withSubstr = message.substr(0,3);
console.log(withSubstr); // <== Don
let withSlice = message.slice(0,3);
console.log(withSlice); // <== Don
```
:::warning lecture
Bien faire référence à MDN qd on utilise ces méthodes. Les différences sont subtiles.
☝️Le plus important ici n'étant pas de retenir les subtilités mais bien de **savoir où trouver la documentation**
:::
As we can see, they all give the same results. What if we pass a **negative** values?
```javascript
let withSubstring = message.substring(-3,-1);
console.log(withSubstring); // <== "" (empty string)
let withSubstr = message.substr(-3,-1);
console.log(withSubstr); // <== "" (empty string)
let withSlice = message.slice(-3,-1);
console.log(withSlice); // <== py
```
Only **.slice() supports negative values** and they mean the **position is counted from the string end**.
It's matter of your personal preference which one to use.
#### Sorting the strings - .localeCompare()
According to [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/localeCompare), the **`.localeCompare()`** method returns a number indicating whether a string comes before or after or is the same as some other string in sort order.
How this method works?
```javascript
'str1'.localeCompare('str2');
```
:+1: Returns **1** if `str1` is greater than `str2` according to the language rules.
:+1: Returns **-1** if `str1` is less than `str2`.
:+1: Returns **0** if they are equal.
```javascript
console.log('barcelona'.localeCompare('miami') ); // -1
console.log('miami'.localeCompare('barcelona') ); // 1
console.log('Miami'.localeCompare('miami') ); // 1
```
ES6 introduced a couple more methods but we will cover them in the later leanring unit.
## Summary
In this lesson we learned how to declare, use and manipulate numbers and strings, two primitive data types.
## Extra Resources
- Most of the JavaScript String methods can be found at [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String)
- [Using special characters in strings](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Grammar_and_types#Using_special_characters_in_strings)