100 Conceitos Javascript
100 Conceitos Javascript
let x = 5; // x is 5
const pi = 3.14; // pi is a constant 3.14
4- Objects: Objects are variables too. But objects can contain many
values.
let x = 5;
let y = x + 2; // y is now 7
if (x > y) {
// do something
} else {
// do something else
}
function myFunction(x, y) {
return x * y;
}
9- Strings and String Methods: Strings are useful for holding data that
can be represented in text form. There are many methods that can be
used with strings including length, indexOf, search, replace, etc.
10- Number and Number Methods: JavaScript has only one type of number.
Numbers can be written with, or without decimals. JavaScript numbers
can also include + and - , and e to indicate exponents.
console.log(Math.PI); // 3.141592653589793
console.log(Math.sqrt(16)); // 4
try {
notAFunction();
} catch(err) {
console.log(err); // ReferenceError: notAFunction is not defined
} finally {
console.log('This will run regardless of the try/catch result');
}
17- AJAX: AJAX is about updating parts of a web page, without reloading
the whole page. It stands for Asynchronous JavaScript and XML.
function makeAdder(x) {
return function(y) {
return x + y;
};
}
let add5 = makeAdder(5);
let add10 = makeAdder(10);
console.log(add5(2)); // 7
console.log(add10(2)); // 12
21- Arrow Functions: Arrow functions allow for a shorter syntax when
writing functions. Arrow functions do not have their own this.
23- Spread Operator and Rest Parameters: The spread operator allows an
iterable to be expanded in places where zero or more arguments are
expected. The rest parameter syntax allows a function to accept an
indefinite number of arguments as an array.
// Spread operator
let arr1 = [1, 2, 3];
let arr2 = [...arr1, 4, 5, 6]; // [1, 2, 3, 4, 5, 6]
// Rest parameters
function sum(...theArgs) {
return theArgs.reduce((previous, current) => {
return previous + current;
});
}
25- Modules: JavaScript modules are a way to share and reuse code
across files.
// lib/math.js
export function sum(x, y) {
return x + y;
}
class Animal {
constructor(name) {
this.name = name;
}
speak() {
console.log(this.name + ' makes a noise.');
}
}
28- Iterators and Generators: Iterators are objects that know how to
access items from a collection one at a time, while keeping track of
its current position within that sequence. Generators are a special
class of functions that simplify the task of writing iterators.
function* idMaker(){
let id = 0;
while(true) {
yield id++;
}
}
console.log(iterator.next().value); // Output: 1
console.log(iterator.next().value); // Output: 2
29- Map, Filter, and Reduce: map, filter, and reduce are all array
methods in JavaScript that provide a functional programming style.
31- NaN: NaN is a special value that stands for "Not a Number". It is
used to indicate an undefined or unrepresentable value.
console.log(Math.sqrt(-1)); // NaN
32- Null and Undefined: Both null and undefined are special values in
JavaScript. undefined means a variable has been declared but has not
yet been assigned a value. null is an assignment value. It can be
assigned to a variable to represent no value or no object.
let test;
console.log(test); // undefined
test = null;
console.log(test); // null
33- Truthy and Falsy: Every value in JavaScript has an inherent boolean
value. When that value is evaluated in the context of a boolean
expression, we say that value is either truthy or falsy.
let x = "5";
console.log(x + 1); // "51"
console.log(+x + 1); // 6
const obj = { a: 1 };
obj.b = 2;
console.log(obj); // { a: 1, b: 2 }
function greeting(name) {
console.log('Hello ' + name);
}
function processUserInput(callback) {
let name = prompt('Please enter your name.');
callback(name);
}
processUserInput(greeting);
let animal = {
eats: true
};
let rabbit = Object.create(animal);
console.log(rabbit.eats); // true
40- Web APIs: Web APIs provide the functionality to create a dynamic,
interactive web application. These APIs include DOM manipulation, Fetch
API, Geolocation API, Web Storage, and more.
fetch('https://api.github.com/users/github')
.then(response => response.json())
.then(data => console.log(data));
41- this Keyword: this keyword refers to the object that is executing
the current function.
const person = {
name: 'John',
greet: function() { console.log('Hello, ' + this.name); }
};
person.greet(); // 'Hello, John'
setTimeout(() => {
console.log('Runs after 2 seconds');
}, 2000);
setInterval(() => {
console.log('Runs every second');
}, 1000);
44- Local Storage: Local Storage allows you to access a local Storage
object. Data stored persistently and isn't sent with every server
request.
localStorage.setItem('myKey', 'myValue');
let data = localStorage.getItem('myKey');
console.log(data); // 'myValue'
sessionStorage.setItem('sessionKey', 'sessionValue');
let data = sessionStorage.getItem('sessionKey');
console.log(data); // 'sessionValue'
<script>
let div = document.getElementById('myDiv');
let customData = div.dataset.myAttr;
console.log(customData); // 'hello'
</script>
let a = 5;
let b = 10;
(function() {
console.log("This is an IIFE!");
})();
49- Strict Mode: Strict mode makes several changes to normal JavaScript
semantics. It eliminates some JavaScript silent errors by changing them
to throw errors.
'use strict';
x = 3.14; // This will cause an error because x is not defined
function multiply(a, b = 1) {
return a * b;
}
console.log(multiply(5, 2)); // 10
console.log(multiply(5)); // 5
let pos = 0;
let box = document.getElementById("animate");
55- JavaScript BOM (Browser Object Model): The BOM allows JavaScript to
"talk to" the browser, it includes objects like navigator, history,
screen, location and document which is also the entry point into the
web page's content.
56- Web Workers: Web Workers are a simple means for web content to run
scripts in background threads.
fetch('https://api.github.com/users/github')
.then(response => response.json())
.then(data => console.log(data));
59- Object Property Shorthand: In situations where the key and the
value that you're assigning to the key in the object you're creating
are the same, you can use a shorthand to create properties.
61- WeakSet: The WeakSet object lets you store weakly held objects in a
collection.
66- Async Iterators and Generators: They are enable the async functions
to be paused in the middle, one line at a time, and resumed only when a
value is ready, perfect for working with streams and other asynchronous
data sources.
let height = 0;
console.log(height ?? 100); // 0
customElements.define('my-element', MyElement);
72- Shadow DOM: Encapsulates style and structure for web components.
this.handleClick = this.handleClick.bind(this);
74- GlobalThis: A universal way to access the global this value (aka
global object) across environments.
76- Array at() method: Allows to get the element at a given index, with
support for negative indices.
match (value) {
when ({ a: 1, b }) -> b
else -> throw new Error('not matched')
}
function multiply(a) {
return function(b) {
return a * b;
};
}
82- Currying with lodash: The curry function from lodash can be used
for currying.
const _ = require('lodash');
function multiply(a, b, c) {
return a * b * c;
}
function add(a) {
return a + 1;
}
function multiply(b) {
return b * 2;
}
if (n <= 2) {
return 1;
}
console.log(fibonacci(10)); // Output: 55
85- Proxy traps: Proxy traps are the methods that can be defined on the
handler object to customize the behavior of the proxied object.
const handler = {
get(target, property) {
console.log(`Accessed ${property}`);
return target[property];
},
};
function* generateNumbers() {
let number = 0;
while (true) {
yield number++;
}
}
console.log(numberGenerator.next().value); // Output: 0
console.log(numberGenerator.next().value); // Output: 1
87- Private class fields: Private class fields are class fields that are
scoped to the class and cannot be accessed outside of it.
class Person {
#name;
constructor(name) {
this.#name = name;
}
getName() {
return this.#name;
}
}
const user = {
name: 'John',
address: {
city: 'New York',
},
};
90- Web Workers: Web Workers allow running JavaScript code in the
background, off the main thread, to improve performance and
responsiveness.
// Main thread
const worker = new Worker('worker.js');
92- Custom iterable objects: You can create custom iterable objects by
implementing the iterator protocol.
const iterable = {
items: ['a', 'b', 'c'],
[Symbol.iterator]() {
let index = 0;
return {
next: () => {
if (index < this.items.length) {
return { value: this.items[index++], done: false };
}
return { done: true };
},
};
},
};
return descriptor;
}
class Calculator {
@log
add(a, b) {
return a + b;
}
}
function logMessage() {
console.log('Message logged');
}
function saveData() {
console.log('Data saved');
}
const obj = {
name: 'John',
age: 30,
};
Object.freeze(obj);
obj.age = 40; // Assignment is ignored in strict mode or throws an error in
non-strict mode
console.log(obj.age); // Output: 30
const obj = {
name: 'John',
age: 30,
};
Object.seal(obj);
delete obj.age; // Deletion is ignored
obj.name = 'Jane'; // Property can be modified
obj.gender = 'Male'; // Property addition is ignored
const obj = {
name: 'John',
age: 30,
};
Object.preventExtensions(obj);
obj.name = 'Jane'; // Property can be modified
obj.gender = 'Male'; // Property addition is ignored
99- FlatMap: The flatMap method combines the map and flat methods,
allowing mapping each element to a new array and then flattening the
resulting arrays into a single array.
const entries = [
['name', 'John'],
['age', 30],
];
const sentence = 'The quick brown fox jumps over the lazy dog.';
const newSentence = sentence.replaceAll('the', 'a');
console.log(newSentence); // Output: The quick brown fox jumps over a lazy
dog.
const obj = {
name: 'John',
};
105- File API: The File API provides a way to interact with files on the
user's device using JavaScript.
reader.readAsText(file);
});
const options = {
root: null,
rootMargin: '0px',
threshold: 0.5,
};