From e7d147bb0fd671ec336a1889d329a4eedd5539fb Mon Sep 17 00:00:00 2001 From: Bryan C Guner Date: Wed, 10 Aug 2022 23:59:46 +0000 Subject: [PATCH] update --- src/pages/docs/javascript/part2-pojo.md | 5921 +---------------------- 1 file changed, 39 insertions(+), 5882 deletions(-) diff --git a/src/pages/docs/javascript/part2-pojo.md b/src/pages/docs/javascript/part2-pojo.md index a84b94e00a..71650d0741 100644 --- a/src/pages/docs/javascript/part2-pojo.md +++ b/src/pages/docs/javascript/part2-pojo.md @@ -28,7 +28,7 @@ Javascript considers most data types to be ‘primitive', these data types are i - Function — Reference #### 2. Identify when to use . vs \[\] when accessing values of an object - +```js let obj = { "one": 1, "two": 2 @@ -41,9 +41,10 @@ Javascript considers most data types to be ‘primitive', these data types are i // Choose the dot property accessor when the property name is known ahead of time. console.log(obj.two); +``` +#### 3. Write an object literal with a variable key using interpolation```js -#### 3. Write an object literal with a variable key using interpolation - +```js let keyName = "two"; // If the key is not known, you can use an alternative `[]` syntax for @@ -52,14 +53,15 @@ Javascript considers most data types to be ‘primitive', these data types are i [keyName]: 2 } console.log(obj2); +``` +#### 4. Use the obj\[key\] !== undefined pattern to check if a given variable that contains a key exists in an object```js -#### 4. Use the obj\[key\] !== undefined pattern to check if a given variable that contains a key exists in an object - - function doesKeyExist(obj, key) { +```js + function doesKeyExist(obj, key) { // obj[key] !== undefined // or: return key in obj; - } + }```js let course = { bootcamp: 'Lambda', @@ -67,14 +69,14 @@ Javascript considers most data types to be ‘primitive', these data types are i } console.log(doesKeyExist(course, 'course')); // => true console.log(doesKeyExist(course, 'name')); // => false - -#### 5. Utilize Object.keys and Object.values in a function - - function printKeys(object) { +``` +#### 5. Utilize Object`.keys and Object.values in a function```js +```js + function printKeys(object) { return Object.keys(object); - } + }```js - function printValues(object) { + function printValues(object) { return Object.values(object); } @@ -86,9 +88,9 @@ Javascript considers most data types to be ‘primitive', these data types are i dog: "Strelka", dog2: "Belka" })); - -#### 6. Iterate through an object using a for in loop - +``` +#### 6. Iterate through an object using a for in loop```js +```js let player = { name: "Sergey", skill: "hockey" @@ -99,10 +101,10 @@ Javascript considers most data types to be ‘primitive', these data types are i } console.log(Object.entries(player)); - -#### 7. Define a function that utilizes …rest syntax to accept an arbitrary number of arguments - - function restSum(...otherNums) { +``` +#### 7. Define a function that utilizes …rest syntax to accept an arbitrary number of arguments```js +```js + function restSum(...otherNums) { let sum = 0; console.log(otherNums); otherNums.forEach(function(num) { @@ -115,13 +117,13 @@ Javascript considers most data types to be ‘primitive', these data types are i console.log(restSum(3, 5, 6)); // => 14 console.log(restSum(1, 2, 3, 4, 5, 6, 7, 8, 9)); // => 45 console.log(restSum(0)); // => 0 - -#### 8. Use …spread syntax for Object literals and Array literals - +``` +#### 8. Use …spread syntax for Object literals and Array literals```js +```js let numArray = [1, 2, 3]; let moreNums = [...numArray, 4, 5, 6] - console.log(moreNums); + console.log(moreNums);```js let shoe = { color: "red", @@ -137,16 +139,16 @@ Javascript considers most data types to be ‘primitive', these data types are i console.log(newShoe); console.log(shoe); - -#### 9. Destructure an array to reference specific elements - - let arr = ['one', 'two', 'three']; +``` +#### 9. Destructure an array to reference specific elements```js +```js + let arr = ['one', 'two', 'three'];```js let [first] = arr; console.log(first); - -#### 10. Destructure an object to reference specific values - +``` +#### 10. Destructure an object to reference specific values```js +```js let me = { name: "Ian", instruments: ['bass', 'synth', 'guitar'], @@ -154,7 +156,7 @@ Javascript considers most data types to be ‘primitive', these data types are i brothers: ['Alistair'], sisters: ['Meghan'] } - } + }```js let { name, @@ -167,10 +169,10 @@ Javascript considers most data types to be ‘primitive', these data types are i console.log(name); console.log(musical_instruments); console.log(sisters); - -#### 11. Write a function that accepts a string as an argument and returns an object representing the count of each character in the array - - function charCount(inputString) { +``` +#### 11. Write a function that accepts a string as an argument and returns an object representing the count of each character in the array```js +```js + function charCount(inputString) { let res = inputString.split("").reduce(function(accum, el) { if (el in accum) { @@ -185,5849 +187,4 @@ Javascript considers most data types to be ‘primitive', these data types are i } console.log(charCount('aaabbbeebbcdkjfalksdfjlkasdfasdfiiidkkdingds')); - -### Review of Concepts - -#### 1. Identify the difference between const, let, and var declarations - -#### 2. Explain the difference between const, let, and var declarations - - var a = "a"; - -- `var` is the historical keyword used for variable declaration. -- `var` declares variables in function scope, or global scope if not inside a function. -- We consider `var` to be deprecated and it is never used in this course. - - - - let b = "b"; - -- `let` is the keyword we use most often for variable declaration. -- `let` declares variables in block scope. -- variables declared with `let` are re-assignable. - - - - const c = "c"; - -- `const` is a specialized form of `let` that can only be used to **initialize** a variable. -- Except when it is declared, you cannot assign to a `const` variable. -- `const` scopes variables the same way that `let` does. - -#### 3. Predict the evaluation of code that utilizes function scope, block scope, lexical scope, and scope chaining - -Consider this `run` function, inside which `foo` and `bar` have `function scope` . `i` and `baz` are scoped to the block expression. - - // function and block scope in this example - function run() { - var foo = "Foo"; - let bar = "Bar"; - - console.log(foo, bar); - - { - console.log(foo); - let baz = "Bazz"; - console.log(baz); - } - - console.log(baz); // ReferenceError - } - - run(); - -Notice that referencing `baz` from outside it's block results in JavaScript throwing a ReferenceError. - -Consider this `run` function, inside of which `foo` has `function scope` . - - function run() { - console.log(foo); // undefined - var foo = "Foo"; - console.log(foo); // Foo - } - - run(); - -Consider this `func1` function and it's nested scopes. - - // global scope - function func1(arg1) { - // func1 scope - - return function func2(arg2) { - // func2 scope - - return function func3(arg3) { - // func3 scope - - console.log(arg1, arg2, arg3); - } - } - } - -#### 6. Implement a closure and explain how the closure effects scope - - const adder = (arg1) => { - return (arg2) => { - return arg1 + arg2; - } - }; - - const func2 = adder(2); - const result = func2(2); - console.log(result); // => 4; - -#### 4. Define an arrow function - - const returnValue = (val) => val; - -This simple construct will create a function that accepts `val` as a parameter, and returns `val` immediately. We do not need to type `return val` , because this is a single-line function. - -Identically, we could write - - const returnValue = (val) => { - return val; - }; - -#### 5. Given an arrow function, deduce the value of `this` without executing the code - - function fDAdder(arr) { - console.log(this); - - return arr.reduce((acc, ele) => { - return acc + ele; - }); - }; - - fDAdder([1, 2, 4, 6]); - -If we use a function declaration style function, the `this` variable is set to the `global` object (i.e. `Object [global]` in Node. JS and `Window` in your browser). - - const adder = (arr) => { - console.log(this); - arr.reduce((acc, ele) => sum += ele); - }; - adder([1, 2, 4, 6]); - -In this example, we use a fat arrow style function. Note that when we declare a functions like this `this` becomes - -#### 7. Define a method that references this on an object literal - - const pokemon = { - firstname: 'Pika', - lastname: 'Chu', - getPokeName: function() { - const fullname = `${this.firstname} ${this.lastname}`; - return fullname; - } - }; - - console.log(pokemon.getPokeName()); - -#### 8. Utilize the built in Function\#bind on a callback to maintain the context of `this` - - const pokemon = { - firstname: 'Pika', - lastname: 'Chu', - getPokeName: function() { - const fullname = `${this.firstname} ${this.lastname}`; - return fullname; - } - }; - - const logPokemon = pokemon.getPokename.bind(pokemon); - - logPokemon('sushi', 'algorithms'); // Pika Chu loves sushi and algorithms - -#### 9. Given a code snippet, identify what `this` refers to - - function Person(name) { - // this.name = name; - // let that = this; - - setTimeout(function() { - // console.log(this); // => Window - // console.log(that); // => [Function] => Person - // this.sayName(); // => no method error - that.sayName(); - }, 1000); - } - - Person.prototype.sayName = function() { - console.log(this.name); - }; - - const jane = new Person("Jane"); - -``` - ---- - -# The Complete JavaScript Reference Guide - ---- - -### The Complete JavaScript Reference Guide - -
- -
### How to learn effectively - -**Learning**: The acquisition of skills and the ability to apply them in the future. - -**What makes an Effective learner?** - -- They are active listeners. -- They are engaged with the material. -- They are receptive of feedback. -- They are open to difficulty. - -**Why do active learning techniques feel difficult?** - -- It feels difficult because you are constantly receiving feedback, and so you are constantly adapting and perfecting the material. - -**Desirable Difficulty** - -- The skills we wish to obtain is often a difficult one. -- We want challenging but possible lessons based on current level of skill. - -**Effective learners space their practice** - -- Consistent effort > cramming => for **durable knowledge** - ---- - -### Getting visual feedback in your programs - -The first command we'll learn in JavaScript is `console.log`. This command is used to _print_ something onto the screen. As we write our first lines of code, we'll be using `console.log` frequently as a way to visually see the output of our programs. Let's write our first program: - - console.log("hello world"); - console.log("how are you?"); - -Executing the program above would print out the following: - - hello world - how are you? - -Nothing too ground breaking here, but pay close attention to the exact way we wrote the program. In particular, notice how we lay out the periods, parentheses, and quotation marks. We'll also terminate lines with semicolons (;). - -> _Depending on how you structure your code, sometimes you'll be able to omit semicolons at the end of lines. For now, you'll want to include them just as we do._ - -### Syntax - -We refer to the exact arrangement of the symbols, characters, and keywords as **syntax**. These details matter — your computer will only be able to "understand" proper JavaScript syntax. A programming language is similar to a spoken language. A spoken language like English has grammar rules that we should follow in order to be understood by fellow speakers. In the same way, a programming language like JavaScript has syntax rules that we ought to follow! - -As you write your first lines of code in this new language, you may make many syntax errors. Don't get frustrated! This is normal — all new programmers go through this phase. Every time we recognize an error in our code, we have an opportunity to reinforce your understanding of correct syntax. Adopt a growth mindset and learn from your mistakes. - -Additionally, one of the best things about programming is that we can get such immediate feedback from our creations. There is no penalty for making a mistake when programming. Write some code, run the code, read the errors, fix the errors, rinse and repeat! - -### Code comments - -Occasionally we'll want to leave **comments** or notes in our code. Commented lines will be ignored by our computer. This means that we can use comments to write plain english or temporarily avoid execution of some JavaScript lines. The proper _syntax_ for writing a comment is to begin the line with double forward slashes (`//`): - - // let's write another program!!! - console.log("hello world"); - - // console.log("how are you?"); - - console.log("goodbye moon"); - -The program above would only print: - - hello world - goodbye moon - -Comments are useful when annotating pieces of code to offer an explanation of how the code works. We'll want to strive to write straightforward code that is self-explanatory when possible, but we can also use comments to add additional clarity. The real art of programming is to write code so elegantly that it is easy to follow. - -**The Number Data Type** - -The **number** data type in JS is used to represent any numerical values, including integers and decimal numbers. - -**Basic Arithmetic Operators** - -Operators are the symbols that perform particular operations. - -- **+** (addition) -- **-** (subtraction) -- **asterisk** (multiplication) -- **/** (division) -- **%** (modulo) - -JS evaluates more complex expressions using the general math order of operations aka PEMDAS. - -- **PEMDAS** : Parentheses, Exponents, Multiplication, Division, Modulo, Addition, Subtraction. -- _To force a specific order of operation, use the group operator ( ) around a part of the expression._ - -**Modulo** : Very useful operation to check divisibility of numbers, check for even & odd, whether a number is prime, and much more! _(Discrete Math concept, circular problems can be solved with modulo)_ - -- Whenever you have a smaller number % a larger number, the answer will just be the initial small number. - console.log(7 % 10) // => 7; - -**The String Data Type** - -The **string** data type is a primitive data type that used to represent textual data. - -- can be wrapped by either **single** or **double** quotation marks, _best to choose one and stick with it for consistency_. -- If your string contains quotation marks inside, can layer single or double quotation marks to allow it to work. - "That's a great string"; (valid) - 'Shakespeare wrote, "To be or not to be"'; (valid) - 'That's a bad string'; (invalid) -- Alt. way to add other quotes within strings is to use template literals. -- \`This is a temp'l'ate literal ${function}\` // use ${} to invoke functions within. -- **.length** : property that can be appended -- empty strings have a length of zero. -- **indices** : indexes of data that begin at 0, can call upon index by using the bracket notation \[ \]. - console.log("bootcamp"\[0\]); // => "b" - console.log("bootcamp"\[10\]); // => "undefined" - console.log("boots"\[1 \* 2\]); // => "o" - console.log("boots"\["boot".length-1\]); // => "t" -- we can pass expressions through the brackets as well since JS always evaluates expressions first. -- The index of the last character of a string is always one less than it's length. -- **indexOf()** : method used to find the first index of a given character within a string. - console.log("bagel".indexOf("b")); // => 0 - console.log("bagel".indexOf("z")); // => -1 -- if the character inside the indexOf() search does not exist in the string, the output will be -1. -- the indexOf() search will return the first instanced index of the the char in the string. -- **concatenate** : word to describe joining strings together into a single string. - -**The Boolean Data Type** - -The **Boolean** data type is the simplest data type since there are only two values: **true** and **false**. - -- **Logical Operators** (B*oolean Operators*) are used to establish logic in our code. -- **!** (not) : reverses a Boolean value. - console.log(!true); // => false - console.log(!!false); // => false -- **Logical Order of Operations** : JS will evaluate !, then &&, then ||. -- **Short-Circuit Evaluation** : Because JS evalutes from left to right, expressions can "short-circuit". For example if we have true on the left of an || logical comparison, it will stop evaluating and yield true instead of wasting resources on processing the rest of the statement. - console.log(true || !false) // => stops after it sees "true ||" - -**Comparison Operators** - -All comparison operators will result in a boolean output. - -**The relative comparators** - -- **>** (greater than) -- **<** (less than) -- **>=** (greater than or equal to) -- **<=** (less than or equal to) -- **===** (equal to) -- **!==** (not equal to) - -Fun Fact: "a" < "b" is considered valid JS Code because string comparisons are compared lexicographically (meaning dictionary order), so "a" is less than "b" because it appears earlier! - -If there is ever a standstill comparison of two string lexicographically (i.e. app vs apple) the comparison will deem the shorter string lesser. - -**Difference between == and ===** - -#### === - -Strict Equality, will only return true if the two comparisons are entirely the same. - -#### == - -Loose Equality, will return true even if the values are of a different type, due to coercion. (Avoid using this) - -**Variables** - -Variables are used to store information to be referenced and manipulated in a program. - -- We initialize a variable by using the **let** keyword and a **=** single equals sign (assignment operator). - let bootcamp = "App Academy"; - console.log(bootcamp); // "App Academy" -- JS variable names can contain any alphanumeric characters, underscores, or dollar signs (cannot being with a number). -- If you do not declare a value for a variable, undefined is automatically set. - let bootcamp; - console.log(bootcamp); // undefined -- We can change the value of a previously declared variable (let, not const) by re-assigning it another value. -- **let** is the updated version of **var**; there are some differences in terms of hoisting and global/block scope - -**Assignment Shorthand** - -let num = 0; -num += 10; // same as num = num + 10 -num -= 2; // same as num = num — 2 -num /= 4; // same as num = num / 4 -num \*= 7; // same as num = num \* 7 - -- In general, any nonsensical arithmetic will result in **NaN** ; usually operations that include undefined. - -**Functions** - -A function is a procedure of code that will run when called. Functions are used so that we do not have to rewrite code to do the same thing over and over. (Think of them as 'subprograms') - -- **Function Declaration** : Process when we first initially write our function. -- Includes three things: -- Name of the function. -- A list of _parameters_ () -- The code to execute {} -- **Function Calls** : We can call upon our function whenever and wherever\* we want. (\*wherever is only after the initial declaration) -- JS evaluates code top down, left to right. -- When we execute a declared function later on in our program we refer to this as **invoking** our function. -- Every function in JS returns undefined unless otherwise specified. -- When we hit a **return** statement in a function we immediately exit the function and return to where we called the function. -- When naming functions in JS always use camelCase and name it something appropriate. - -Greate code reads like English and almost explains itself. Think: Elegant, readable, and maintainable! - -**Parameters and Arguments** - -- **Parameters** : Comma seperated variables specified as part of a function's declaration. -- **Arguments** : Values passed to the function when it is invoked. -- _If the number of arguments passed during a function invocation is different than the number of paramters listed, it will still work._ -- However, is there are not enough arguments provided for parameters our function will likely yield **Nan**. - -### Including Comments - -Comments are important because they help other people understand what is going on in your code or remind you if you forgot something yourself. Keep in mind that they have to be marked properly so the browser won't try to execute them. - -In JavaScript you have two different options: - -- Single-line comments — To include a comment that is limited to a single line, precede it with `//` -- Multi-line comments — In case you want to write longer comments between several lines, wrap it in `/*` and `*/` to avoid it from being executed - -### Variables in JavaScript - -Variables are stand-in values that you can use to perform operations. You should be familiar with them from math class. - -### var, const, let - -You have three different possibilities for declaring a variable in JavaScript, each with their own specialties: - -- `var` — The most common variable. It can be reassigned but only accessed within a function. Variables defined with `var` move to the top when the code is executed. -- `const` — Can not be reassigned and not accessible before they appear within the code. -- `let` — Similar to `const`, the `let` variable can be reassigned but not re-declared. - -### Data Types - -Variables can contain different types of values and data types. You use `=` to assign them: - -- Numbers — `var age = 23` -- Variables — `var x` -- Text (strings) — `var a = "init"` -- Operations — `var b = 1 + 2 + 3` -- True or false statements — `var c = true` -- Constant numbers — `const PI = 3.14` -- Objects — `var name = {firstName:"John", lastName:"Doe"}` - -There are more possibilities. Note that variables are case sensitive. That means `lastname` and `lastName` will be handled as two different variables. - -### Objects - -Objects are certain kinds of variables. They are variables that can have their own values and methods. The latter are actions that you can perform on objects. - -var person = { - -firstName:"John", - -lastName:"Doe", - -age:20, - -nationality:"German" - -}; - -### The Next Level: Arrays - -Next up in our JavaScript cheat sheet are arrays. Arrays are part of many different programming languages. They are a way of organizing variables and properties into groups. Here's how to create one in JavaScript: - -var fruit = \["Banana", "Apple", "Pear"\]; - -Now you have an array called `fruit` which contains three items that you can use for future operations. - -### Array Methods - -Once you have created arrays, there are a few things you can do with them: - -- `concat()` — Join several arrays into one -- `indexOf()` — Returns the first position at which a given element appears in an array -- `join()` — Combine elements of an array into a single string and return the string -- `lastIndexOf()` — Gives the last position at which a given element appears in an array -- `pop()` — Removes the last element of an array -- `push()` — Add a new element at the end -- `reverse()` — Sort elements in a descending order -- `shift()` — Remove the first element of an array -- `slice()` — Pulls a copy of a portion of an array into a new array -- `sort()` — Sorts elements alphabetically -- `splice()` — Adds elements in a specified way and position -- `toString()` — Converts elements to strings -- `unshift()` —Adds a new element to the beginning -- `valueOf()` — Returns the primitive value of the specified object - -### Operators - -If you have variables, you can use them to perform different kinds of operations. To do so, you need operators. - -### Basic Operators - -- `+` — Addition -- `-` — Subtraction -- `*` — Multiplication -- `/` — Division -- `(...)` — Grouping operator, operations within brackets are executed earlier than those outside -- `%` — Modulus (remainder ) -- `++` — Increment numbers -- `--` — Decrement numbers - -### Comparison Operators - -- `==` — Equal to -- `===` — Equal value and equal type -- `!=` — Not equal -- `!==` — Not equal value or not equal type -- `>` — Greater than -- `<` — Less than -- `>=` — Greater than or equal to -- `<=` — Less than or equal to -- `?` — Ternary operator - -### Logical Operators - -- `&&` — Logical and -- `||` — Logical or -- `!` — Logical not - -### Bitwise Operators - -- `&` — AND statement -- `|` — OR statement -- `~` — NOT -- `^` — XOR -- `<<` — Left shift -- `>>` — Right shift -- `>>>` — Zero fill right shift - -### Functions - -JavaScript functions are blocks of code that perform a certain task. A basic function looks like this: - -function name(parameter1, parameter2, parameter3) { - -// what the function does - -} - -As you can see, it consists of the `function` keyword plus a name. The function's parameters are in the brackets and you have curly brackets around what the function performs. You can create your own, but to make your life easier - there are also a number of default functions. - -### Outputting Data - -A common application for functions is the output of data. For the output, you have the following options: - -- `alert()` — Output data in an alert box in the browser window -- `confirm()` — Opens up a yes/no dialog and returns true/false depending on user click -- `console.log()` — Writes information to the browser console, good for debugging purposes -- `document.write()` — Write directly to the HTML document -- `prompt()` — Creates a dialogue for user input - -### Global Functions - -Global functions are functions built into every browser capable of running JavaScript. - -- `decodeURI()` — Decodes a Uniform Resource Identifier (URI) created by `encodeURI` or similar -- `decodeURIComponent()` — Decodes a URI component -- `encodeURI()` — Encodes a URI into UTF-8 -- `encodeURIComponent()` — Same but for URI components -- `eval()` — Evaluates JavaScript code represented as a string -- `isFinite()` — Determines whether a passed value is a finite number -- `isNaN()` — Determines whether a value is NaN or not -- `Number()` —- Returns a number converted from its argument -- `parseFloat()` — Parses an argument and returns a floating-point number -- `parseInt()` — Parses its argument and returns an integer - -### JavaScript Loops - -Loops are part of most programming languages. They allow you to execute blocks of code desired number of times with different values: - -for (before loop; condition **for** loop; execute after loop) { - -// what to do during the loop - -} - -You have several parameters to create loops: - -- `for` — The most common way to create a loop in JavaScript -- `while` — Sets up conditions under which a loop executes -- `do while` — Similar to the `while` loop but it executes at least once and performs a check at the end to see if the condition is met to execute again -- `break` —Used to stop and exit the cycle at certain conditions -- `continue` — Skip parts of the cycle if certain conditions are met - -### If — Else Statements - -These types of statements are easy to understand. Using them, you can set conditions for when your code is executed. If certain conditions apply, something is done, if not — something else is executed. - -if (condition) { - -// what to do if condition is met - -} **else** { - -// what to do if condition is not met - -} - -A similar concept to `if else` is the `switch` statement. However, using the switch you select one of several code blocks to execute. - -### Strings - -Strings are what JavaScript calls to text that does not perform a function but can appear on the screen. - -var person = "John Doe"; - -In this case, `John Doe` is the string. - -### Escape Characters - -In JavaScript, strings are marked with single or double-quotes. If you want to use quotation marks in a string, you need to use special characters: - -- `\'` — Single quote -- `\"` — Double quote - -Aside from that you also have additional escape characters: - -- `\\` — Backslash -- `\b` — Backspace -- `\f` — Form feed -- `\n` — New line -- `\r` — Carriage return -- `\t` — Horizontal tabulator -- `\v` — Vertical tabulator - -### String Methods - -There are many different ways to work with strings: - -- `charAt()` — Returns a character at a specified position inside a string -- `charCodeAt()` — Gives you the Unicode of a character at that position -- `concat()` — Concatenates (joins) two or more strings into one -- `fromCharCode()` — Returns a string created from the specified sequence of UTF-16 code units -- `indexOf()` — Provides the position of the first occurrence of a specified text within a string -- `lastIndexOf()` — Same as `indexOf()` but with the last occurrence, searching backward -- `match()` — Retrieves the matches of a string against a search pattern -- `replace()` — Find and replace specified text in a string -- `search()` — Executes a search for a matching text and returns its position -- `slice()` — Extracts a section of a string and returns it as a new string -- `split()` — Splits a string object into an array of strings at a specified position -- `substr()` — Similar to `slice()` but extracts a substring depending on a specified number of characters -- `substring()` — Also similar to `slice()` but can't accept negative indices -- `toLowerCase()` — Convert strings to lower case -- `toUpperCase()` — Convert strings to upper case -- `valueOf()` — Returns the primitive value (that has no properties or methods) of a string object - -### Regular Expression Syntax - -Regular expressions are search patterns used to match character combinations in strings. The search pattern can be used for text search and text to replace operations. - -### Pattern Modifiers - -- `e` — Evaluate replacement -- `i` — Perform case-insensitive matching -- `g` — Perform global matching -- `m` — Perform multiple line matching -- `s` — Treat strings as a single line -- `x` — Allow comments and whitespace in the pattern -- `U` — Ungreedy pattern - -### Brackets - -- `[abc]` — Find any of the characters between the brackets -- `[^abc]` — Find any character which is not in the brackets -- `[0-9]` — Used to find any digit from 0 to 9 -- `[A-z]` — Find any character from uppercase A to lowercase z -- `(a|b|c)` — Find any of the alternatives separated with `|` - -### Metacharacters - -- `.` — Find a single character, except newline or line terminator -- `\w` — Word character -- `\W` — Non-word character -- `\d` — A digit -- `\D` — A non-digit character -- `\s` — Whitespace character -- `\S` — Non-whitespace character -- `\b` — Find a match at the beginning/end of a word -- `\B` — A match not at the beginning/end of a word -- `\0` — NUL character -- `\n` — A new line character -- `\f` — Form feed character -- `\r` — Carriage return character -- `\t` — Tab character -- `\v` — Vertical tab character -- `\xxx` — The character specified by an octal number xxx -- `\xdd` — Character specified by a hexadecimal number dd -- `\uxxxx` — The Unicode character specified by a hexadecimal number XXXX - -### Quantifiers - -- `n+` — Matches any string that contains at least one n -- `n*` — Any string that contains zero or more occurrences of n -- `n?` — A string that contains zero or one occurrence of n -- `n{X}` — String that contains a sequence of X n's -- `n{X,Y}` — Strings that contain a sequence of X to Y n's -- `n{X,}` — Matches any string that contains a sequence of at least X n's -- `n$` — Any string with n at the end of it -- `^n` — String with n at the beginning of it -- `?=n` — Any string that is followed by a specific string n -- `?!n` — String that is not followed by a specific string ni - -### Numbers and Math - -In JavaScript, you can also work with numbers, constants and perform mathematical functions. - -### Number Properties - -- `MAX_VALUE` — The maximum numeric value representable in JavaScript -- `MIN_VALUE` — Smallest positive numeric value representable in JavaScript -- `NaN` — The "Not-a-Number" value -- `NEGATIVE_INFINITY` — The negative Infinity value -- `POSITIVE_INFINITY` — Positive Infinity value - -### Number Methods - -- `toExponential()` — Returns the string with a rounded number written as exponential notation -- `toFixed()` — Returns the string of a number with a specified number of decimals -- `toPrecision()` — String of a number written with a specified length -- `toString()` — Returns a number as a string -- `valueOf()` — Returns a number as a number - -### Math Properties - -- `E` — Euler's number -- `LN2` — The natural logarithm of 2 -- `LN10` — Natural logarithm of 10 -- `LOG2E` — Base 2 logarithm of E -- `LOG10E` — Base 10 logarithm of E -- `PI` — The number PI -- `SQRT1_2` — Square root of 1/2 -- `SQRT2` — The square root of 2 - -### Math Methods - -- `abs(x)` — Returns the absolute (positive) value of x -- `acos(x)` — The arccosine of x, in radians -- `asin(x)` — Arcsine of x, in radians -- `atan(x)` — The arctangent of x as a numeric value -- `atan2(y,x)` — Arctangent of the quotient of its arguments -- `ceil(x)` — Value of x rounded up to its nearest integer -- `cos(x)` — The cosine of x (x is in radians) -- `exp(x)` — Value of Ex -- `floor(x)` — The value of x rounded down to its nearest integer -- `log(x)` — The natural logarithm (base E) of x -- `max(x,y,z,...,n)` — Returns the number with the highest value -- `min(x,y,z,...,n)` — Same for the number with the lowest value -- `pow(x,y)` — X to the power of y -- `random()` — Returns a random number between 0 and 1 -- `round(x)` — The value of x rounded to its nearest integer -- `sin(x)` — The sine of x (x is in radians) -- `sqrt(x)` — Square root of x -- `tan(x)` — The tangent of an angle - -### Dealing with Dates in JavaScript - -You can also work with and modify dates and time with JavaScript. This is the next chapter in the JavaScript cheat sheet. - -### Setting Dates - -- `Date()` — Creates a new date object with the current date and time -- `Date(2017, 5, 21, 3, 23, 10, 0)` — Create a custom date object. The numbers represent a year, month, day, hour, minutes, seconds, milliseconds. You can omit anything you want except for a year and month. -- `Date("2017-06-23")` — Date declaration as a string - -### Pulling Date and Time Values - -- `getDate()` — Get the day of the month as a number (1-31) -- `getDay()` — The weekday as a number (0-6) -- `getFullYear()` — Year as a four-digit number (yyyy) -- `getHours()` — Get the hour (0-23) -- `getMilliseconds()` — The millisecond (0-999) -- `getMinutes()` — Get the minute (0-59) -- `getMonth()` — Month as a number (0-11) -- `getSeconds()` — Get the second (0-59) -- `getTime()` — Get the milliseconds since January 1, 1970 -- `getUTCDate()` — The day (date) of the month in the specified date according to universal time (also available for day, month, full year, hours, minutes etc.) -- `parse` — Parses a string representation of a date and returns the number of milliseconds since January 1, 1970 - -### Set Part of a Date - -- `setDate()` — Set the day as a number (1-31) -- `setFullYear()` — Sets the year (optionally month and day) -- `setHours()` — Set the hour (0-23) -- `setMilliseconds()` — Set milliseconds (0-999) -- `setMinutes()` — Sets the minutes (0-59) -- `setMonth()` — Set the month (0-11) -- `setSeconds()` — Sets the seconds (0-59) -- `setTime()` — Set the time (milliseconds since January 1, 1970) -- `setUTCDate()` — Sets the day of the month for a specified date according to universal time (also available for day, month, full year, hours, minutes etc.) - -### DOM Mode - -The DOM is the Document Object Model of a page. It is the code of the structure of a webpage. JavaScript comes with a lot of different ways to create and manipulate HTML elements (called nodes). - -### Node Properties - -- `attributes` — Returns a live collection of all attributes registered to an element -- `baseURI` — Provides the absolute base URL of an HTML element -- `childNodes` — Gives a collection of an element's child nodes -- `firstChild` — Returns the first child node of an element -- `lastChild` — The last child node of an element -- `nextSibling` — Gives you the next node at the same node tree level -- `nodeName` —Returns the name of a node -- `nodeType` — Returns the type of a node -- `nodeValue` — Sets or returns the value of a node -- `ownerDocument` — The top-level document object for this node -- `parentNode` — Returns the parent node of an element -- `previousSibling` — Returns the node immediately preceding the current one -- `textContent` — Sets or returns the textual content of a node and its descendants - -### Node Methods - -- `appendChild()` — Adds a new child node to an element as the last child node -- `cloneNode()` — Clones an HTML element -- `compareDocumentPosition()` — Compares the document position of two elements -- `getFeature()` — Returns an object which implements the APIs of a specified feature -- `hasAttributes()` — Returns true if an element has any attributes, otherwise false -- `hasChildNodes()` — Returns true if an element has any child nodes, otherwise false -- `insertBefore()` — Inserts a new child node before a specified, existing child node -- `isDefaultNamespace()` — Returns true if a specified namespaceURI is the default, otherwise false -- `isEqualNode()` — Checks if two elements are equal -- `isSameNode()` — Checks if two elements are the same node -- `isSupported()` — Returns true if a specified feature is supported on the element -- `lookupNamespaceURI()` — Returns the namespace URI associated with a given node -- `lookupPrefix()` — Returns a DOMString containing the prefix for a given namespace URI if present -- `normalize()` — Joins adjacent text nodes and removes empty text nodes in an element -- `removeChild()` — Removes a child node from an element -- `replaceChild()` — Replaces a child node in an element - -### Element Methods - -- `getAttribute()` — Returns the specified attribute value of an element node -- `getAttributeNS()` — Returns string value of the attribute with the specified namespace and name -- `getAttributeNode()` — Gets the specified attribute node -- `getAttributeNodeNS()` — Returns the attribute node for the attribute with the given namespace and name -- `getElementsByTagName()` — Provides a collection of all child elements with the specified tag name -- `getElementsByTagNameNS()` — Returns a live HTMLCollection of elements with a certain tag name belonging to the given namespace -- `hasAttribute()` — Returns true if an element has any attributes, otherwise false -- `hasAttributeNS()` — Provides a true/false value indicating whether the current element in a given namespace has the specified attribute -- `removeAttribute()` — Removes a specified attribute from an element -- `removeAttributeNS()` — Removes the specified attribute from an element within a certain namespace -- `removeAttributeNode()` — Takes away a specified attribute node and returns the removed node -- `setAttribute()` — Sets or changes the specified attribute to a specified value -- `setAttributeNS()` — Adds a new attribute or changes the value of an attribute with the given namespace and name -- `setAttributeNode()` — Sets or changes the specified attribute node -- `setAttributeNodeNS()` — Adds a new namespaced attribute node to an element - -### Working with the User Browser - -Besides HTML elements, JavaScript is also able to take into account the user browser and incorporate its properties into the code. - -### Window Properties - -- `closed` — Checks whether a window has been closed or not and returns true or false -- `defaultStatus` — Sets or returns the default text in the status bar of a window -- `document` — Returns the document object for the window -- `frames` — Returns all `