domingo, 12 de fevereiro de 2023

Tipos de Dados em Javascript


Os dados em JavaScript podem ser apresentados de diversas formas.

strings
Strings são comumente conhecidas como sequências de caracteres. Elas podem ou não ter um significado em algum idioma, ou podem ser apenas um aglomerado de letras. É como se fosse texto puro, sem qualquer tipo de significado funcional para o código.
  • Concatenação de string: agregação de duas ou mais strings utilizando o +. nome + idade
  • Interpolação de string: agregação de uma variável a uma strings utilizando o ${}. `${nome}, prazer`
    Observação: usa-se crase na interpolação.

When you are defining a string you must start and end with a single or double quote. What happens when you need a literal quote: " or ' inside of your string? In JavaScript, you can escape a quote from considering it as an end of string quote by placing a backslash (\) in front of the quote. const sampleStr = "Alan said, \"Peter is learning JavaScript\"."; This signals to JavaScript that the following quote is not the end of the string, but should instead appear inside the string. So if you were to print this to the console, you would get: Alan said, "Peter is learning JavaScript". Escape Sequences in Strings Quotes are not the only characters that can be escaped inside a string. There are two reasons to use escaping characters: To allow you to use characters you may not otherwise be able to type out, such as a newline. To allow you to represent multiple quotes in a string without JavaScript misinterpreting what you mean. We learned this in the previous challenge. Code Output \' single quote \" double quote \\ backslash \n newline \t tab \r carriage return \b word boundary \f form feed concatenação com +=: repete sem o var/let += a nova coisa Find the Length of a String You can find the length of a String value by writing .length after the string variable or string literal. console.log("Alan Peter".length); The value 10 would be displayed in the console. Note that the space character between "Alan" and "Peter" is also counted. For example, if we created a variable const firstName = "Ada", we could find out how long the string Ada is by using the firstName.length property. numbers
Os números são utilizados puramente como demonstrações quantitativas, ou seja, eles têm valores reais. Existem strings que podem se disfarçar de números, ou seja, você pode se deparar com um número escrito em forma de string. Ele não terá valor quantitativo, pois será uma string (um conjunto de caracteres sem valor real), mas é possível transformá-los com a funcionalidade number().


boolean
Booleans retornam um true ou false. São usadas em condicionais.


Array
Arrays podem armazenar vários elementos, que são chamados de index.
const groceries = ['banana', 'orange', 'apple', 'pear']
console.log(groceries[2]) ===> apple
  • A contagem sempre começa em 0.
.push: inclui mais um index.
groceries.push('pineapple')
.slice: extrai uma quantidade de indexes, incluindo o primeiro (0) e adicionando a quantidade de indexes que for informada.
console.log(groceries.slice(0,2))
indexOf: dá o número do index de uma array.
console.log(groceries.indexOf('orange'))
length: dá o número total de indexes de uma array.
console.log(groceries.length)


Object
Object podem armazenar várias características.
const person = {
name: 'Leonardo',
shirt: 'white'
}

console.log(person.name)
console.log(person.shirt)


Para acessar as informações do objeto:
Com pontos:
console.log(person.name)

Com chaves:
console.log(person['name'])

Para adicionar as informações do objeto:
Com pontos:
person.phone = '1-222-333-4444'

Com chaves:
person['sign'] = 'Aries'
Objeto em ação:
const person2 = {
name: 'Qazi',
shirt: 'black'
}

const introducer = (name, shirt) => {
const person = {
name: name,
shirt: shirt
}
const intro = `Hi, my name is ${person.name}, and my shirt is ${person.shirt}`
return intro
}

console.log(introducer('Malu', 'pink'))


Tipos de Dados: undefined, null, boolean, string, symbol, bigint, number, and object.