### Bitwise AND Example Source: https://github.com/getify/you-dont-know-js/blob/2nd-ed/types-grammar/ch2.md Demonstrates the bitwise AND operation. Operands are converted to 32-bit integers before the operation. ```javascript 42 & 36 ``` -------------------------------- ### Locale-Specific String Comparison Examples Source: https://github.com/getify/you-dont-know-js/blob/2nd-ed/types-grammar/ch2.md Provides examples of `localeCompare()` demonstrating locale-specific sorting behavior, such as how 'ä' is sorted differently in German ('de') versus Swedish ('sv'). ```javascript // examples from MDN: // // in German, ä sorts before z "ä".localeCompare("z","de"); // -1 (or negative number) // a negative value // in Swedish, ä sorts after z "ä".localeCompare("z","sv"); // 1 (or positive number) ``` -------------------------------- ### isPrime(..) and factorize(..) Usage Examples Source: https://github.com/getify/you-dont-know-js/blob/2nd-ed/scope-closures/apB.md Demonstrates the expected output of the isPrime and factorize functions for specific inputs. ```javascript isPrime(11); // true isPrime(12); // false factorize(11); // [ 11 ] factorize(12); // [ 3, 2, 2 ] --> 3*2*2=12 ``` -------------------------------- ### Bitwise OR Example Source: https://github.com/getify/you-dont-know-js/blob/2nd-ed/types-grammar/ch2.md Demonstrates the bitwise OR operation. Operands are converted to 32-bit integers before the operation. ```javascript 42 | 36 ``` -------------------------------- ### Simulating Calculator Usage with Helper Source: https://github.com/getify/you-dont-know-js/blob/2nd-ed/scope-closures/apB.md Examples of using the `useCalc` helper to process strings of calculator inputs and display intermediate results. ```javascript useCalc(calc,"4+3="); // 4+3=7 useCalc(calc,"+9="); // +9=16 useCalc(calc,"*8="); // *5=128 useCalc(calc,"7*2*3="); // 7*2*3=42 useCalc(calc,"1/0="); // 1/0=ERR useCalc(calc,"+3="); // +3=ERR useCalc(calc,"51="); // 51 ``` -------------------------------- ### Asynchronous Module Definition (AMD) Example Source: https://github.com/getify/you-dont-know-js/blob/2nd-ed/scope-closures/apA.md An example of an Asynchronous Module Definition (AMD) using the RequireJS utility. It defines a module with its dependencies and returns its public API. ```javascript define([ "./Student" ],function StudentList(Student){ var elems = []; return { renderList() { // .. } }; }); ``` -------------------------------- ### Calculator Module Usage Example Source: https://github.com/getify/you-dont-know-js/blob/2nd-ed/scope-closures/apB.md Demonstrates how to instantiate and use the calculator module by calling its public API methods for number input and operations. ```javascript var calc = calculator(); calc.number("4"); // 4 calc.plus(); // + calc.number("7"); // 7 calc.number("3"); // 3 calc.minus(); // - calc.number("2"); // 2 calc.eq(); // 75 ``` -------------------------------- ### DOM Event Listener Setup Source: https://github.com/getify/you-dont-know-js/blob/2nd-ed/objects-classes/ch4.md Demonstrates setting up a DOM event listener using `addEventListener`. The `this` context within the `clickHandler` will depend on how `clickHandler` is defined and passed. ```javascript var infoForm = { theFormElem: null, theSubmitBtn: null, init() { this.theFormElem = document.getElementById("the-info-form"); this.theSubmitBtn = theFormElem.querySelector("button[type=submit]"); // is *this* the call-site? this.theSubmitBtn.addEventListener( "click", this.clickHandler, false ); }, // .. } ``` -------------------------------- ### Bitwise XOR Example Source: https://github.com/getify/you-dont-know-js/blob/2nd-ed/types-grammar/ch2.md Demonstrates the bitwise XOR operation. Operands are converted to 32-bit integers before the operation. ```javascript 42 ^ 36 ``` -------------------------------- ### Variable Hoisting Example Source: https://github.com/getify/you-dont-know-js/blob/2nd-ed/scope-closures/ch5.md Illustrates how variable declarations are conceptually 'hoisted' to the top of their scope before execution. ```javascript var greeting; greeting = "Hello!"; console.log(greeting); ``` -------------------------------- ### JavaScript Program Example Source: https://github.com/getify/you-dont-know-js/blob/2nd-ed/scope-closures/ch2.md Illustrates variable declarations, function definition, loop, and console output. This code is used to demonstrate scope and compilation concepts. ```javascript var students = [ { id: 14, name: "Kyle" }, { id: 73, name: "Suzy" }, { id: 112, name: "Frank" }, { id: 6, name: "Sarah" } ]; function getStudentName(studentID) { for (let student of students) { if (student.id == studentID) { return student.name; } } } var nextStudent = getStudentName(73); console.log(nextStudent); // Suzy ``` -------------------------------- ### Boolean Arithmetic Example Source: https://github.com/getify/you-dont-know-js/blob/2nd-ed/types-grammar/ch4.md An example demonstrating how booleans are treated as their numeric equivalents in arithmetic operations. ```javascript false + true + false + false + true; // 2 ``` -------------------------------- ### Destructuring Defaults + Parameter Defaults Example Source: https://github.com/getify/you-dont-know-js/wiki/_Footer Demonstrates the behavior of destructuring defaults and parameter defaults when the function is called with no arguments. ```javascript function f6({ x = 10 } = {}, { y } = { y: 10 }) { console.log( x, y ); } f6(); // 10 10 ``` -------------------------------- ### Left Shift Example Source: https://github.com/getify/you-dont-know-js/blob/2nd-ed/types-grammar/ch2.md Demonstrates the left shift operation. Bits are shifted to the left, and zeros fill from the right. ```javascript 42 << 3 ``` -------------------------------- ### Partial Application with Closure Source: https://github.com/getify/you-dont-know-js/blob/2nd-ed/scope-closures/ch7.md Demonstrates adapting partial application using closure. It separates the setup of request details from the event handler itself, creating a reusable handler function. ```javascript function defineHandler(requestURL,requestData) { return function makeRequest(evt){ ajax(requestURL,requestData); }; } function setupButtonHandler(btn) { var recordKind = btn.dataset.kind; var handler = defineHandler( APIendpoints[recordKind], data[recordKind] ); btn.addEventListener("click",handler); } ``` -------------------------------- ### JavaScript Namespace Example Source: https://github.com/getify/you-dont-know-js/blob/2nd-ed/scope-closures/ch8.md Use this pattern to group related stateless functions under a single object. It does not provide encapsulation or state management. ```javascript var Utils = { cancelEvt(evt) { evt.preventDefault(); evt.stopPropagation(); evt.stopImmediatePropagation(); }, wait(ms) { return new Promise(function c(res){ setTimeout(res,ms); }); }, isValidEmail(email) { return /[^@]+@[^@.]+\.[^@.]+/.test(email); } }; ``` -------------------------------- ### Closure Example: `adder` Function Source: https://github.com/getify/you-dont-know-js/blob/2nd-ed/scope-closures/ch7.md Illustrates closure by creating functions that 'remember' a value from their outer scope. Each call to `adder` creates a new closure. ```javascript function adder(num1) { return function addTo(num2){ return num1 + num2; }; } var add10To = adder(10); var add42To = adder(42); add10To(15); // 25 add42To(9); // 51 ``` -------------------------------- ### Variable Hoisting Caution Source: https://github.com/getify/you-dont-know-js/blob/2nd-ed/scope-closures/apA.md Shows an example of variable hoisting with 'var' that is generally considered a bad practice due to potential confusion. ```javascript pleaseDontDoThis = "bad idea"; // much later var pleaseDontDoThis; ``` -------------------------------- ### Function Declaration and Expression Naming Source: https://github.com/getify/you-dont-know-js/blob/2nd-ed/scope-closures/apA.md Provides examples of different ways functions can be declared or expressed, highlighting named vs. anonymous forms. ```javascript function thisIsNamed() { // .. } ajax("some.url",function thisIsAlsoNamed(){ // .. }); var notNamed = function(){ // .. }; makeRequest({ data: 42, cb /* also not a name */: function(){ // .. } }); var stillNotNamed = function butThisIs(){ // .. }; ``` -------------------------------- ### Function Declaration Hoisting Example Source: https://github.com/getify/you-dont-know-js/blob/2nd-ed/scope-closures/ch5.md Demonstrates how function declarations are hoisted entirely to the top of their scope, allowing them to be called before their physical appearance in the code. ```javascript studentName = "Suzy"; greeting(); function greeting() { console.log(`Hello ${ studentName }!`); } var studentName; ``` -------------------------------- ### Event Handler Using Closure (Optimized) Source: https://github.com/getify/you-dont-know-js/blob/2nd-ed/scope-closures/ch7.md Further optimizes the closure pattern by pre-calculating `requestURL` and `requestData` during setup. This is slightly more performant and cleaner. ```javascript function setupButtonHandler(btn) { var recordKind = btn.dataset.kind; var requestURL = APIendpoints[recordKind]; var requestData = data[recordKind]; btn.addEventListener( "click", function makeRequest(evt){ ajax(requestURL,requestData); } ); } ``` -------------------------------- ### Word Segmentation with Intl.Segmenter Source: https://github.com/getify/you-dont-know-js/blob/2nd-ed/types-grammar/ch2.md Demonstrates how to use `Intl.Segmenter` to break down a string into words based on a specified locale. The example iterates through segments and logs only those identified as words. ```javascript arabicHelloWorld = "\u{645}\u{631}\u{62d}\u{628}\u{627} \ \u{628}\u{627}\u{644}\u{639}\u{627}\u{644}\u{645}"; console.log(arabicHelloWorld); // مرحبا بالعالم arabicSegmenter = new Intl.Segmenter("ar",{ granularity: "word" }); for ( let { segment: word, isWordLike } of arabicSegmenter.segment(arabicHelloWorld) ) { if (isWordLike) { console.log(word); } } // مرحبا //لعالم ``` -------------------------------- ### Zero-Fill Right Shift Example Source: https://github.com/getify/you-dont-know-js/blob/2nd-ed/types-grammar/ch2.md Demonstrates the zero-fill right shift. Bits are shifted right, and zeros fill from the left, ignoring the sign bit. ```javascript 42 >>> 3 ``` ```javascript -43 >>> 3 ``` -------------------------------- ### Delegation Pattern Example Source: https://github.com/getify/you-dont-know-js/blob/2nd-ed/objects-classes/ch5.md Demonstrates explicit and implicit delegation using shared behavior objects and object creation. Use this pattern for runtime composition without traditional inheritance. ```javascript var Coordinates = { setX(x) { this.x = x; }, setY(y) { this.y = y; }, setXY(x,y) { this.setX(x); this.setY(y); }, }; var Inspect = { toString() { return `(${this.x},${this.y})`; }, }; var point = {}; Coordinates.setXY.call(point,3,4); Inspect.toString.call(point); // (3,4) var anotherPoint = Object.create(Coordinates); anotherPoint.setXY(5,6); Inspect.toString.call(anotherPoint); // (5,6) ``` -------------------------------- ### Primitive Value Copy Example Source: https://github.com/getify/you-dont-know-js/blob/2nd-ed/get-started/apA.md Demonstrates how primitive values (like strings) are copied by value. Assigning a primitive to a new variable creates an independent copy. ```javascript var myName = "Kyle"; var yourName = myName; ``` -------------------------------- ### Getting Character Code Point at Index Source: https://github.com/getify/you-dont-know-js/blob/2nd-ed/types-grammar/ch2.md Retrieve the full Unicode code point value starting at a specified index using String.prototype.codePointAt(). Handles surrogate pairs correctly. ```javascript str = "\uD83D\uDE00"; // Grinning Face emoji str.codePointAt(0); // 128512 ``` -------------------------------- ### Instantiate and Use Classic Modules (Book, BlogPost) Source: https://github.com/getify/you-dont-know-js/blob/2nd-ed/get-started/ch2.md Demonstrates how to instantiate and use the `Book` and `BlogPost` module factory functions. These are called directly as functions, not with the `new` keyword. ```javascript var YDKJS = Book({ title: "You Don't Know JS", author: "Kyle Simpson", publishedOn: "June 2014", publisher: "O'Reilly", ISBN: "123456-789" }); YDKJS.print(); // Title: You Don't Know JS // By: Kyle Simpson // June 2014 // Publisher: O'Reilly // ISBN: 123456-789 var forAgainstLet = BlogPost( "For and against let", "Kyle Simpson", "October 27, 2014", "https://davidwalsh.name/for-and-against-let" ); forAgainstLet.print(); // Title: For and against let // By: Kyle Simpson // October 27, 2014 // https://davidwalsh.name/for-and-against-let ``` -------------------------------- ### Function Hoisting Example in JavaScript Source: https://github.com/getify/you-dont-know-js/blob/2nd-ed/scope-closures/ch5.md Demonstrates how functions declared with 'function' keyword can be called before their declaration due to function hoisting. This behavior is specific to function declarations. ```javascript greeting(); // Hello! function greeting() { console.log("Hello!"); } ``` -------------------------------- ### Manage Student Grades with Closures Source: https://github.com/getify/you-dont-know-js/blob/2nd-ed/scope-closures/ch7.md This example illustrates how closures can maintain state across function calls. The returned `addGrade` function closes over the `grades` variable, allowing it to be updated and managed persistently. Call the returned function to add a new grade and get the updated top 10 list. ```javascript function manageStudentGrades(studentRecords) { var grades = studentRecords.map(getGrade); return addGrade; // ************************ function getGrade(record){ return record.grade; } function sortAndTrimGradesList() { // sort by grades, descending grades.sort(function desc(g1,g2){ return g2 - g1; }); // only keep the top 10 grades grades = grades.slice(0,10); } function addGrade(newGrade) { grades.push(newGrade); sortAndTrimGradesList(); return grades; } } var addNextGrade = manageStudentGrades([ { id: 14, name: "Kyle", grade: 86 }, { id: 73, name: "Suzy", grade: 87 }, { id: 112, name: "Frank", grade: 75 }, // ..many more records.. { id: 6, name: "Sarah", grade: 91 } ]); // later addNextGrade(81); addNextGrade(68); // [ .., .., ... ] ``` -------------------------------- ### Instantiate and Use Book and BlogPost Classes Source: https://github.com/getify/you-dont-know-js/blob/2nd-ed/get-started/ch2.md Demonstrates creating instances of the 'Book' and 'BlogPost' classes and calling their print methods. This showcases inheritance and polymorphism in action. ```javascript var YDKJS = new Book({ title: "You Don't Know JS", author: "Kyle Simpson", pubDate: "June 2014", publisher: "O'Reilly", ISBN: "123456-789" }); YDKJS.print(); var forAgainstLet = new BlogPost( "For and against let", "Kyle Simpson", "October 27, 2014", "https://davidwalsh.name/for-and-against-let" ); forAgainstLet.print(); ``` -------------------------------- ### TypeScript Type Inference Example Source: https://github.com/getify/you-dont-know-js/blob/2nd-ed/types-grammar/ch4.md Demonstrates TypeScript's ability to infer types without explicit annotations. Both examples achieve the same static type enforcement. ```typescript let API_BASE_URL: string = "https://some.tld/api/2"; ``` ```typescript let API_BASE_URL = "https://some.tld/api/2"; ``` -------------------------------- ### String Comparison with Intl.Collator Source: https://github.com/getify/you-dont-know-js/blob/2nd-ed/types-grammar/ch2.md Illustrates how to use `Intl.Collator` to create locale-specific string comparison functions. This example shows default German sorting and how to configure case-sensitive sorting. ```javascript germanStringSorter = new Intl.Collator("de"); listOfGermanWords = [ /* .. */ ]; germanStringSorter.compare("Hallo","Welt"); // -1 (or negative number) // examples adapted from MDN: // germanStringSorter.compare("Z","z"); // 1 (or positive number) caseFirstSorter = new Intl.Collator("de",{ caseFirst: "upper", }); caseFirstSorter.compare("Z","z"); // -1 (or negative number) ``` -------------------------------- ### Instantiate and Use Reminder Class Source: https://github.com/getify/you-dont-know-js/blob/2nd-ed/objects-classes/ch3.md Demonstrates creating a `Reminder` instance, calling its `summary` method before and after marking it complete, and checking its type using `instanceof`. ```javascript var callMyParents = new Reminder( "Call my parents to say hi", new Date("July 7, 2022 11:00:00 UTC") ); callMyParents.toString(); // [object Reminder] callMyParents.summary(); // (586380912) Call my parents to say hi at // Thu, 07 Jul 2022 11:00:00 GMT callMyParents.markComplete(); callMyParents.summary(); // (586380912) Complete. callMyParents instanceof Reminder; // true callMyParents instanceof CalendarItem; // true callMyParents instanceof Meeting; // false ``` -------------------------------- ### Instantiate and Use Meeting Class Source: https://github.com/getify/you-dont-know-js/blob/2nd-ed/objects-classes/ch3.md Demonstrates creating a `Meeting` instance, calling its `summary` method, and checking its type using `instanceof`. ```javascript var interview = new Meeting( "Job Interview: ABC Tech", new Date("June 23, 2022 08:30:00 UTC"), new Date("June 23, 2022 09:15:00 UTC") ); interview.toString(); // [object Meeting] interview.summary(); // (994337604) Job Interview: ABC Tech at Thu, // 23 Jun 2022 08:30:00 GMT - Thu, 23 Jun 2022 // 09:15:00 GMT interview instanceof Meeting; // true interview instanceof CalendarItem; // true interview instanceof Reminder; // false ``` -------------------------------- ### Closure for Partial Application (Currying) Source: https://github.com/getify/you-dont-know-js/blob/2nd-ed/scope-closures/apA.md This example demonstrates closure being utilized for partial application. The inner function `createLabel` closes over the `list` variable, preserving access to it for later invocation. ```javascript function printLabels(labels) { var list = document.getElementById("labelsList"); var renderLabel = renderTo(list); // definitely closure this time! labels.forEach( renderLabel ); // ************** function renderTo(list) { return function createLabel(label){ var li = document.createElement("li"); li.innerText = label; list.appendChild(li); }; } } ``` -------------------------------- ### Define Accessor Property (Getter/Setter) Source: https://github.com/getify/you-dont-know-js/blob/2nd-ed/objects-classes/ch2.md Define an accessor property using get() and set() functions within the property descriptor. This allows custom logic for getting and setting the property's value. ```javascript anotherObj = {}; Object.defineProperty(anotherObj,"fave",{ get() { console.log("Getting 'fave' value!"); return 123; }, set(v) { console.log(`Ignoring ${v} assignment.`); } }); anotherObj.fave; // Getting 'fave' value! // 123 anotherObj.fave = 42; // Ignoring 42 assignment. anotherObj.fave; // Getting 'fave' value! // 123 ``` -------------------------------- ### Using the toggle utility Source: https://github.com/getify/you-dont-know-js/blob/2nd-ed/scope-closures/apB.md Demonstrates how to use the `toggle` utility with different sets of values. The returned functions cycle through the provided arguments on successive calls. ```javascript var hello = toggle("hello"); var onOff = toggle("on","off"); var speed = toggle("slow","medium","fast"); hello(); // "hello" hello(); // "hello" onOff(); // "on" onOff(); // "off" onOff(); // "on" speed(); // "slow" speed(); // "medium" speed(); // "fast" speed(); // "slow" ``` -------------------------------- ### Illustrative Node.js Module Wrapping Source: https://github.com/getify/you-dont-know-js/blob/2nd-ed/scope-closures/ch4.md This illustrative example shows how Node.js conceptually wraps CommonJS module code in a function, creating a distinct module scope for declarations. ```javascript function Module(module,require,__dirname,...) { var studentName = "Kyle"; function hello() { console.log(`Hello, ${ studentName }!`); } hello(); // Hello, Kyle! module.exports.hello = hello; } ``` -------------------------------- ### Get Property Descriptor Source: https://github.com/getify/you-dont-know-js/blob/2nd-ed/objects-classes/ch2.md Use Object.getOwnPropertyDescriptor to retrieve the descriptor object for a specific property on an object. ```javascript myObj = { favoriteNumber: 42, isDeveloper: true, firstName: "Kyle" }; Object.getOwnPropertyDescriptor(myObj,"favoriteNumber"); // { // value: 42, // enumerable: true, // writable: true, // configurable: true // } ``` -------------------------------- ### Main ES Module Usage Example Source: https://github.com/getify/you-dont-know-js/blob/2nd-ed/get-started/ch2.md Imports the `create` function from `blogpost.js` (aliased as `newBlogPost`) into `main.js`. It then uses this function to create a blog post instance and calls its `print` method, illustrating the final usage of the module chain. ```javascript import { create as newBlogPost } from "blogpost.js"; var forAgainstLet = newBlogPost( "For and against let", "Kyle Simpson", "October 27, 2014", "https://davidwalsh.name/for-and-against-let" ); forAgainstLet.print(); // Title: For and against let // By: Kyle Simpson // October 27, 2014 // https://davidwalsh.name/for-and-against-let ``` -------------------------------- ### Event binding with incorrect `this` context Source: https://github.com/getify/you-dont-know-js/blob/2nd-ed/objects-classes/ch4.md This is the initial event binding setup that leads to `this` context issues. ```javascript this.submitBtnaddEventListener( "click", this.clickHandler, false ); ``` -------------------------------- ### Extracting a Substring Source: https://github.com/getify/you-dont-know-js/blob/2nd-ed/types-grammar/ch2.md Extract a portion of a string using String.prototype.substring(). It takes start and end indices. ```javascript str = "JavaScript"; str.substring(4, 10); // "Script" ``` -------------------------------- ### Calculator Input Simulation Source: https://github.com/getify/you-dont-know-js/blob/2nd-ed/scope-closures/apB.md Demonstrates how to interact with the calculator instance by passing keypress characters. ```javascript calc("4"); // 4 calc("+"); // + c alc("7"); // 7 calc("3"); // 3 calc("-"); // - c alc("2"); // 2 calc("="); // 75 calc("*"); // * c alc("4"); // 4 calc("="); // 300 calc("5"); // 5 c alc("-"); // - calc("5"); // 5 calc("="); // 0 ``` -------------------------------- ### Static Property Initialization with 'this' Source: https://github.com/getify/you-dont-know-js/blob/2nd-ed/objects-classes/ch3.md Demonstrates initializing static properties using 'this' to refer to the class constructor. Prefer direct class name references for clarity. ```javascript class Point2d { // class statics static originX = 0 static originY = 0 static origin = new this(this.originX,this.originY) // .. } ``` -------------------------------- ### Bitwise NOT Example Source: https://github.com/getify/you-dont-know-js/blob/2nd-ed/types-grammar/ch2.md Demonstrates the bitwise NOT operation. The operand is converted to a 32-bit integer, and the result is equivalent to -(x + 1). ```javascript ~42 ``` -------------------------------- ### Using `new` with Object Methods Source: https://github.com/getify/you-dont-know-js/blob/2nd-ed/objects-classes/ch4.md Demonstrates calling a function property of an object using the `new` keyword to create an instance. The `init` function must be a function expression assigned to a property to be valid with `new`. ```javascript var point = { // .. init: function() { /* .. */ } // .. }; var anotherPoint = new point.init(3,4); anotherPoint.x; // 3 anotherPoint.y; // 4 ``` -------------------------------- ### Exporting Functions in CommonJS Source: https://github.com/getify/you-dont-know-js/blob/2nd-ed/scope-closures/ch8.md Expose module functions by assigning them to `module.exports`. This example shows exporting a `getName` function. ```javascript module.exports.getName = getName; // ************************ var records = [ { id: 14, name: "Kyle", grade: 86 }, { id: 73, name: "Suzy", grade: 87 }, { id: 112, name: "Frank", grade: 75 }, { id: 6, name: "Sarah", grade: 91 } ]; function getName(studentID) { var student = records.find( student => student.id == studentID ); return student.name; } ``` -------------------------------- ### Trimming Whitespace from the Start Source: https://github.com/getify/you-dont-know-js/blob/2nd-ed/types-grammar/ch2.md Remove whitespace from the beginning (left side in LTR locales) of a string using String.prototype.trimStart(). ```javascript str = " Hello World "; str.trimStart(); // "Hello World " ``` -------------------------------- ### Borrowing Methods with Explicit Context Source: https://github.com/getify/you-dont-know-js/blob/2nd-ed/objects-classes/ch4.md Demonstrates borrowing the `init` method from `point` to initialize `anotherPoint` using `call()`. This avoids repeating function definitions on new objects. ```javascript var point = { x: null, y: null, init(x,y) { this.x = x; this.y = y; }, rotate(angleRadians) { /* .. */ }, toString() { return `(${this.x},${this.y})`; }, }; point.init(3,4); var anotherPoint = {}; point.init.call( anotherPoint, 5, 6 ); point.x; // 3 point.y; // 4 anotherPoint.x; // 5 anotherPoint.y; // 6 ``` -------------------------------- ### Using the Static Math Namespace Source: https://github.com/getify/you-dont-know-js/blob/2nd-ed/types-grammar/ch2.md Illustrates common mathematical operations and constants available on the static Math object. These utilities are directly accessible without instantiation. ```javascript Math.PI; // absolute value Math.abs(-32.6); // rounding Math.round(-32.6); // min/max selection Math.min(100,Math.max(0,42)); ``` -------------------------------- ### Regular Function Equivalent Source: https://github.com/getify/you-dont-know-js/blob/2nd-ed/objects-classes/ch4.md Presents the non-arrow function equivalent of the `clickHandler` example. Regular functions have their own `this` binding determined by the call-site. ```javascript const clickHandler = function(evt) { evt.target.matches("button") ? this.theFormElem.submit() : evt.stopPropagation(); }; ``` -------------------------------- ### String Literal Example Source: https://github.com/getify/you-dont-know-js/blob/2nd-ed/get-started/ch2.md Demonstrates a basic string literal used in a function call. Strings are ordered collections of characters. ```javascript greeting("My name is Kyle."); ``` -------------------------------- ### Defining Base and Subclass with Static Inheritance Source: https://github.com/getify/you-dont-know-js/blob/2nd-ed/objects-classes/ch3.md Illustrates static properties and methods in a base class (`Point2d`) and their inheritance and overriding in a subclass (`Point3d`). Shows how `super` is used for referencing base class statics. ```javascript class Point2d { static origin = /* .. */ static distance(x,y) { /* .. */ } static { // .. this.maxDistance = /* .. */; } // .. } class Point3d extends Point2d { // class statics static origin = new Point3d( // here, `this.origin` references wouldn't // work (self-referential), so we use // `super.origin` references instead super.origin.x, super.origin.y, 0 ) static distance(point1,point2) { // here, super.distance(..) is Point2d.distance(..), // if we needed to invoke it return Math.sqrt( ((point2.x - point1.x) ** 2) + ((point2.y - point1.y) ** 2) + ((point2.z - point1.z) ** 2) ); } // instance members/methods z constructor(x,y,z) { super(x,y); // <-- don't forget this line! this.z = z; } toString() { return `(${this.x},${this.y},${this.z})`; } } Point2d.maxDistance; // 10 Point3d.maxDistance; // 10 ``` -------------------------------- ### Creating Multiple Instances with Factory Function Source: https://github.com/getify/you-dont-know-js/blob/2nd-ed/objects-classes/ch5.md Demonstrates how the 'make' factory function can be used to create multiple instances of objects that share the same prototype and initialization logic. ```javascript var point = make(Point2d,3,4); var anotherPoint = make(Point2d,5,6); ``` -------------------------------- ### Checking if String Starts With a Substring Source: https://github.com/getify/you-dont-know-js/blob/2nd-ed/types-grammar/ch2.md Check if a string begins with the characters of a specified string using String.prototype.startsWith(). Returns a boolean. ```javascript str = "Hello World"; str.startsWith("Hello"); // true ``` -------------------------------- ### Manual default assignment (verbose) Source: https://github.com/getify/you-dont-know-js/wiki/_Footer Demonstrates the traditional, manual method for applying default values to a nested configuration object, highlighting its verbosity. ```javascript config.options = config.options || {}; config.options.remove = (config.options.remove !== undefined) ? config.options.remove : defaults.options.remove; config.options.enable = (config.options.enable !== undefined) ? config.options.enable : defaults.options.enable; ... ``` -------------------------------- ### JavaScript Function with Parameters and Console Output Source: https://github.com/getify/you-dont-know-js/blob/2nd-ed/get-started/ch2.md Demonstrates a function that accepts a parameter and uses it to produce output. Parameters act as local variables within the function. ```javascript function greeting(myName) { console.log(`Hello, ${ myName }!`); } greeting("Kyle"); // Hello, Kyle! ``` -------------------------------- ### Traditional Pre-ES6 Approach with 'arguments' and apply() Source: https://github.com/getify/you-dont-know-js/wiki/_Footer Demonstrates the older method of handling function arguments using the 'arguments' object, Array.prototype.slice, and Function.prototype.apply(). ```javascript // doing things the old-school pre-ES6 way function bar() { // turn `arguments` into a real array var args = Array.prototype.slice.call( arguments ); // add some elements on the end args.push( 4, 5 ); // filter out odd numbers args = args.filter( function(v){ return v % 2 == 0; } ); // pass along all of `args` as arguments // to `foo(..)` foo.apply( null, args ); } bar( 0, 1, 2, 3 ); // 2 4 ``` -------------------------------- ### Named Function Stack Trace Source: https://github.com/getify/you-dont-know-js/blob/2nd-ed/scope-closures/apA.md Compares to the previous example, this shows how named functions improve stack trace readability for debugging. ```javascript btn.addEventListener("click",function onClick(){ setTimeout(function waitAMoment(){ ["a",42].map(function allUpper(v){ console.log(v.toUpperCase()); }); },100); }); ``` -------------------------------- ### Nested Function `this` Binding Example Source: https://github.com/getify/you-dont-know-js/blob/2nd-ed/objects-classes/ch4.md Demonstrates a complex scenario of `this` binding with nested regular and arrow functions, highlighting call-site analysis. ```javascript globalThis.value = { result: "Sad face" }; function one() { function two() { var three = { value: { result: "Hmmm" }, fn: () => { const four = () => this.value; return four.call({ value: { result: "OK", }, }); }, }; return three.fn(); }; return two(); } new one(); // ??? ``` -------------------------------- ### Module Registration with Wrapper Function Scope Source: https://github.com/getify/you-dont-know-js/blob/2nd-ed/scope-closures/ch4.md Demonstrates how modules can register themselves using local variables within a shared wrapper function scope, acting as an application-wide scope. ```javascript (function wrappingOuterScope(){ var moduleOne = (function one(){ // .. })(); var moduleTwo = (function two(){ // .. function callModuleOne() { moduleOne.someMethod(); } // .. })(); })(); ``` -------------------------------- ### String Equality and Relational Shorthand Source: https://github.com/getify/you-dont-know-js/blob/2nd-ed/types-grammar/ch2.md Shows how '<=' and '>=' operators work, demonstrating their equivalence to compound checks involving '<', '>', and '=='. ```javascript "hello" <= "hello"; // true ("hello" < "hello") || ("hello" == "hello"); // true "hello" >= "hello"; // true ("hello" > "hello") || ("hello" == "hello"); // true ``` -------------------------------- ### Import and Use an ES Module Source: https://github.com/getify/you-dont-know-js/blob/2nd-ed/get-started/ch2.md Imports the `create` function from `publication.js` (aliased as `createPub`) into `blogpost.js`. It then defines its own `create` function that uses the imported module to create and manage a blog post, demonstrating module composition. ```javascript import { create as createPub } from "publication.js"; function printDetails(pub,URL) { pub.print(); console.log(URL); } export function create(title,author,pubDate,URL) { var pub = createPub(title,author,pubDate); var publicAPI = { print() { printDetails(pub,URL); } }; return publicAPI; } ``` -------------------------------- ### Constructor Function for Prototypal Classes Source: https://github.com/getify/you-dont-know-js/blob/2nd-ed/get-started/apA.md Illustrates the traditional prototypal class pattern using a constructor function and assigning methods to its prototype property. This pattern was common before ES6 classes. ```javascript function Classroom() { // .. } Classroom.prototype.welcome = function hello() { console.log("Welcome, students!"); }; var mathClass = new Classroom(); mathClass.welcome(); // Welcome, students! ``` -------------------------------- ### Getting Character Code Unit at Index Source: https://github.com/getify/you-dont-know-js/blob/2nd-ed/types-grammar/ch2.md Obtain the UTF-16 code unit value of the character at a specified index using String.prototype.charCodeAt(). ```javascript str = "abc"; str.charCodeAt(1); // 98 (Unicode value for 'b') ``` -------------------------------- ### Getting a Character at a Specific Index Source: https://github.com/getify/you-dont-know-js/blob/2nd-ed/types-grammar/ch2.md Retrieve the character at a specific index using String.prototype.charAt(). Returns an empty string if the index is out of range. ```javascript str = "abc"; str.charAt(1); // "b" str.charAt(5); // "" ``` -------------------------------- ### Comprehensive Destructuring and Parameter Defaults Scenarios Source: https://github.com/getify/you-dont-know-js/wiki/_Footer Provides a detailed comparison of various function calls to illustrate the nuances between destructuring defaults and parameter defaults. ```javascript function f6({ x = 10 } = {}, { y } = { y: 10 }) { console.log( x, y ); } f6(); // 10 10 f6( undefined, undefined ); // 10 10 f6( {}, undefined ); // 10 10 f6( {}, {} ); // 10 undefined f6( undefined, {} ); // 10 undefined f6( { x: 2 }, { y: 3 } ); // 2 3 ``` -------------------------------- ### Module Registration in Global Scope via Bundling Source: https://github.com/getify/you-dont-know-js/blob/2nd-ed/scope-closures/ch4.md Shows how modules are registered directly into the global scope when no surrounding function scope is present, typically after bundling. ```javascript var moduleOne = (function one(){ // .. })(); var moduleTwo = (function two(){ // .. function callModuleOne() { moduleOne.someMethod(); } // .. })(); ``` -------------------------------- ### Padding a String to a Specific Length (Start) Source: https://github.com/getify/you-dont-know-js/blob/2nd-ed/types-grammar/ch2.md Pad the beginning of a string with a specified string until it reaches a target length using String.prototype.padStart(). ```javascript str = "5"; str.padStart(2, "0"); // "05" ``` -------------------------------- ### Coercive Equality with Negated Empty Array Source: https://github.com/getify/you-dont-know-js/blob/2nd-ed/types-grammar/ch4.md An example of a surprising result from loose equality (==) due to multiple corner case coercions. ```javascript [] == ![]; // true ``` -------------------------------- ### Illustrative `bind()` Implementation (Pre-ES6) Source: https://github.com/getify/you-dont-know-js/blob/2nd-ed/objects-classes/ch4.md A simplified, conceptual implementation of `bind()` using `apply()` to set the context. Note that the actual `bind()` is more complex. ```javascript function bind(fn,context) { return function bound(...args){ return fn.apply(context,args); }; } ``` -------------------------------- ### SameValueZero: Zero Equality Source: https://github.com/getify/you-dont-know-js/blob/2nd-ed/types-grammar/ch4.md Demonstrates SameValueZero's key difference from SameValue: it treats positive and negative zero as indistinguishable. ```javascript // SameValueZero() is abstract SameValueZero(0,-0); // true ``` -------------------------------- ### Sign-Propagating Right Shift Example Source: https://github.com/getify/you-dont-know-js/blob/2nd-ed/types-grammar/ch2.md Demonstrates the sign-propagating right shift. Bits are shifted right, and the sign bit is copied to fill from the left. ```javascript 42 >> 3 ``` -------------------------------- ### Creating and Accessing Object Properties in JS Source: https://github.com/getify/you-dont-know-js/blob/2nd-ed/get-started/ch2.md Shows how to create an object with key-value pairs and access properties using dot notation. Square-bracket notation is an alternative. ```javascript var me = { first: "Kyle", last: "Simpson", age: 39, specialties: [ "JS", "Table Tennis" ] }; console.log(`My name is ${ me.first }.`); ``` -------------------------------- ### Define base and subclass with constructor and extends Source: https://github.com/getify/you-dont-know-js/blob/2nd-ed/objects-classes/ch3.md Demonstrates the definition of a base class 'Point2d' and a subclass 'Point3d' that extends it, including constructors and instance properties. The 'super()' call is used to invoke the parent constructor. ```javascript class Point2d { x y constructor(x,y) { this.x = x; this.y = y; } } class Point3d extends Point2d { z constructor(x,y,z) { super(x,y); this.z = z; } toString() { console.log(`(${this.x},${this.y},${this.z})`); } } var anotherPoint = new Point3d(3,4,5); ``` -------------------------------- ### Event Callback with Explicit Context Source: https://github.com/getify/you-dont-know-js/blob/2nd-ed/objects-classes/ch4.md This example demonstrates an event callback being invoked using `.call()`, explicitly setting the `this` context to the DOM element. ```javascript // .. eventCallback.call( domElement, domEventObj ); ``` -------------------------------- ### Coercive Equality Examples Source: https://github.com/getify/you-dont-know-js/blob/2nd-ed/get-started/ch2.md Demonstrates how the '==' operator performs type coercion before comparison when types differ. It converts non-number values to numbers. ```javascript 42 == "42"; // true 1 == true; // true ``` -------------------------------- ### Implement Slot Machine Structure Source: https://github.com/getify/you-dont-know-js/blob/2nd-ed/get-started/apB.md Sets up the main slot machine object with an array for reels and methods for spinning and displaying. It utilizes delegation via `Object.create()` for individual reel instances. ```javascript var slotMachine = { reels: [ // this slot machine needs 3 separate reels // hint: Object.create(..) ], spin() { this.reels.forEach(function spinReel(reel){ reel.spin(); }); }, display() { // TODO } }; slotMachine.spin(); slotMachine.display(); // ☾ | ☀ | ★ // ☀ | ♠ | ☾ // ♠ | ♥ | ☀ slotMachine.spin(); slotMachine.display(); // ♦ | ♠ | ♣ // ♣ | ♥ | ☺ // ☺ | ♦ | ★ ``` -------------------------------- ### Slot Machine Simulation using Prototypes (JavaScript) Source: https://github.com/getify/you-dont-know-js/blob/2nd-ed/get-started/apB.md Simulates a slot machine with multiple reels, each having symbols and a spin mechanism. Demonstrates object-oriented patterns using prototypes. ```javascript function randMax(max) { return Math.trunc(1E9 * Math.random()) % max; } var reel = { symbols: [ "♠", "♥", "♦", "♣", "☺", "★", "☾", "☀" ], spin() { if (this.position == null) { this.position = randMax( this.symbols.length - 1 ); } this.position = ( this.position + 100 + randMax(100) ) % this.symbols.length; }, display() { if (this.position == null) { this.position = randMax( this.symbols.length - 1 ); } return this.symbols[this.position]; } }; var slotMachine = { reels: [ Object.create(reel), Object.create(reel), Object.create(reel) ], spin() { this.reels.forEach(function spinReel(reel){ reel.spin(); }); }, display() { var lines = []; // display all 3 lines on the slot machine for ( let linePos = -1; linePos <= 1; linePos++ ) { let line = this.reels.map( function getSlot(reel){ var slot = Object.create(reel); slot.position = ( reel.symbols.length + reel.position + linePos ) % reel.symbols.length; return slot.display(); } ); lines.push(line.join(" | ")); } return lines.join("\n"); } }; slotMachine.spin(); slotMachine.display(); // ☾ | ☀ | ★ // ☀ | ♠ | ☾ // ♠ | ♥ | ☀ slotMachine.spin(); slotMachine.display(); // ♦ | ♠ | ♣ // ♣ | ♥ | ☺ // ☺ | ♦ | ★ ``` -------------------------------- ### Immediately Invoked Function Expressions (IIFE) Source: https://github.com/getify/you-dont-know-js/blob/2nd-ed/get-started/apA.md Examples of Immediately Invoked Function Expressions (IIFE), both anonymous and named, including asynchronous variants. ```javascript // IIFE (function(){ .. })(); (function namedIIFE(){ .. })(); // asynchronous IIFE (async function(){ .. })(); (async function namedAIIFE(){ .. })(); ``` -------------------------------- ### Object Reference Copy Example Source: https://github.com/getify/you-dont-know-js/blob/2nd-ed/get-started/apA.md Illustrates how object values are assigned by reference. Assigning an object to a new variable copies the reference, not the object itself. ```javascript var myAddress = { street: "123 JS Blvd", city: "Austin", state: "TX" }; var yourAddress = myAddress; ``` -------------------------------- ### Getting a Character at a Specific Index (Negative Index) Source: https://github.com/getify/you-dont-know-js/blob/2nd-ed/types-grammar/ch2.md Retrieve a character using String.prototype.at(), which supports negative indices to count from the end of the string. ```javascript str = "abc"; str.at(-1); // "c" ``` -------------------------------- ### Scope Comparison: var vs. let Source: https://github.com/getify/you-dont-know-js/blob/2nd-ed/get-started/ch2.md Demonstrates the difference in scope between 'var' and 'let'. 'let' is block-scoped, while 'var' is function-scoped. ```javascript var adult = true; if (adult) { var myName = "Kyle"; let age = 39; console.log("Shhh, this is a secret!"); } console.log(myName); // Kyle console.log(age); // Error! ``` -------------------------------- ### Get Minimum Value Source: https://github.com/getify/you-dont-know-js/blob/2nd-ed/types-grammar/ch1.md Access the smallest positive value representable by the JavaScript number type. Values smaller than this may be rounded to zero. ```javascript Number.MIN_VALUE; ``` -------------------------------- ### Get Maximum Value Source: https://github.com/getify/you-dont-know-js/blob/2nd-ed/types-grammar/ch1.md Access the largest finite value representable by the JavaScript number type. Values exceeding this may not be accurately represented. ```javascript Number.MAX_VALUE; ``` -------------------------------- ### Pre-ES6 Equivalent using apply() Source: https://github.com/getify/you-dont-know-js/wiki/_Footer Demonstrates the pre-ES6 method of passing array elements as function arguments using Function.prototype.apply(). ```javascript foo.apply( null, [1,2,3] ); // 1 2 3 ``` -------------------------------- ### Check for Secure API URL Source: https://github.com/getify/you-dont-know-js/blob/2nd-ed/types-grammar/ch4.md Use a regular expression to check if the API_BASE_URL starts with 'https'. This operation is type-safe because API_BASE_URL is known to be a string. ```javascript // are we using the secure API URL? isSecureAPI = /^https/.test(API_BASE_URL); ``` -------------------------------- ### Classic Module Pattern (Singleton) Source: https://github.com/getify/you-dont-know-js/blob/2nd-ed/scope-closures/ch8.md Creates a single instance of a module with private state and a public API. The public method retains access to private data via closure. ```javascript var Student = (function defineStudent(){ var records = [ { id: 14, name: "Kyle", grade: 86 }, { id: 73, name: "Suzy", grade: 87 }, { id: 112, name: "Frank", grade: 75 }, { id: 6, name: "Sarah", grade: 91 } ]; var publicAPI = { getName }; return publicAPI; // ************************ function getName(studentID) { var student = records.find( student => student.id == studentID ); return student.name; } })(); Student.getName(73); // Suzy ``` -------------------------------- ### Pre-ES6 for...of Equivalent Source: https://github.com/getify/you-dont-know-js/wiki/_Footer Shows the equivalent of a for...of loop using pre-ES6 JavaScript syntax with Object.keys(). ```javascript var a = ["a","b","c","d","e"], k = Object.keys( a ); for (var val, i = 0; i < k.length; i++) { val = a[ k[i] ]; console.log( val ); } // "a" "b" "c" "d" "e" ```