Concepts for JavaScript
JavaScript is a dynamic, high-level programming language primarily used for web development. It was originally created by Brendan Eich at Netscape in 1995. JavaScript is known for its versatility and is predominantly used for client-side scripting within web browsers to create interactive and dynamic web pages. It supports object-oriented, imperative, and functional programming styles. Key features include its ability to manipulate the HTML DOM (Document Object Model) to dynamically update content, handle events, and interact with users. JavaScript is also commonly used on the server-side (with Node.js) for building scalable and real-time applications, making it one of the most widely used programming languages in the world.
Print Text
console.log('Hello World!'); console.log("Hello World!");Comments
// one line comment /* multi line comment */
Variables
var carCount = 2; let name = 'Joe'; const isPurple = true;
Data Types
let carCount = 2; let age = 15; let seaLevel = -10000; let usBudget = 11000000000; let lightSpeed = 11799312874; let myGPA = 3.45; let piValue = 3.14159265; let lastLetter = 'Z'; let isMale = true; let myName = 'Joe';
Math Op
const carCount = 6; const truckCount = 3; const total = carCount + truckCount; console.log(total); const subtract = carCount - truckCount; console.log(subtract); const multiple = carCount * truckCount; console.log(multiple); const divisible = carCount / truckCount; console.log(divisible); // performs division and gets remainder which is 0 const modulo = carCount % truckCount; console.log(modulo);
Math Functions
const power = Math.pow(3.0, 6.0); console.log(power); const root = Math.sqrt(16.0); console.log(root); const floorVal = Math.floor(3.14); console.log(floorVal); const ceilVal = Math.ceil(4.3); console.log(ceilVal); const roundVal = Math.round(3.4); console.log(roundVal); // random number from 0 to 100 const ranNum = Math.floor(Math.random() * 100) + 1 console.log(ranNum);
If/Else
const carCount = 6; if (carCount > 3) { console.log('More than three cars'); } else if (carCount === 3) { console.log('Equal to three cars'); } else { console.log('Less than three cars'); }Ternary
const carCount = 3; const result = (carCount > 2) ? "Yes" : "No"; console.log(result);
Switch
const carCount = 3; switch (carCount) { case 1: console.log('One car'); break; case 2: console.log('Two cars'); break; case 3: console.log('Three cars'); break; default: console.log('More than three'); }Functions
function handleCars(cars, wheels) { const total = cars * wheels; return total; } const result = handleCars(3, 4); console.log(result);Interpolation
const name = 'Joe'; const car = 'Mazda'; const result = `${name} drives a ${car}`; console.log(result);Type Casting
function squareA(length) { const result = Math.pow(length, 2); return result.toString(); } const squareL = "4"; const convertedVal = parseInt(squareL); const area = squareA(convertedVal); console.log(area);Date and Time
// get time in milliseconds const milliTime = Date.now(); console.log(milliTime); // current year const currentYear = new Date().getFullYear(); console.log(currentYear); // create new Date obj const utcDate = Date.UTC(2023, 11, 20, 3, 0, 0); const fullDate = new Date(); const date = new Intl.DateTimeFormat(); // formats date in a more traditional format const formatedDate = date.format(fullDate); console.log(formatedDate);
Classes
class Cars { constructor() { this.carList = []; } addCar(name) { this.carList.push(name); } removeFirst() { this.carList.shift(); } getFirstVal() { if (this.carList.length) { return this.carList[0]; } return ''; } } const newList = new Cars(); newList.addCar("Honda"); newList.addCar("Mazda"); newList.addCar("Toyota"); newList.removeFirst(); const firstCar = newList.getFirstVal(); console.log(firstCar);Inheritance
class User { username; password; constructor(username, password) { this.username = username; this.password = password; } } class Admin extends User { constructor(username, password, id) { super(username, password); this.id = id; } getAdminID() { return this.id } getUsername() { return this.username } } const newAdmin = new Admin( "alpha0", "pw1", "1FE" ) console.log(newAdmin.getUsername()); console.log(newAdmin.getAdminID());Method Overload
// No Native Support or Implementation
Abstract Class
class Animation { constructor() { if(this.constructor == Animation) { throw new Error( "Cannot initiate abstract class" ); }; if(this.walk == undefined) { throw new Error( "walk method not implemented" ); }; if(this.run == undefined) { throw new Error( "run method not implemented" ); }; if(this.idle == undefined) { throw new Error( "idle method not implemented" ); }; } } class Human extends Animation { walk() { console.log("Human walks"); } run() { console.log("Human runs"); } idle() { console.log("Human idles"); } } class Zombie extends Animation { walk() { console.log("Zombie walks"); } run() { console.log("Zombie runs"); } idle() { console.log("Zombie idles"); } } const player = new Human(); player.walk(); const zombie = new Zombie(); zombie.run();Static Class
class Helper { static CircleA(radius) { const power = Math.pow(radius, 2); return 3.14 * power; } static SquareA(length) { return Math.pow(length, 2); } } const circle = Helper.CircleA(3); console.log(circle); const square = Helper.SquareA(4); console.log(square);Arrays/Lists
const names = ['Joe', 'Sam', 'David']; names[1] = "Tom"; const name = names[1]; const numItems = names.length; console.log(name); console.log(numItems);
Array Methods
const cars = ['Honda', 'Mazda', 'Toyota']; // creates new array to newlist from index 1 const newList = cars.slice(1); console.log(newList); // cuts original list at index 1 to returnVal const returnVal = cars.splice(1); console.log(returnVal); console.log(cars); // add Ford to end of array cars.push('Ford'); console.log(cars); // removes last element Ford from array cars.pop(); console.log(cars); // adds Kia to beginning of array cars.unshift('Kia'); console.log(cars); // removes first element of array Kia cars.shift(); console.log(cars); // sorts array in alphabetical order cars.sort(); console.log(cars);Concatenation
const carsListKr = ["Kia", "Hyundai", "Daewoo"]; const carsListJp = ["Honda", "Mazda", "Toyota"]; const combined = [...carsListKr, ...carsListJp]; console.log(combined[1]); console.log(combined[4]);
Sort Method
const ages = [5, 3, 1, 6, 7, 4, 19]; ages.sort(); console.log(ages);
Objects
const user = { first: 'Joe', last: 'Doe', age: 23, retired: false, carBrands: ['Mazda', 'Toyota'], fullName: function () { return `${this.first} ${this.last}` } } console.log(user.first); console.log(user.carBrands[1]); console.log(user.fullName());Maps (Key/Value)
const carMap = new Map(); carMap.set("Joe", "Toyota"); carMap.set("Bob", "Mazda"); carMap.set("Tom", "Ford"); console.log(carMap.get("Tom")); carMap.delete('Tom'); console.log(carMap.keys());Sets
const cars = new Set(); cars.add("Mazda"); cars.add("Toyota"); cars.add("Honda"); console.log(cars.has("Honda")); cars.delete("Honda"); console.log(cars.has("Honda"));Stack
const cars = []; cars.push('Mazda'); cars.push('Toyota'); cars.push('Honda'); console.log(cars[cars.length - 1]); cars.pop(); console.log(cars[cars.length - 1]);Queues
const cars = []; cars.push('Mazda'); cars.push('Toyota'); cars.push('Honda'); console.log(cars[0); cars.shift(); console.log(cars[0]);Linked List
class Node { constructor(value) { this.value = value; this.next = null; } } class LinkedList { constructor() { this.head = null; } add(value) { const newNode = new Node(value); if (this.head === null) { this.head = newNode; } else { let current = this.head; while (current.next) { current = current.next; } current.next = newNode; } } returnHead() { return this.head?.value; } traverse() { let current = this.head; while(current) { console.log(current.value); current = current.next; } } } const carList = new LinkedList(); carList.add("Mazda"); carList.add("Toyota"); carList.add("Honda"); console.log(carList.returnHead()); carList.traverse();Graphs
class Graph { constructor() { this.graphMap = {}; } addNode(val) { this.graphMap[val] = []; } addVertices(node1, node2) { if(!this.graphMap[node1]) { this.graphMap[node1] = []; } if(!this.graphMap[node2]) { this.graphMap[node2] = []; } this.graphMap[node1].push(node2); this.graphMap[node2].push(node1); } breadthTraverse(start) { const queue = [start]; const visited = {}; visited[start] = true; while(queue.length) { const val = queue.shift(); console.log(val); const tempArr = this.graphMap[val]; for (let i = 0; i < tempArr.length; i++) { if (!visited[tempArr[i]]) { queue.push(tempArr[i]); visited[tempArr[i]] = true; } } } } depthTraverse(start) { const stack = [start]; const visited = {}; visited[start] = true; while(stack.length) { const val = stack.pop(); console.log(val); const tempArr = this.graphMap[val]; for (let i = 0; i < tempArr.length; i++) { if (!visited[tempArr[i]]) { stack.push(tempArr[i]); visited[tempArr[i]] = true; } } } } } const newGraph = new Graph(); newGraph.addNode("a"); newGraph.addVertices("a", "b"); newGraph.addVertices("a", "c"); newGraph.addVertices("b", "d"); newGraph.addVertices("b", "e"); newGraph.addVertices("d", "f"); newGraph.addVertices("d", "g"); newGraph.addVertices("d", "h"); newGraph.addVertices("e", "i"); newGraph.addVertices("e", "j"); newGraph.breadthTraverse("a"); newGraph.depthTraverse("a");For Loops
let names = ['Joe', 'Alex', 'Bob']; for (let i = 0; i < names.length; i++) { console.log(names[i]); }While Loops
const carList = ['Mazda', 'Toyota', 'Honda']; while (carList.length) { console.log(carList[0]); carList.shift(); } console.log(carList.length);Loop Breaks
const cars = ['Toyota', 'Honda', 'Mazda']; for (let i = 0; i < cars.length; i++) { if (cars[i] === 'Honda') { console.log(`Found at index ${i}`); break; } console.log(`Visted index ${i}`); }Recursion
function getSum (arr) { if (arr.length === 0) return 0; const firstVal = arr.shift(); console.log(firstVal); return firstVal + getSum(arr); } const testArr = [1, 2, 4, 5] const sum = getSum(testArr); console.log(sum);Regex Words
const pattern = /\w+/i; const phrase = "I am legend"; const result = phrase.match(pattern); console.log(result[0]);
Regex Numbers
const pattern = /\d+/i; const phrase = "I am 23"; const result = phrase.match(pattern); console.log(result[0]);
Regex Test
const name = 'Bob Lee'; const regex = new RegExp('Lee*', 'g'); const result = regex.test(name); console.log(result);Regex Characters
const pattern = /\#+\w?/g; const phrase = "##I am legend##"; const result = phrase.match(pattern); console.log(result[0]);