# JavaScript | ![img \|150](https://upload.wikimedia.org/wikipedia/commons/thumb/a/a4/JavaScript_code.png/320px-JavaScript_code.png) | **JavaScript**, often abbreviated as JS, is a programming language and core technology of the World Wide Web, alongside HTML and CSS. As of 2023, 98.7% of websites use JavaScript on the client side for webpage behavior, often incorporating third-party libraries. All major web browsers have a dedicated JavaScript engine to execute the code on users' devices. | |-|-| | | wikipedia:: [JavaScript](https://en.wikipedia.org/wiki/JavaScript) | ## Meta JavaScript ### [[JavaScript Conventions, Style, & Best Practices]] ### Documentation ### Syntax #### Comments ##### Single line - // ##### Multi-line `/* This is a multiline comment */` #### Curly brackets - You don’t technically need curly brackets in one statement conditionals but it is considered not best practice. #### Expressions & statements - expressions are a subset of statements - good thing to think of is if you can return it or not #### Blocks - Everything inside {} - In JavaScript, any code between curly braces is also known as a block. ##### Header - e.g. if (condition) ##### Body - e.g. the block under a conditional ### Reserved keywords https://www.w3schools.com/js/js_reserved.asp - abstract - arguments - await - boolean - break - byte - case - catch - char - class - const - continue - debugger - default - delete - do - double - else - enum - eval - export - extends - false - final - finally - float - for - function - goto - if - implements - import - in - instanceof - int - interface - let* - long - native - new - null - package - private - protected - public - return - short - static - super - switch - synchronized - this - throw - throws - transient - true - try - typeof - var - void - volatile - while - with - yield - Break - Case ### Security ### [[Web Development Debugging]] ### [[JavaScript Testing]] ### [[JavaScript Logging]] ### Versions #### [[ECMAScript]] ### Related languages #### [[TypeScript]] #### [[CoffeeScript]] #### [[Dart]] ### [[JavaScript Asynchronous]] ## Environment ### [[Node.js]] ### [[+JavaScript Dependencies, Packaging, Building, Artifacts, Libraries, Modules, & Structure]] ### [[Browser]] #### JavaScript With HTML ##### Similar to CSS, JS has 3 Contexts for applying the code - In the tag - In a script tag (in header or anywhere) - In an external file ##### Javascript inside the script tag - `<script>`{=html} ```{=html} <script> Javascript code; </script> ``` - Can add as many ¶ `<script>`{=html} ¶ elements as you want. Can go in either head or body. ##### Javascript in an external file linked to in the script tag - `<script src="myjs.js"></script>`{=html} type=”text/javascript” Not required anymore - Best practice now to put the scripts at the bottom - Good for performance reasons since it can load the html structure before it might get bogged down in a js script - Also because custom scripts tend to not need to be called at the top - Exception is things like jquery, bootstrap etc. ##### Javascript in a remote server linked to in the script tag - e.g. the bootstrap CDN ##### Inline JS - onclick - onclick=”javascript code;” ##### Return - Return statement to control running of code - you can use a return false statement to stop that part of the code from running - e.g. to make a link work or not. ### [[DOM (Document Object Model)]] ### [[Browser Tools (Developer Tools)]] ### [[JavaScript Frameworks]] ### [[IDEs & Text Editors]] ### Developer Environment - Can run via Live server vs code extension - Can run with VS Code debugger - Integrate it into html and load the html file #### [[DOM (Document Object Model)]] - [[DOMParser]] ## [[JavaScript Functions]] ## [[Object-Oriented JavaScript]] ### [[JavaScript Objects]] ### [[JavaScript Classes]] ## Reference ### [[JavaScript Variables]] ### [[JavaScript Scope]] ### [[JavaScript Reference & Identity]] ### [[JavaScript Hoisting]] ### [[JavaScript Closures]] ## [[JavaScript Data Types]] ### [[JavaScript strings]] ## Data structures ### [[JavaScript Arrays]] ### [[JavaScript Maps]] ### [[JavaScript Objects]] ### [[JSON]] ### [[JavaScript Text Processing]] ### JavaScript stacks ### JavaScript queues ### JavaScript trees ### [[JavaScript Destructuring]] ## Control ### [[JavaScript Conditionals]] ### [[JavaScript Iteration]] ### [[JavaScript ExceptionError Handling]] ### Program termination `process.exit(0)` ### Pause execution `setTimeout()` - https://www.w3schools.com/js/js_timing.asp `Function printMessage() { console.log(”The future is now!”); } setTimeout(printMessage, 5000);` `setTimeout(function () { console.log(”The Future is now!”); }, 5000);` ### Async/Await #### Promises ##### Helps avoid callback hell, basically nested callback functions ##### Way to handle async callbacks ##### Promise object - Example - const fetchPromise = fetch(”https://handlers.education.launchcode.org/static/weather.json”); fetchPromise.then( function(response) { console.log(response); } ); - fetch returns an instance of the Promise class. The Promise class represents a promise. A promise is the eventual outcome of an asynchronous event. In the above example, fetchPromise represents the eventual response from the HTTP request to https://handlers.education.launchcode.org/static/weather.json. A promise can be fulfilled or rejected. When a promise is fulfilled, data is passed to the response handler function. The then method of Promise defines what will happen when the promise is fulfilled. When a promise is rejected, the error reason is returned. - .then() - on a promise - runs async - whenever you see .then, it’s a promise - .exec() - So instead of needing to nest a bunch of callbacks, you can chain a bunch of .then() - .catch() ##### So, can/should you always use promises instead of callbacks? - No, because it depends on if the underlying code is modern enough ##### Example from get programming with node book: ``` use strict; const mongoose = require(”mongoose”), User = require(”./models/user”); mongoose.connect( “mongodb://localhost:27017/recipe_db”, { useNewUrlParser: true } ); mongoose.set(”useCreateIndex”, true); mongoose.connection; var contacts = \[ { name: { first: “Jon”, last: “Wexler” }, email: “[email protected]”, zipCode: 10016 }, { name: { first: “Chef”, last: “Eggplant” }, email: “[email protected]”, zipCode: 20331 }, { name: { first: “Professor”, last: “Souffle” }, email: “[email protected]”, zipCode: 19103 } \]; User.deleteMany() .exec() .then(() =\> { console.log(”Subscriber data is empty!”); }); var commands = \[\]; contacts.forEach(c =\> { commands.push( User.create({ name: c.name, email: c.email, zipCode: c.zipCode, password: c.zipCode }) ); }); Promise.all(commands) .then(r =\> { console.log(JSON.stringify(r)); mongoose.connection.close(); }) .catch(error =\> { console.log(\`ERROR: \${error}\`); }); ``` #### Await #### Generators? ## Quantitative ### [[JavaScript Operators]] ### [[JavaScript Math & Science]] ### Money - Don't store values in dollars and cents ### Date & time #### Date \#issue ##### A date consists of a year, a month, a day, an hour, a minute, a second, and a millisecond. - getYear() - getMonth() - month as number, starting with 0 - getDay() - weekday as a number, starting with 0 - ?getDate()? - ?getTime()? - getHour() - getMinute() - getSecond() - getMillisecond() ##### Example var date = new Date(“1985-10-21”); document.write(date) Mon Oct 21 1985 00:00:00 GMT ## I/O ### console.log(”message”) Automatically includes \n per console.log() console.log(3.4, “hello”, 45); ### alert(”message”) ### Files - document.write() - deprecated - [Node.js — Writing files with Node.js](https://nodejs.org/en/learn/manipulating-files/writing-files-with-nodejs) ### [[HTTP]] #### [[API]]s #### Fetch [[Fetch]] #### Example ``` Const port = 3000; const http = require(”http”); const httpstatus = require(”http-status-codes”); let app = http.createServer((request, response) =\> { console.log(”Received an incoming request.“); response.writeHead(httpStatus.OK, { ”Content-Type”: “text/html” }); let responsemessage = ” ¶ hello, nodemon. ¶ “; response.write(responseMessage); response.end(); console.log(\`Sent a response : \${responseMessage}\`); }); app.listen(port); console.log(\`The server has started and is listening on port number: \${port}\`); ``` #### App .listen .createServer(request, response) Request Response - .writeHead() - http headers - 200 - .write() - .end() - flushes buffers and sends response #### Httpstatus package - Helps with http status codes `Const input = require(’readline-sync’); let info = input.question(”Question text… “);` ### Innerhtml ### Ui ### Graphics #### Images `Var someimage = new Image(); someImage.src = ‘nanonaut.png’;` ### Visualization & graphs - https://www.chartjs.org/ #### D3.js - https://d3js.org/ ## Issues - ==?Make a javascript controlled input and button work with enter?== ## Inbox ### Strict mode - “use strict”; - in a js file - node –use_strict - checks that variables are declared, etc. - Todo: https://medium.freecodecamp.org/es5-to-esnext-heres-every-feature-added-to-javascript-since-2015-d0c255e13c6e - Codeschool recommends javascript learning strategy: “we recommend: Learn JavaScript and its modern ecosystem well. Adopt Node.js, even for your client-side development, as it will bring a lot of good tooling to help bundle your code, run linters to avoid common syntax mistakes, run unit tests, and more. Once you’ve adopted Node.js, be sure to bring all your depen- dencies in through NPM, including your CSS dependencies, such as Font Awesome, Twitter Bootstrap, etc. Adopt ES2015 (also known as ES6) and all its latest features through Babel, which transpiles ES6 code back to ES5 JavaScript code that browsers can understand, since they haven’t been fully upgraded to support the latest fea- tures of JavaScript yet. Also, if you are a fan of strict typed languages, then be sure to look into Flow and/or TypeScript.” - Everything is an object in js by way of object prototyping which I think is synonymous with inheritance - Sockets as opposed to ajax? - https://socket.io/ ## Sources - https://developer.mozilla.org/en-US/docs/Web/JavaScript - https://eloquentjavascript.net/ - [JavaScript Algorithms and Data Structures Certification | freeCodeCamp.org](https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/#basic-javascript) - [Chapters — Introduction to Professional Web Development in JavaScript documentation](https://education.launchcode.org/intro-to-professional-web-dev/) - https://courses.wesbos.com/account/access/5de17cfca0fbbc5276b71f7c/view/375473287