Introdução ao ECMAScript
Introdução
- Criada por Brendan Eich em 1995 (Netscape)
- Ecossistema popular (Stackoverflow)
- Características
- Linguagem de alto nível
- Linguagem interpretada
- Linguagem de script
- Tipagem dinâmica e fraca
- Automatic semicolon insertion (ASI)
- Multi-paradigma: orientado a eventos, orientado a objeto, protótipos, imperativo, funcional
Execução de Código
Instalação
- Navegador
- Node.js
Testar a instalação:
$ node -v
$ npm -v
$ npx -v
$ node -v
$ npm -v
$ npx -v
Execução
- Ambiente de Desenvolvimento
- Desktop: VSCode
- Online: replit
- Navegador
- Terminal
$ node file.js
$ node file.js
Tipos de dados
JavaScript for impatient programmers (Book)
Category | Types | Values |
---|---|---|
Primitive | Undefined | undefined |
Primitive | Null | null |
Primitive | Boolean | true , false |
Primitive | Number | -15 15 , 0b1111 , 0o17 , 0xf -123.45 123.45 , 1.2345e2 , 12345E-2 |
Primitive | String | 'Hello' , "Hello" , `Hello` |
Object | Array | [] [1, 2, 3] [1, '2', true, [3, false]] ["Alice", "alice@email"] |
Object | Object | {name: "Alice", email: "alice@email"} |
Declaração de Variáveis
var number = 10;
console.log(number); //=> 10
var number = 10;
console.log(number); //=> 10
let number = 10;
console.log(number); //=> 10
let number = 10;
console.log(number); //=> 10
const number = 10;
console.log(number); //=> 10
const number = 10;
console.log(number); //=> 10
Operadores
Operator type | Operators |
---|---|
Primary expressions | this , function , class , function* , yield , yield* , async function* , await , [] , {} , /ab+c/i , ( ) |
Left-hand-side expressions | object.property , object["property"] , new , new.target , super , ...obj |
Increment and decrement | A++ , A-- , ++A , --A |
Unary operators | delete , void , typeof , + , - , ~ , ! |
Arithmetic operators | + , - , * , / , % , ** |
Relational operators | in , instanceof , < , <= , > , >= |
Equality operators | == , != , === , !== |
Bitwise shift operators | << , >> , >>> |
Binary bitwise operators | & , | , ^ |
Binary logical operators | && , || |
Assignment operators | = , *= , /= , %= , += , -= , <<= , >>= , >>>= , &= , ^= , |= , [a, b] = [1, 2] , {a, b} = {a:1, b:2} |
Conditional operator | (condition ? ifTrue : ifFalse) |
Comma operator | , |
Referências:
Estruturas de Decisão
const number1 = 10;
const number2 = 10;
const operator = '+'; // (+, -)
// decision
console.log(result); //=> 20
const number1 = 10;
const number2 = 10;
const operator = '+'; // (+, -)
// decision
console.log(result); //=> 20
if
if (operator === '+') {
result = number1 + number2;
} else if (operator === '-') {
result = number1 - number2;
} else {
result = 'Invalid operator';
}
if (operator === '+') {
result = number1 + number2;
} else if (operator === '-') {
result = number1 - number2;
} else {
result = 'Invalid operator';
}
switch
switch (operator) {
case '+':
result = number1 + number2;
break;
case '-':
result = number1 - number2;
break;
default:
result = 'Invalid operator';
}
switch (operator) {
case '+':
result = number1 + number2;
break;
case '-':
result = number1 - number2;
break;
default:
result = 'Invalid operator';
}
Estrutura de Repetição
1
2
...
9
10
1
2
...
9
10
while
let flag = 1;
while (flag <= 10) {
console.log(flag);
flag += 1;
}
let flag = 1;
while (flag <= 10) {
console.log(flag);
flag += 1;
}
do…while
let flag = 1;
do {
console.log(flag);
flag += 1;
} while (flag < 10);
let flag = 1;
do {
console.log(flag);
flag += 1;
} while (flag < 10);
for
for (let flag = 1; flag <= 10; flag += 1) {
console.log(flag);
}
for (let flag = 1; flag <= 10; flag += 1) {
console.log(flag);
}
Declaração de função
function sum(param1, param2) {
return param1 + param2;
}
// Calling functions
console.log(sum(2, 1)); //=> 3
function sum(param1, param2) {
return param1 + param2;
}
// Calling functions
console.log(sum(2, 1)); //=> 3
const sum = function (param1, param2) {
return param1 + param2;
};
// Calling functions
console.log(sum(2, 1)); //=> 3
const sum = function (param1, param2) {
return param1 + param2;
};
// Calling functions
console.log(sum(2, 1)); //=> 3
const sum = (param1, param2) => param1 + param2;
// Calling functions
console.log(sum(2, 1)); //=> 3
const sum = (param1, param2) => param1 + param2;
// Calling functions
console.log(sum(2, 1)); //=> 3
Definição de Módulos
Cenários
/codes/ecma/modules/function-sum/index.js
function sum(a, b) {
return a + b;
}
console.log(sum(2, 1)); //=> 3
/codes/ecma/modules/function-sum/index.js
function sum(a, b) {
return a + b;
}
console.log(sum(2, 1)); //=> 3
src
├── lib.js
└── main.js
src
├── lib.js
└── main.js
Uma Função | Várias Funções | |
---|---|---|
CJS | 1.1 | 2.1 |
ESM | 1.2 | 2.2 |
Cenário 1.1 - Uma função no CJS
/codes/ecma/modules/cjs-default/lib.js
function sum(a, b) {
return a + b;
}
module.exports = sum;
/codes/ecma/modules/cjs-default/lib.js
function sum(a, b) {
return a + b;
}
module.exports = sum;
/codes/ecma/modules/cjs-default/main.js
const sum = require('./lib.js');
console.log(sum(2, 1)); //=> 3
/codes/ecma/modules/cjs-default/main.js
const sum = require('./lib.js');
console.log(sum(2, 1)); //=> 3
Cenário 1.2 - Uma função no ESM
/codes/ecma/modules/esm-default/lib.js
function sum(a, b) {
return a + b;
}
export default sum;
/codes/ecma/modules/esm-default/lib.js
function sum(a, b) {
return a + b;
}
export default sum;
/codes/ecma/modules/esm-default/main.js
import sum from './lib.js';
console.log(sum(2, 1)); //=> 3
/codes/ecma/modules/esm-default/main.js
import sum from './lib.js';
console.log(sum(2, 1)); //=> 3
Warning: To load an ES module, set “type”: “module” in the package.json or use the .mjs extension.
/codes/ecma/modules/esm-default/package.json
{
"name": "module-esm-default",
"version": "1.0.0",
"description": "",
"main": "main.js",
"type": "module",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC"
}
/codes/ecma/modules/esm-default/package.json
{
"name": "module-esm-default",
"version": "1.0.0",
"description": "",
"main": "main.js",
"type": "module",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC"
}
Cenário 2.1 - Várias funções no CJS
/codes/ecma/modules/cjs-named/lib.js
function sum(a, b) {
return a + b;
}
function minus(a, b) {
return a - b;
}
module.exports = { sum, minus };
/codes/ecma/modules/cjs-named/lib.js
function sum(a, b) {
return a + b;
}
function minus(a, b) {
return a - b;
}
module.exports = { sum, minus };
/codes/ecma/modules/cjs-named/main.js
const { sum, minus } = require('./lib.js');
console.log(sum(2, 1)); //=> 3
console.log(minus(2, 1)); //=> 1
/codes/ecma/modules/cjs-named/main.js
const { sum, minus } = require('./lib.js');
console.log(sum(2, 1)); //=> 3
console.log(minus(2, 1)); //=> 1
Cenário 2.2 - Várias funções no ESM
/codes/ecma/modules/esm-named/lib.js
function sum(a, b) {
return a + b;
}
function minus(a, b) {
return a - b;
}
export { sum, minus };
/codes/ecma/modules/esm-named/lib.js
function sum(a, b) {
return a + b;
}
function minus(a, b) {
return a - b;
}
export { sum, minus };
/codes/ecma/modules/esm-named/main.js
import { sum, minus } from './lib.js';
console.log(sum(2, 1)); //=> 3
console.log(minus(2, 1)); //=> 1
/codes/ecma/modules/esm-named/main.js
import { sum, minus } from './lib.js';
console.log(sum(2, 1)); //=> 3
console.log(minus(2, 1)); //=> 1
Resumo dos Cenários
Uma Função | Várias Funções |
---|---|
CJS
CJS
| CJS
CJS
|
ESM
ESM
| ESM
ESM
|
Named e Default
/codes/ecma/modules/esm-default-named/lib.js
export const PI = 3.14;
export function sum(a, b) {
return a + b;
}
export function minus(a, b) {
return a - b;
}
export default { sum, minus, PI };
/codes/ecma/modules/esm-default-named/lib.js
export const PI = 3.14;
export function sum(a, b) {
return a + b;
}
export function minus(a, b) {
return a - b;
}
export default { sum, minus, PI };
/codes/ecma/modules/esm-default-named/main.js
import Math, { sum } from './lib.js';
console.log(sum(1, 1));
console.log(Math.minus(1, 1));
/codes/ecma/modules/esm-default-named/main.js
import Math, { sum } from './lib.js';
console.log(sum(1, 1));
console.log(Math.minus(1, 1));
NPM
/codes/ecma/modules/esm-npm/lib.js
export const PI = 3.14;
export function sum(a, b) {
return a + b;
}
export function minus(a, b) {
return a - b;
}
export default { sum, minus, PI };
/codes/ecma/modules/esm-npm/lib.js
export const PI = 3.14;
export function sum(a, b) {
return a + b;
}
export function minus(a, b) {
return a - b;
}
export default { sum, minus, PI };
/codes/ecma/modules/esm-npm/main.js
import { sqrt } from 'mathjs';
import Math, { sum } from './lib.js';
console.log(sum(1, 1));
console.log(Math.minus(1, 1));
console.log(sqrt(16));
/codes/ecma/modules/esm-npm/main.js
import { sqrt } from 'mathjs';
import Math, { sum } from './lib.js';
console.log(sum(1, 1));
console.log(Math.minus(1, 1));
console.log(sqrt(16));
$ npm install mathjs
$ npm install mathjs
/codes/ecma/modules/esm-npm/package.json
{
"type": "module",
"dependencies": {
"mathjs": "^11.7.0"
}
}
/codes/ecma/modules/esm-npm/package.json
{
"type": "module",
"dependencies": {
"mathjs": "^11.7.0"
}
}