Public
Edited
Aug 4, 2022
Insert cell
Insert cell
Insert cell
Insert cell
{
const userFirstName = 'Rory';
const userBirthYear = 1986;
const userBirthDate = '1986-01-21';
let userAge = 33;
userAge = 34;
let message = 'Now you know variables!';
return message;
}
Insert cell
Insert cell
{
let name = 'Peter';
let age = 32;
let score = 7.68;
let knowsJS = true;
let job = null;
return 'Now you know primitives!';
}
Insert cell
Insert cell
{
const user = {
age: 29,
username: 'dick',
firstName: 'Dick',
lastName: 'van Dyke',
};
let property = 'username';

return user[property];
}
Insert cell
Insert cell
Insert cell
{
// const hobbies = ['JavaScript', 'Music', 'Fishing'];
const randomList = [1, 2, 'Tea', { username: 'Paul', age: 45 }];
// read from array
const firstEntry = randomList[1];
// read from array and then read from the object it returns
let thingIWantToRead = 'age';
return randomList[3][thingIWantToRead];
}
Insert cell
Insert cell
Insert cell
{
let numberOfUsers = 12;
numberOfUsers = numberOfUsers / 2 * 2 + 5;
return numberOfUsers;
}
Insert cell
Insert cell
{
const inputUsername = ' Paul ';
const lowercaseUsername = inputUsername.toLowerCase();
const trimmedUsername = lowercaseUsername.trim();
const resultUsername = inputUsername.toLowerCase().trim();
const pathString = 'users/dick/friends';
const pathList = pathString.split('/');
const sentence = 'I love bananas';
const replacedSentence = sentence.replace('bananas', 'apples');
const link = 'https://eclecticiq.com';
const user = {
username: 'dick',
};
const message = `Dear ${user.username}, please check out this link: ${link}.`;
return message;
}
Insert cell
Insert cell
{
const user = {
username: 'dick',
age: 34,
name: 'Dick van Dyke',
};
user.username = 'john'; // change a value
delete user.age; // remove a property
user.hobbies = ['Music', 'JS']; // add a property
const propertiesOfUSer = Object.keys(user);
const valuesOfUSer = Object.values(user);
return valuesOfUSer;
}
Insert cell
Insert cell
{
const animals = ['ant', 'bison', 'camel', 'duck', 'elephant'];
// const selectedAnimals = animals.slice(1, 3);
// animals[0] = 'spider';
// const indexOfDuck = animals.indexOf('duck');
// const hasDuck = animals.includes('spider');
// animals.push('spider'); // add last item
// animals.pop(); // remove last item
// animals.unshift('cow'); // add to beginning
// animals.shift(); // remove first item
return animals;
}
Insert cell
Insert cell
{
const names = ['John', 'Peter'];
const others = ['Jack', 'Jill', 'John'];
const together = [...names, ...others];
return together;
}
Insert cell
{
const user = { name: 'Paul', age: 30 };
const extraUserData = { hobbies: ['Fishing', 'JavaScript'] };
const oldUserData = { ...user, ...extraUserData };
const newUserData = { name: 'Stephanie', age: 31 };
const completeUserData = {
...oldUserData,
...newUserData,
};
return completeUserData;
}
Insert cell
Insert cell
{
// destructure objects
const entity = {
id: 1,
title: 'Bad guy',
type: 'threat-actor',
createdBy: {
id: 5,
username: 'paul',
workspaces: [1,2,3,4]
}
};

// this can be replaced:
// const id = entity.id;
// const type = entity.type;
// const title = entity.title;
// by this:
const { id: entityId, type, title } = entity;
// this can be replaced:
// const userId = entity.createdBy.id;
// const workspaces = entity.createdBy.workspaces;
// const username = entity.createdBy.username;
const { createdBy: { id: userId, workspaces, username } } = entity;
console.log('entityId:', entityId, 'userId:', userId);
if(userId) {
console.log(username);
}
return workspaces;
// destructure arrays
const types = ['threat-actor', 'indicator', 'incident'];
const [a, b, c] = types;
return a;
}
Insert cell
Insert cell
{
let myVar = 1;
// myVar = 'paul';
// myVar = {};
// return typeof myVar;
const url = 'users/1';
const splittedUrl = url.split('/');
const userId = splittedUrl[1];
// return Number(userId);
const value = { id: 1 };
return Boolean(value);
}
Insert cell
Insert cell
{
const user = { id: 4, name: 'paul', age: 27 };
// anything inside an if statement, is auto converted to a Boolean
// if(user) {
// return user;
// } else {
// return 'No user found';
// }
// if(user.age < 18) {
// return 'Access denied.';
// } else if (user.age > 65) {
// return 'User too old.';
// } else {
// return 'Access granted';
// }
// assigning a variable if a condition is true
// let isUnderage = null;
// if(user.age < 18) {
// isUnderage = true;
// } else {
// isUnderage = false;
// }
// can be replaced with this:
const isUnderage = user.age < 18 ? 'Yes' : 'No';
return isUnderage;
}
Insert cell
Insert cell
{
const userIdFromUrl = '1'; // number inside a string
const lookForUserId = 1;
// don't do this, JS will convert types for you if the types are not the same
// return userId == lookForUserId;
// return userId != lookForUserId;
// do this:
return Number(userIdFromUrl) === lookForUserId;
}
Insert cell
Insert cell
{
// declare a function with the 'function' keyword
function changeUsername(user, newUsername) {
return {
...user,
username: newUsername,
};
}
// implementation
const user = {
username: 'paul',
name: 'Paul Fitzgerald',
age: 32,
};
const updatedUser = changeUsername(user, 'paulfitz');
// declare function with arrow notation
const setUsername = (user, newUsername) => ({
...user,
username: newUsername,
});
// implementation
const user2 = {
username: 'dick',
name: 'Dick Duck',
age: 44,
};
const updatedUser2 = setUsername(user2, 'dickduck');
// short hand for arrows
const mutateUsernameShort = user => user.username = 'paul';
const mutateUsernameLong = (user) => {
user.username = 'paul';
};
// pure functions only read from their arguments, and don't mutate any data outside
let user3 = { id: 3, username: 'paul' };
// not pure
const mutateUsername = (username) => {
// it reads from outside scope, and mutates this data
user3.username = username; // side-effect
};
mutateUsername('dick');
// pure
const updateUsername = (user, newUsername) => {
// it only reads from arguments, and doesn't mutate anything: it returns a new object
return {
...user,
username: newUsername,
};
};
const updatedUser3 = updateUsername(user3, 'paul');
// return updatedUser3;
// these two are the same:
const giveMeUser = () => ({ id: 5, name: 'john' });
const giveMeUser2 = () => {
return { id: 4, name: 'pete' };
};
const myUser = giveMeUser(); // myUser is now { id: 5, name: 'john' }
const myOtherUser = giveMeUser2(); // myUser is now { id: 4, name: 'pete' }
}
Insert cell
Insert cell
Insert cell
{
// Array.filter is a utility that allows to filter a list
// it will iterate over each item of the list, every time the callback
// returns true, the item will be added to the new list, else it will be lost
const names = ['ruslan', 'archie', 'ion', 'alex', 'mihai', 'serghei'];
const namesWithI = names.filter(name => name.includes('i'));
// return namesWithI;
// we have a list of users
const users = [{ id: 321, name: 'pete'}, { id: 567, name: 'john' }, { id: 900, name: 'dick' }];
// Array.map is a utility that allows you to transform arrays
const userIds = users.map(user => user.id);
// return userIds;
// filter and then map:
const usernamesWithI = users
.filter(user => user.name.includes('i'))
.map(user => user.name);
// return usernamesWithI;
let list = [1, 3, 5, 6, 7];
// mapping function that takes a number, and returns the number times 10
const timesTen = (number) => {
return number * 10;
}
// perform the mapping on our array
const timesTenList = list.map(timesTen);
// return timesTenList;
// shorthand for mapping
const timesTenList2 = list.map(number => number * 10);
// let list = ['a', 'b', 'c', 'd'];
// input2.value = '';
// list.forEach(value => {
// input2.value = `${input2.value} + ${value}`;
// });
// let iteration = 0;
// setInterval(() => {
// iteration += 1;
// input.value = iteration;
// }, 1000);
// version 1
// function callback() {
// console.log('called');
// }
// setInterval(callback, 1000);

// // version 2
// setInterval(function() {
// console.log('called');
// }, 1000);
// // version 3
// setInterval(() => {
// console.log('called');
// }, 1000);
}
Insert cell
Insert cell
{
// returns a 'package' which will resolve after 2 seconds
const myPromise = new Promise(resolve => {
setTimeout(() => {
resolve(`done ${Date.now()}`);
}, 2000);
});
// after it resolves return the result
return myPromise.then(result => {
return result;
});
// PROMISE MAGIC AHEAD
// mock a network request by returning succes or error
const getUserRequest = (userId) => new Promise((resolve, reject) => {
// set a timeout of 2000 ms
setTimeout(() => {
// generate a random number: 1 or 0
// const randomResult = Math.round(Math.random());
const randomResult = 1;
if(randomResult === 1) {
// if 1, resolve: promise is a success
resolve({ username: 'pete', id: userId, groupId: 10 });
} else {
// if 0, reject: promise is a error
reject(`${Date.now()}`);
}
}, 2000);
});

const getGroupRequest = (groupId) => new Promise((resolve, reject) => {
const callback = () => {
// const coinFlip = Math.round(Math.random()); // returns 0 or 1, at random
const coinFlip = 1;
if(coinFlip) {
resolve({ id: groupId, name: 'analysts' });
} else{
reject('404 Not found');
}
};

setTimeout(callback, 1000);
});
// get user with id 10 and then group with the groupId
return getUserRequest(10)
.then(user => getGroupRequest(user.groupId))
.then(group => console.log(group));
}
Insert cell
Insert cell
Insert cell
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more