Docsity
Docsity

Prepare for your exams
Prepare for your exams

Study with the several resources on Docsity


Earn points to download
Earn points to download

Earn points by helping other students or get them with a premium plan


Guidelines and tips
Guidelines and tips

JavaScript CheatSheet: essential notions, Cheat Sheet of Javascript programming

In this cheat sheet we have essential notions and detailed explanation of JavaScript language

Typology: Cheat Sheet

2019/2020

Uploaded on 10/09/2020

anahitay
anahitay 🇺🇸

4.7

(16)

12 documents

Partial preview of the text

Download JavaScript CheatSheet: essential notions and more Cheat Sheet Javascript programming in PDF only on Docsity! Musa Al-hassy https://github.com/alhassy/JavaScriptCheatSheet March 12, 2020 JavaScript CheatSheet JavaScript is what everyone calls the language, but that name is trademarked (by Oracle, which inherited the trademark from Sun). Therefore, the official name of JavaScript is ECMAScript. The “ECMA” in “ECMAScript” comes from the organisation that hosts the primary standard, the European Computer Manufacturers Association. As the programming language of browsers, it is remarkably error-tolerant. It simply “fails silently” by giving error values such as undefined when things are not there or 0 / 0 ≈ NaN for nonsensical numeric expressions. By accident, there are two (mostly) interchangeable values null and undefined that de- note the absence of a meaningful value. Many operations that don’t produce meaningful values yield undefined simply because they have to yield some value. Here is a neat story about null. Types JavaScript considers types only when actually running the program, and even there often tries to implicitly convert values to the type it expects.  typeof gives a string value naming the type of its argument.  The functions Number, String, Boolean try to convert values into those types. console.log(typeof 4.5, typeof ’4.5’, typeof true) // ⇒ number string boolean console.log(8 * null // Multiplication needs numbers so null 7→ 0 , ’five’ * 2 // ’five’ is not a number, so ’five’ 7→ NaN , ’5’ - 1 // Subtraction needs numbers so ’5’ 7→ 5 , ’5’ + 1) // The first is a string, // so “+” denotes catenation, so 1 7→ ’1’ console.log(Number(’2.3’) // ⇒ 2.3 ,Number(’five’) // ⇒ NaN ,Boolean(’five’) // ⇒ true ,Boolean(’’) // ⇒ false ,String(NaN) // ⇒ ’NaN’ ,String(null)) // ⇒ ’null’ Variable Bindings let x0 = v0, ..., xn = vn; introduces n-new names xi each having value vi.  The vi are optional, defaulting to undefined.  The program crashes if any xi is already declared.  Later we use xi = wi; to update the name xi to refer to a new value wi. ◦ Augmented updates: x ⊕= y ≡ x = x ⊕ y ◦ Increment: x-- ≡ x += 1 ◦ Decrement: y-- ≡ x -= 1 let x, y = 1, z; console.log(x, y, z); // ⇒ undefined 1 undefined  In the same way, for the same purpose, we may use var but it has undesirable properties; e.g., its declarations are in the global scope and no error is raised using var x = · · · if x is already declared.  In the same way, we may use const to introduce names that are constant: Any attempt to change their values crashes the program.  A binding name may include dollar signs ($) or underscores (_) but no other punctuation or special characters. Scope and Statements Each binding has a scope, which is the part of the program in which the binding is visible. For bindings defined outside of any function or block, the scope is the whole program—you can refer to such bindings wherever you want. These are called global. let x = 10; { // new local scope let y = 20; var z = 30; console.log(x + y + z); // ⇒ 60 } // y is not visible here // console.log(y) // But z is! console.log(x + z); // ⇒ 40 global bindings are defined outside of any block and can be referenced anywhere. local bindings are defined within a block and can only be referenced in it. let, const declare local bindings; var always makes global ones! Besides the assignment statement, we also have the following statements:  Conditionals: if (condition) A else B  Blocks: If Si are statements, then {S0; ...; Sn;} is a statement.  The for/of syntax applies to arrays, strings, and other iterable structures —we will define our own later. // Print all the elements in the given list. for (let x of [’a’, 1, 2.3]) { console.log(‘x ≈ ${x}‘); } JavaScript is whitespace insensitive. Arithmetic In addition to the standard arithmetic operations, we have Math.max(x0, ..., xn) that takes any number of numbers and gives the largest; likewise Math.min(· · · ). Other common functions include Math.sqrt, Math.ceil, Math.round, Math.abs, and Math.random() which returns a random number between 0 and 1. Also, use % for remain- der after division. // Scientific notation: xey ≈ x × 10y console.log(1, 2.998e8, 100 + 4 * 11) 1 // Special numbers so that division “never crashes”. console.log(1/0, -1/0, Infinity - 10) // ⇒ Infinity -Infinity Infinity console.log(Infinity - Infinity, 0/0) // ⇒ NaN NaN // Random number in range min...Max Math.floor(Math.random() * (max - min) + min) NaN stands for “not a number”, it is what you get when a numeric expression has no meaningful value.  Any NaN in an arithmetic expressions swallows the whole expression into a NaN.  Number.isNaN(x) is true iff x is NaN. Everything is equal to itself, except NaN. Why? NaN denotes the result of nonsensical computations, and so is not equal to the result of any other nonsensical computation. console.log(NaN == NaN) // ⇒ false Booleans The empty string ”, list [], and 0, NaN are falsey —all else is truthy.  Note: (p < q < r) ≈ (p < q) < r, it is not conjunctive! console.log(true, false, 3 > 2, 1 < 2, 1 != 2, 4 <= 2 < 3) // Upper case letters come first, then lower case ones. console.log(’abc’ < ’def’, ’Z’ < ’a’) // Equality with coercions, and without. console.log(1.23 == ’1.23’, 1.23 === ’1.23’)  Precise Equality === is equality with no type coercions.  Applying the “not” ! operator will convert a value to Boolean type before negating it.  Precedence: Relationals like == and > are first, then “and” &&, then “or” ||.  The ternary operator: condition ? if_true : if_false console.log(null == undefined) // ⇒ true Only the empty values are coerced into being equal, no other value is equal to an empty value. As such, x != null means that x is not an empty value, and is in fact a real meaningful value. Since && and || are lazy, x || y means return x if x != false and otherwise return y; i.e., give me x if it’s non-empty, else y. Likewise, x && y means give me y, if x is nonempty, else give me the particular empty value x. console.log( 4 == 3 && 4 // 3 is truthy ,’’ == ’’ && 4 // ’’ is falsey ,’H’ == ’H’ && 4 // ’H’ is truthy , 0 == 0 && 4 // 0 is falsey , 4 == 0 || 4 // 0 is falsey ) Strings Any pair of matching single-quotes, backticks, or double-quotes will produce a string literal. However, backticks come with extra support: They can span multiple lines and produce formatted strings, where an expression can be evaluated if it is enclosed in ${· · · }. console.log(‘half of 100 is ${100 / 2}‘) // ⇒ half of 100 is 50  s.repeat(n) ≈ Get a new string by gluing n-copies of the string s.  Trim removes spaces, newlines, tabs, and other whitespace from the start and end of a string. console.log(" okay \n ".trim()); // ⇒ okay  s.toUpperCase() and s.toLowerCase() to change case.  s.padStart(l, p) ≈ Ensure s is of length ≥ l by padding it with p at the start. console.log(String(6).padStart(3, "0")); // ⇒ 006  s.replace(/./g, c => p(c) ? f(c) : ”) ≈ Keep only the characters that satisfy predicate p, then transform them via f. let s = ’abcde’.replace(/./g, c => ’ace’.includes(c) ? c.toUpperCase() : ’’) console.log(s); // ⇒ ACE The following methods also apply to arrays.  s.length ⇒ Length of string  s[i] ⇒ Get the i-th character from the start ◦ Unless 0 ≤ i < s.length, we have s[i] = undefined.  s.concat(t) ⇒ Glue together two strings into one longer string; i.e., s + t. console.log((’cat’ + ’enation’).toUpperCase()) // ⇒ CATENATION  s.includes(t) ⇒ Does s contain t as a substring?  s.indexOf(t) ⇒ Where does substring t start in s, or -1 if it’s not in s. ◦ To search from the end instead of the start, use lastIndexOf.  s.slice(m,n) ⇒ Get the substring between indices m (inclusive) and n (exclu- sive). ◦ n is optional, defaulting to s.length. ◦ If n is negative, it means start from the end: s.slice(-n) ≈ s.slice(s.length - n). ◦ s.slice() ⇒ Gives a copy of s.  There is no character type, instead characters are just strings of length 1.  You can “split” a string on every occurrence of another string to get a list of words, and which you can “join” to get a new sentence. s.split(d).join(d) ≈ s.  To treat a string as an array of characters, so we can apply array only methods such as f = reverse, we can use split and join: s.split(”).f().join(”)  Keeping certain characters is best done with regular expressions. 2 Note that if you try to destructure null or undefined, you get an error, much as you would if you directly try to access a property of those values. let {x0, ..., xn, ...w} = v ≡ let x0 = v.x0, ..., xn = v.xn; w = v; delete w.x0, ..., delete w.xn As usual, in arrow functions, we may destructure according to the shape of the elements of the array; e.g., if they are lists of at least length 2 we use (soFar, [x, y]) => · · · . This may be useful in higher order functions such as map, filter, reduce. Objects Objects and arrays (which are a specific kind of object) provide ways to group several values into a single value. Conceptually, this allows us to put a bunch of related things in a bag and run around with the bag, instead of wrapping our arms around all of the individual things and trying to hold on to them separately. These “things” are called properties. Arrays are just a kind of object specialised for storing sequences of things. Values of the type object are arbitrary collections of properties. One way to create an object is by using braces as an expression that lists properties as “name:value” pairs. 1. Almost all JavaScript values have properties. The exceptions are null and undefined. If you try to access a property on one of these nonvalues, you get an error. Properties are accessed using value.prop or value["prop"]. 2. Whereas value.x fetches the property of value named x, value[e] tries to eval- uate the expression e and uses the result, converted to a string, as the property name. 3. The dot notation only works with properties whose names look like valid (variable) binding names. So if you want to access a property named 2 or John Doe, you must use square brackets: value[2] or value["John Doe"]. 4. Unless value contains a property x, we have value.x ≈ undefined.  Hence, out of bounds indexing results in undefined. 5. Notice that the this keyword allows us to refer to other parts of this object literal. Above, info used the person object’s information, whereas speak did not. The “this” keyword is covered in more detail below. 6. Variables names in an object literal, like languages, denote a shorthand for a property with the same and value, but otherwise is no longer related to that bind- ing. This is useful if we want multiple objects to have the same binding; e.g., with let x = · · · , a = {name: ’a’, x}, b = {name: ’b’, x}, both objects have a x property: a.x and b.x. 7. We cannot dynamically attach new properties to the atomic types String, Number, Boolean; e.g., let x = 2; x.vest = ’purple’; console.log(x.vest); prints undefined. We can write it, but they “don’t stick”. 8. Below, we could have begun with the empty object then added properties dynam- ically: let person = {}; person.name = ‘musa‘; person.age = 29; .... let languages = [’js’, ’python’, ’lisp’] let person = { name: ’musa’ , age: 27 , ’favourite number’: 1 , languages // Shorthand for “languages: [’js’, ’python’, ’lisp’]” , age: 29 // Later bindings override earlier ones. // Two ways to attach methods; the second is a shorthand. , speak: () => ‘Salamun Alaykum! Hello!‘ , info () { return ‘${this.name} is ${this.age} years old!‘; } }; console.log(person.age) // ⇒ 29 // Trying to access non-existent properties // Reading a property that doesn’t exist will give you the value undefined. console.log(person.height) // ⇒ undefined // Is the property “name” in object “person”? console.log(’name’ in person); // ⇒ true // Updating a (computed) property let prop = ’favourite’ + ’ ’ + ’number’ person[’favourite number’] = 1792 console.log(person[prop]) // ⇒ 1792 // Dynamically adding a new property person.vest = ’purple’ console.log(person.vest) // ⇒ purple // Discard a property delete person[’favourite number’] // Get the list of property names that an object *currently* has. console.log(Object.keys(person)) // ⇒ [ ’name’, ’age’, ’languages’, ’vest’ ] // Variables can contribute to object definitions, but are otherwise unrelated. languages = [’C#’, ’Ruby’, ’Prolog’] console.log(person.languages) // ⇒ [ ’js’, ’python’, ’lisp’ ] // Calling an object’s methods console.log(person.speak()) // ⇒ Salamun Alaykum! Hello! console.log(person.info()) // ⇒ musa is 29 years old! You can define getters and setters to secretly call methods every time an object’s property is accessed. E.g., below num lets you read and write value as any number, but internally the getter method is called which only shows you the value’s remainder after division by the modulus property. let num = { modulus: 10 , get value() { return this._secret % this.modulus; } , set value(val) { this._secret = val; } } num.value = 99 console.log(num._secret) // ⇒ 99 console.log(num.value) // ⇒ 9 num.modulus = 12; console.log(num.value) // ⇒ 3 5  Exercise: Make an object num such that num.value varies, returning a random number less than 100, each time it’s accessed. Using get, set is a way to furnish prototypes with well-behaved properties that are readable or writable, or both. An object can also be used as a “key:value” dictionary: When we ‘look-up’ a key, we find a particular value. E.g., with ages = {mark: 12, james: 23, larry: 42} we use ages.mark to find Mark’s age. Similarly, objects can be used to simulate keyword arguments in function calls. The this Keyword Usually a method needs to do something with the object it was called on. When a function is called as a method — looked up as a property and immediately called, as in object.method() —– the binding called this in its body automatically points at the object that it was called on. function speak(line) { console.log(‘The ${this.type} rabbit says ’${line}’‘); } let whiteRabbit = {type: "white", speak}; let hungryRabbit = {type: "hungry", speak}; whiteRabbit.speak("Hola!"); // ⇒ The white rabbit says ’Hola!’ hungryRabbit.speak("Hey!") // ⇒ The hungry rabbit says ’Hey!’ You can think of this as an extra parameter that is passed in a different way. If you want to pass it explicitly, you can use a function’s call method, which takes the this value as its first argument and treats further arguments as normal parameters. speak.call(hungryRabbit, "Burp!"); // ⇒ The hungry rabbit says ’Burp!’ With call, an object can use a method belonging to another object. E.g., below we use whiteRabbit’s speaking method with its this keywords referring to exoticRabbit. let exoticRabbit = {type: ’exotic’} whiteRabbit.speak.call(exoticRabbit, ‘Jambo!‘) // ⇒ The exotic rabbit says ’Jambo!’ Since each function has its own this binding, whose value depends on the way it is called, you cannot refer to the this of the wrapping scope in a regular function defined with the function keyword. Arrow functions are different —they do not bind their own this but can see the this binding of the scope around them. Thus, you can do something like the following code, which references this from inside a local function: function normalise() { console.log(this.coords.map(n => n / this.length)); } normalise.call({coords: [0, 2, 3], length: 5}); // ⇒ [0, 0.4, 0.6] If we had written the argument to map using the function keyword, the code wouldn’t work. Object-Oriented Programming In English, prototype means a preliminary model of something from which other forms are developed or copied. As such, a prototypical object is an object denoting the original or typical form of something. In addition to their properties, JavaScript objects also have prototype —i.e., another object that is used as a source of additional properties. When an object gets a request for a property that it does not have, its prototype will be searched for the property, then the prototype’s prototype, and so on.  Object.getPrototypeOf(x) returns the prototype of an object x. For example, arrays are derived from Array.prototype which is derived from Object.prototype —which is the great ancestral prototype, the entity behind almost all object. Object.prototype provides a few methods that show up in all objects, such as toString, which converts an object to a string representation.  We can use the Object.getOwnPropertyNames(x) to get all the property names linked to object x. It is occasionally useful to know whether an object was derived from a specific class. For this, JavaScript provides a binary operator called instanceof. Almost every object is an instance of Object.  x instanceof y ≈ Object.getPrototypeOf(x) == y.prototype // “Object” includes “toString”, and some other technical utilities. console.log(Object.getOwnPropertyNames(Object.prototype)) // Some true facts console.log( {} instanceof Object , [] instanceof Array , Math.max instanceof Function , Math.max instanceof Object) // Since Function derives from Object // “Object” has no parent prototype. console.log(Object.getPrototypeOf(Object.prototype)); // ⇒ null (Extension Methods / Open Classes) To attach a new property to a ‘kind’ of object, we simply need to attach it to the prototype —since all those ‘kinds’ of objects use the prototype’s properties. Let’s attach a new method that can be used with any array. Array.prototype.max = function () { console.log(’ola’); return Math.max(...this) } console.log([3,1,5].max()); // ⇒ Prints “ola”, returns 5 console.log(Object.getOwnPropertyNames(Array.prototype)) // ⇒ Includes length, slice, ..., and our new “max” from above When you call the String function (which converts a value to a string) on an object, it will call the toString method on that object to try to create a meaningful string from it. Array.prototype.toString = function() { return this.join(’ and ’); }; console.log(String([1, 2, 3])) // ⇒ 1 and 2 and 3 6 (Overriding) When you add a property to an object, whether it is present in the pro- totype or not, the property is added to the object itself. If there was already a property with the same name in the prototype, this property will no longer affect the object, as it is now hidden behind the object’s own property. Array.prototype.colour = ’purple’ let xs = [1, 2, 3] console.log(xs.colour) // ⇒ purple xs.colour = ’green’ console.log(xs.colour) // ⇒ green console.log(Array.prototype.colour) // ⇒ purple You can use Object.create to create an object with a specific prototype. The de- fault prototype is Object.prototype. For the most part, Object.create(someObject) ≈ { ...someObject }; i.e., we copy the properties of someObject into an empty object, thereby treating someObject as a prototype from which we will build more sophisticated objects. Unlike other object-oriented languages where Object sits as the ancestor of all objects, in JavaScript it is possible to create objects with no prototype parent! // Empty object that *does* derive from “Object” let basic = {} console.log( basic instanceof Object // ⇒ true , "toString" in basic) // ⇒ true // Empty object that does not derive from “Object” let maximal = Object.create(null); console.log( maximal instanceof Object // ⇒ false , "toString" in maximal) // ⇒ false Prototypes let us define properties that are the same for all instances, but properties that differ per instance are stored directly in the objects themselves. E.g., the prototypical person acts as a container for the properties that are shared by all people. An individual person object, like kathy below, contains properties that apply only to itself, such as its name, and derives shared properties from its prototype. // An example object prototype let prototypicalPerson = {}; prototypicalPerson._world = 0; prototypicalPerson.speak = function () { console.log(‘I am ${this.name}, a ${this.job}, in a world of ‘ + ‘${prototypicalPerson._world} people.‘) } prototypicalPerson.job = ‘farmer‘; // Example use: Manually ensure the necessary properties are setup // and then manually increment the number of people in the world. let person = Object.create(prototypicalPerson); person.name = ‘jasim‘; prototypicalPerson._world++; person.speak() // ⇒ I am jasim, a farmer, in a world of 1 people. // Another person requires just as much setup let kathy = { ...prototypicalPerson }; // Same as “Object.create(· · · )” kathy.name = ‘kathy‘; prototypicalPerson._world++; kathy.speak() // ⇒ I am kathy, a farmer, in a world of 2 people. Classes are prototypes along with constructor functions! A class defines the shape of a kind of object; i.e., what properties it has; e.g., a Person can speak, as all people can, but should have its own name property to speak of. This idea is realised as a prototype along with a constructor function that ensures an instance object not only derives from the proper prototype but also ensures it, itself, has the properties that instances of the class are supposed to have. let prototypicalPerson = {}; prototypicalPerson._world = 0; prototypicalPerson.speak = function () { console.log(‘I am ${this.name}, a ${this.job}, in a world of ‘ + ‘${prototypicalPerson._world} people.‘) } function makePerson(name, job = ‘farmer‘) { let person = Object.create(prototypicalPerson); person.name = name; person.job = job; prototypicalPerson._world++; return person; } // Example use let jasim = makePerson(‘jasim‘); jasim.speak() // I am jasim, a farmer, in a world of 1 people. makePerson(‘kathy‘).speak() // I am kathy, a farmer, in a world of 2 people. We can fuse these under one name by making the prototype a part of the constructor.  By convention, the names of constructors are capitalised so that they can easily be distinguished from other functions. function Person(name, job = ‘farmer‘) { this.name = name; this.job = job; Person.prototype._world++; } Person.prototype._world = 0; Person.prototype.speak = function () { console.log(‘I am ${this.name}, a ${this.job}, in a world of ‘ + ‘${Person.prototype._world} people.‘) } // Example use let jasim = Object.create(Person.prototype) Person.call(jasim, ‘jasim‘) jasim.speak() // ⇒ I am jasim, a farmer, in a world of 1 people. // Example using shorthand let kasim = new Person (‘kathy‘) kasim.speak() // ⇒ I am kathy, a farmer, in a world of 2 people. If you put the keyword new in front of a function call, the function is treated as a con- structor. This means that an object with the right prototype is automatically created, bound to this in the function, and returned at the end of the function. 7
Docsity logo



Copyright © 2024 Ladybird Srl - Via Leonardo da Vinci 16, 10126, Torino, Italy - VAT 10816460017 - All rights reserved