This document provides an overview of core JavaScript concepts including variables, data types, conditional statements, functions, objects, arrays, scope, callbacks, and events. It explains variable declaration and initialization, if/else statements, for loops, function definition and invocation, object properties, arrays of objects, scope, callbacks, and common DOM events. It also covers ES6 features like let, const, arrow functions, and classes as well as DOM manipulation methods like getElementById, querySelector, and querySelectorAll.
This document provides an overview of core JavaScript concepts including variables, data types, conditional statements, functions, objects, arrays, scope, callbacks, and events. It explains variable declaration and initialization, if/else statements, for loops, function definition and invocation, object properties, arrays of objects, scope, callbacks, and common DOM events. It also covers ES6 features like let, const, arrow functions, and classes as well as DOM manipulation methods like getElementById, querySelector, and querySelectorAll.
Core Building Blocks Scope this a special keyword used by a callback to reference its own property
function scoping - global & local obj.celebrate_birthday = function() {
variables Hoisting - declaring variable before defining will output undefined instead of not this.age++; var a = 5; // for storing a number in a variable defined console.log(this.name + " is now " + this.age + " years old"); var b = "hello world"; //for storing a string in a variable var whoamI; } var c = [1,3,5,7,8]; //for storing an array in a variable console.log ( whoamI ); whoamI = 5; Event Listeners if/else HTML if( ...condition... ) { ES6 <button id='myBtn'>My Button</button> // codes that should be executed if the condition is true let & const <p id='demo'>...</p> } block-scoping Javascript else if( ...condition... ) { document.getElementById("myBtn").addEventListener("click", // codes that should be executed if the second condition is true Callbacks function() { } store a function in a variable document.getElementById("demo").innerHTML = "Hello World"; else { let c = function(name = "Michael") { }); ... console.log('my name is', name); other functions in getting an element aside from "id" (can be also by "class", or } return name.length; the "tag" itself) } for loops console.log( c("John") ); Main Events for(var i=0; i<10; i++) { change - an HTML element has been changed console.log(i); //prints a number from 0 to 9 passing a function to a function - function that is passed as an argument for the click - the user clicks an HTML element } function mouseover - the user moves the mouse over an HTML element const sum = function(a, b) { mouseout - the user moves the mouse out/away from an HTML element functions return a+b; keydown - the user presses a keyboard key function abc(x, y, z) { } load - the browser finishes loading the page ... function performOperation(num1, num2, operation){ submit - a form is submitted return x+y+z; let result = operation(num1, num2); https://www.w3schools.com/jsref/dom_obj_event.asp } console.log('result is', result); return result; Using Inspect Element, you can also see which html elements have event EcmaScript - scripting language } listeners attached. For example, see performOperation(3, 5, sum); https://umaar.com/dev-tips/24-view-event-listeners/ Objects (associative array) key value pair having a function return a function querySelector is used to grab the first specific element specified, only returns the var teacher = { name: 'Michael', city: 'Seattle', state: 'Washington' }; function abc(a, b){ first specific element console.log( teacher.name ); return function() { document.querySelector(CSS selectors); teacher.city = 'Bellevue'; console.log('hello'); document.querySelector("h1"); //gets the first <h1> element in the console.log( teacher.city ); //this will now log Bellevue return a+b+10; document teacher.favorite_sport = "soccer"; } document.querySelector("p.example"); //gets the first <p> element in console.log(teacher); //this would now log all the key values storied in } the document with class 'example' the variable teacher let result = abc(5, 10); document.querySelector("#title").innerHTML = "New Title"; //gets the let z = result(); element with an id of title and updates the HTML array of objects console.log(z); var students = [ { name: "John", age: 25 }, querySelectorAll grab ALL elements specified by the CSS selectors { name: "KB", age: 21 }, note that you can also attach a callback function to a key let x = document.querySelectorAll("p.red"); // gets all <p> elements in { name: "Jomar", age: 25 } ]; var obj = { the document with class red for(var i=0; i<students.length; i++) { name: 'Michael', for(let i=0; i<x.length; i++){ console.log( "Student Name: " + students[i].name + " - Age: " + age: 39, x[i].innerHTML = "hello"; //updates each innerHTML students[i].age); hello: function() { } } console.log('Michael says hello!'); // for(student of students) { } let y = document.querySelectorAll("h2, p, img"); //gets all the <h2>, <p>, console.log( "Student Name: " + student.name + " - Age: " + }; and <img> elements student.age); obj.hello(); // this executes the function inside the hello property and for(let i=0; i<y.length; i++){ } logs 'Michael says hello!' y[i].style.backgroundColor = "blue"; //updates each style.backgroundColor to be blue } this.secret = "Hero"; //again no private methods nor private variables let x = "Doritos"; // for ES6 function abc(...){ let z = document.querySelectorAll("div > p"); //gets every <p> element } //things that do wonderful stuff with a, x, and some other stuff where the parent is a <div> element } return ... for(let i=0; i<x.length; i++){ let obj1 = new MyFirstClass("J1"); } z[i].style.backgroundColor = "green"; let obj2 = new MyFirstClass("J2"); function edf(...){ } //things that do wonderful stuff with variables a, x, and some other Inheritance using extend stuff OOP (Object Oriented Programming) super() can call the parent class return ... Javascript ES5 OOP no built in constructor, no class class Shape { } function MyFirstClass(name){ constructor(x, y) { return { abc: abc, edf: edf }; this.name = name; //put all public attributes with this. this.x = x; })(); this.property = "I am the first property! Woohoo"; //put all public this.y = y; NOTE: need to access some global variables such as the window object, or the attributes with this. } jQuery object, or the document itself? simply pass these objects as arguments var secret = "Hacker"; //this is a private variable } var unique_name = (function(window, jQuery, document){ console.log('I get called for each instance of this class!'); class Circle extends Shape { let a = 35; //this is a public method constructor(x, y, r) { let x = "Doritos"; this.update_property = function(property){ super(x, y); function abc(...){ this.property = property; this.r = r; //things that do wonderful stuff with a, x, and some other } } stuff //put any private method in a variable area() { return ... var update_secret = function(){ return this.r * 2 * Math*PI; } secret = "Hero"; } function edf(...){ } } //things that do wonderful stuff with variables a, x, and some } other stuff var obj1 = new MyFirstClass("J1"); static method is something you can call without instantiating the class return ... var obj2 = new MyFirstClass("J2"); class Person { } static createAnonymous(gender){ return { abc: abc, edf: edf }; prototype allows you to add new properties to object constructors return ""; //sample code })(window, jQuery, document); function Circle(size){ } this.size = size; } Closure is where the function inside the function still remembers variables of the } let anonymous = Person.createAnonymous("male"); parent function, even when the program left/existed the parent function Circle.prototype.updateSize = function(new_size) { function abc(){ this.size = new_size; Assignment by reference var name = "Michael"; } call stack creating a string or a number and storing these in a variable function sayHello(){ var circle1 = new Circle(5); heap stack store an array, an object, a function, or a class in a variable console.log(name); let a = 5; //creates this value in the call stack } Javascript ES6 OOP use the word class. a private variable NOR private methods let b = a; //duplicates the value stored in a and assigns that to b return sayHello; are not really supported. prototype supported b = b + 5; //b is updated to be 10. } class MyFirstClass { console.log(a, b); //logs 5 and 10 let result = abc(); //ES6 has a constructor support! let c = "Michael"; //creates this value in the call stack console.log(result); //what would get logged here??? constructor(name) { let d = c; //duplicates the value stored in c and stores that to d // this.name = name; d = d + " Choi"; //d is updated as "Michael Choi" console.log(result()); //what would get logged now? this.property = "I am the first property! Woohoo"; console.log(c,d); //logs "Michael" and "Michael Choi" this.secret = "Hacker"; //again in ES6, private variables are not really let x = [1,3,5]; //creates this value in the heap stack Arrow function is a compact alternative to a traditional function expression supported let y = x; //y also points to that value in the heap stack //traditional function console.log('I get called for each instance of this class!'); y.push(7); //at where y is pointed to, it pushes a new value called 7 function abc(a) { } console.log(x, y); //logs [1,3,5,7] twice! return a+100; //public method } update_property(property){ Immediate Function put all the code inside a function, then immediately execute //one way of using an arrow function this.property = property; that function. a function that's invoked immediately abc = (a) => { } namespace conflict conflict of variable names or function names return a+100; //another public method var unique_name = (function(){ } update_secret(){ let a = 35; //if the function is simply returning a value, the curly brackets and the fs.readFile('index.html', 'utf8', function (errors, contents){ Node Modules return statement is optional response.writeHead(200, {'Content-Type': 'text/html'}); // send To include a module, use the require() function with the name of the module abc = (a) => a+100; data about response Requiring a Node module allows you to use the module.exports object of another //the parenthesis is even optional! response.write(contents); // send response body file! abc = a => a+100; response.end(); // finished! my_module.js file: }); module.exports = { var obj = { } greet: function(){ name: 'coding', // request didn't match anything: console.log("we are now using a module!"); b: (word) => { else { }, console.log(this.name, word); response.writeHead(404); add: function(num1, num2){ } response.end('File not found!!!'); console.log("the sum is:", num1 + num2); } } } obj.b('is fun'); }); } // tell your server which port to run on app.js file: Asynchronous Callbacks functions running in parallel with other functions server.listen(6789); var my_module = require('./my_module'); let a = (function task1() { // print to terminal window my_module.greet(); function abc() { console.log("Running in localhost at port 6789"); my_module.add(5,6); console.log('hello'); return 100; var server = http.createServer(function (request, response){...} require() method looks for the modules located in a folder called node_modules. } To tell require() to look in the current directory (i.e. the folder that the file is abc(); Configuring the root route: located in) we have to include "./" in front of the file path. "./" (dot-slash) is the console.log('world'); if(request.url === '/') { file path for the current directory return 5; fs.readFile('index.html', 'utf8', function (errors, contents){ my_module.js file: })(); response.writeHead(200, {'Content-Type': 'text/html'}); module.exports = function(){ console.log(a); response.write(contents); return { response.end(); greet: function(){ let a = (function() { }); console.log("we are now using a module!"); return function(a, b) { } }, console.log('hello'); add: function(num1, num2){ return a*b; 1. Notice the code begins with an if statement. We are asking if the URL console.log("the sum is:", num1 + num2); } property of the request object is equal to "/". The route "/" is always } console.log('world'); considered the root route. In English, we are asking if the URL requested by } })(); the client is of a particular form. } console.log(a(3,5)); 2. If the request URL matches the string to the right of the triple equals sign, we app.js file: will serve the appropriate response. That response begins at fs.readFile(...). var my_module = require('./my_module')(); //notice the extra Promise a JavaScript object that links producing code and consuming code This command goes and finds a file by name and reads it. invocation parentheses! 3. The name of the file we're opening is called 'index.html'. console.log(my_module); Async & Await inside an async function, you can use the await keyword before a 4. The second parameter is the encoding of the file. Here, we're telling my_module.greet(); the fs object what type of characters to expect in the file it's opening. You call to a function that returns a promise. my_module.add(5,6); will need to include this line for any text-based document you serve, async makes a function return a Promise remember this!! await makes a function wait for a Promise 5. When the fs module reads the file, it passes the contents of the file into a callback and this is where we actually formulate and serve the response. 6. Notice the first thing we do is call the response.writeHead() method. This FS and HTTP method sends the headers for our response along with a status code. // get the http module: A header is the part of a response that contains the specifics of the response. var http = require('http'); We need to tell the browser what type of response we're serving. The status // fs module allows us to read and write content for responses!! code is a code that tells the browser the status of the response. Any status var fs = require('fs'); code in the 200's or 300's is good. Anything in the 400's to the 500's is bad. // creating a server using http module: For now, just always put a 200 as your status code on any valid request. var server = http.createServer(function (request, response){ 7. After all of that, we finally send the response to the client using // see what URL the clients are requesting: the response.write() method, which just sends the contents of the files to console.log('client request URL: ', request.url); the client. // this is how we do routing: 8. Since a response might contain multiple chunks of data, we if(request.url === '/') { call response.end() when we are finished. a