Categories
JavaScript

JavaScript tips

A collection of useful JavaScript functions and handy tips / study notes

forEach

                    
// forEach
const x = [1,3,4,66,77];
x.forEach(v => {log (v*2)})

Map

                    
// Map
const x = [1,3,4,5,6,7,87]
let f = x.map(x=>x*2);
log(f);

Filter

                    
// Filter
const ages = [1,3,4,5,6,7,87];
let filteredAges = function(ages){
return (ages > 5);
}
let f = ages.filter(filteredAges);
log(f);

Invoking a class

                    
// Create Animal.js
export default class Animal{
constructor() {
console.log(“i am an animal”);
}
getClassType() {
return “Animal”;
}
}
// In Index.js
// import Animal from ‘./Animal’;
var animal = new Animal();
log(animal.getClassType()

Clickable div – linked to a js function

Use a JavaScript function on a div – (flex)
                    
function klik1() {
document.getElementById(“moo1″).innerHTML=”M”;
}

Use JavaScript to fetch data

Use Stringify to convert JSON to text

API – JS – HTML Demo

We use JavaScript to fetch from an API and create a new element in the html for each character in the API response

                    
const fetchapi = fetch(“https://rickandmortyapi.com/api/character/”)
.then(response => response.json())
.then(characters => showCharacters(characters.results));
//
const showCharacters = characters => {
const charactersDiv = document.querySelector(“#rmc”);
characters.forEach(character => {
const characterElement = document.createElement(‘p’);
characterElement.innerText = `Character Name: ${character.name}`;
charactersDiv.append(characterElement); })};
                    
<!DOCTYPE html>
<html lang=”en”>
<head>
<meta charset=”UTF-8″>
<meta http-equiv=”X-UA-Compatible” content=”IE=edge”>
<title>Flex</title>
<meta name=”viewport” content=”width=device-width, initial-scale=1″>
<script src=”https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js”></script>
<script src=”https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js”></script>
<link rel=”stylesheet” href=”style.css”>
</head>
<body>
<div class=”container-fluid”>
<h1>My API Demo Page</h1>
<script src=”app.js” defer=”true”></script>
<div id=”rmc”></div>
</div>
</body>
</html>
js-api-html-demo