Section 1

Preview this deck

return

Front

Star 0%
Star 0%
Star 0%
Star 0%
Star 0%

0.0

0 reviews

5
0
4
0
3
0
2
0
1
0

Active users

0

All-time users

0

Favorites

0

Last updated

6 years ago

Date created

Mar 1, 2020

Cards (185)

Section 1

(50 cards)

return

Front

exists a function

Back

null === undefined // false null == undefined // true

Front

null === undefined // false null == undefined // true

Back

10!

Front

10 factorial

Back

EVENT EQUENE

Front

The browser has an event loop which checks the event queue and processes pending events. For example, if an event happens in the background (e.g., a script onload event) while the browser is busy (e.g., processing an onclick), the event gets appended to the queue. When the onclick handler is complete, the queue is checked and the event is then handled (e.g., the onload script is executed). Similarly, setTimeout() also puts execution of its referenced function into the event queue if the browser is busy.

Back

( ) operator

Front

Using the example above, toCelsius refers to the function object, and toCelsius() refers to the function result. Accessing a function without () will return the function definition instead of the function result:

Back

JavaScript Types are Dynamic

Front

JavaScript has dynamic types. This means that the same variable can be used to hold different data types:

Back

closure

Front

Back

\

Front

backslash

Back

setTimeout()

Front

Calls a function or evaluates an expression after a specified number of milliseconds setTimeout(function(){ alert("Hello"); }, 3000);

Back

use strict

Front

a way to voluntarily enforce stricter parsing and error handling on your JavaScript code at runtime. Code errors that would otherwise have been ignored or would have failed silently will now generate errors or throw exceptions. In general, it is a good practice.

Back

= is the assign operator

Front

Back

comments

Front

code after // or between / and / will be treated as comment

Back

for (let i = 0; i < 5; i++) { setTimeout(function() { console.log(i); }, i * 1000 ); }

Front

It will print 0 1 2 3 4, because we use let instead of var here. The variable i is only seen in the for loop's block scope.

Back

Accessing Object Methods

Front

objectName.methodName() If you access a method without the () parentheses, it will return the function definition:

Back

"5" + 5 = 55

Front

When adding a number and a string, JavaScript will treat the number as a string.

Back

object key

Front

When setting an object property, JavaScript will implicitly stringify the parameter value. In this case, since b and c are both objects, they will both be converted to "[object Object]"

Back

CSS

Front

Cascading Style Sheets (CSS) are used to describe the appearance or presentation of content on a webpage.

Back

NaN

Front

The NaN property represents a value that is "not a number". This special value results from an operation that could not be performed either because one of the operands was non-numeric (e.g., "abc" / 4), or because the result of the operation is non-numeric. A better solution would either be to use value !== value, which would only produce true if the value is equal to NaN. Also, ES6 offers a new Number.isNaN() function, which is a different and more reliable than the old global isNaN() function.

Back

this keyword

Front

In a function definition, this refers to the "owner" of the function. In the example above, this is the person object that "owns" the fullName function. In other words, this.firstName means the firstName property of this object.

Back

common html events

Front

<element event='some JavaScript'> onchange An HTML element has been changed onclick The user clicks an HTML element onmouseover The user moves the mouse over an HTML element onmouseout The user moves the mouse away from an HTML element onkeydown The user pushes a keyboard key onload The browser has finished loading the page

Back

parameters vs arguments

Front

Function parameters are listed inside the parentheses () in the function definition. Function arguments are the values received by the function when it is invoked.

Back

HTTP

Front

HyperText Transfer Protocol (HTTP) is used to deliver HTML and other hypermedia documents on the web.

Back

JS quotes

Front

JavaScript has dynamic types. This means that the same variable can be used to hold different data types:

Back

hoisting (function () { try { throw new Error(); } catch (x) { var x = 1, y = 2; console.log(x); } console.log(x); console.log(y); })();

Front

var statements are hoisted (without their value initialization) to the top of the global or function scope it belongs to, even when it's inside a with or catch block. However, the error's identifier is only visible inside the catch block. It is equivalent to: (function () { var x, y; // outer and hoisted try { throw new Error(); } catch (x / inner /) { x = 1; // inner x, not the outer one y = 2; // there is only one y, which is in the outer scope console.log(x / inner /); } console.log(x); console.log(y); })();

Back

HTML

Front

HyperText Markup Language (HTML) is used to describe and define the content of a webpage.

Back

Object Methods

Front

A method is a function stored as a property. Objects can also have methods. Methods are actions that can be performed on objects. Methods are stored in properties as function definitions. var person = { firstName: "John", lastName : "Doe", id : 5566, fullName : function() { return this.firstName + " " + this.lastName; } }

Back

javascript objects

Front

containers for variables called properties and methods

Back

return statement

Front

When JavaScript reaches a return statement, the function will stop executing.

Back

Accessing Object Properties

Front

You can access object properties in two ways: objectName.propertyName or objectName["propertyName"]

Back

{ }

Front

curly bracket

Back

JS

Front

JavaScript is the programming language that runs in your browser. You can use it to add interactivity and other dynamic features to your website or application. With the advent of Node.js, you can also run JavaScript on the server.

Back

javascript identifiers

Front

the first letter must be a letter, an underscore _, or a dollar sign. Subsequent characters may be letters digits, underscores, or dollar signs

Back

Local Variables

Front

Variables declared within a JavaScript function, become LOCAL to the function. Local variables can only be accessed from within the function.

Back

console.log(sum(2,3)); // Outputs 5 console.log(sum(2)(3)); // Outputs 5

Front

function sum(x) { if (arguments.length == 2) { return arguments[0] + arguments[1]; } else { return function(y) { return x + y; }; } }

Back

How do you add an element at the begining of an array? How do you add one at the end?

Front

var myArray = ['a', 'b', 'c', 'd']; myArray.push('end'); myArray.unshift('start'); console.log(myArray); // ["start", "a", "b", "c", "d", "end"] With ES6, one can use the spread operator: myArray = ['start', ...myArray]; myArray = [...myArray, 'end']; Or, in short: myArray = ['start', ...myArray, 'end'];

Back

var hero = { _name: 'John Doe', getSecretIdentity: function (){ return this._name; } }; var stoleSecretIdentity = hero.getSecretIdentity;

Front

The first console.log prints undefined because we are extracting the method from the hero object, so stoleSecretIdentity() is being invoked in the global context (i.e., the window object) where the _name property does not exist.

Back

Object Properties

Front

The name:values pairs in JavaScript objects are called properties:

Back

breaking longlines

Front

If a JavaScript statement does not fit on one line, the best place to break it is after an operator:

Back

typeOf(undefined)

Front

is undefined

Back

a unary operation is an operation with only one operand, i.e. a single input

Front

goes

Back

var x = 21; var girl = function () { console.log(x); var x = 20; }; girl ();

Front

Neither 21, nor 20, the result is undefined It's because JavaScript initialization is not hoisted. (Why doesn't it show the global value of 21? The reason is that when the function is executed, it checks that there's a local x variable present but doesn't yet declare it, so it won't look for global one.)

Back

promise

Front

Back

semi column

Front

The reason for this has to do with the fact that semicolons are technically optional in JavaScript (although omitting them is generally really bad form). As a result, when the line containing the return statement (with nothing else on the line) is encountered in foo2(), a semicolon is automatically inserted immediately after the return statement.

Back

console.log(0.1 + 0.2); console.log(0.1 + 0.2 == 0.3);

Front

An educated answer to this question would simply be: "You can't be sure. it might print out 0.3 and true, or it might not. Numbers in JavaScript are all treated with floating point precision, and as such, may not always yield the expected results."

Back

JavaScript Expressions

Front

An expression is a combination of values, variables, and operators, which computes to a value. The computation is called an evaluation.

Back

typeOf(null)

Front

is an Object

Back

javascript is a loosely typed language

Front

string + number => string

Back

hoisting

Front

Back

[ ]

Front

square bracket

Back

closure

Front

an inner function that has access to the variables in the outer (enclosing) function's scope chain. The closure has access to variables in three scopes; specifically: (1) variable in its own scope, (2) variables in the enclosing function's scope, and (3) global variables.

Back

Section 2

(50 cards)

Re-Declaring JavaScript Variables

Front

when a js variable is redeclared, it will not lose its value. var carName = "Volvo"; var carName; //still have the value Volvo

Back

NaN is a number: typeof NaN returns number:

Front

Back

slice(start, end)

Front

end is not included

Back

Assignment Operator

Front

=, +=, -=, =, /=, %/, *=

Back

Number Methods

Front

- num.toString() - num.toExponential(num(optional, defines the number of characters behind the decimal point)) ->returns a string, with a number rounded and written using exponential notation. - num.toFixed(num(optional, # of specific decimals)) returns a string, with the number written with a specified number of decimals: - num.toPrecision(num(optional)) returns a string, with a number written with a specified length: -num.valueOf() returns a number as a number. -> The valueOf() method is used internally in JavaScript to convert Number objects to primitive values. There is no reason to use it in your code. All JavaScript data types have a valueOf() and a toString() method. Global JavaScript Methods Converting Variables to Numbers The Number() method The parseInt() method -> parseInt() parses a string and returns a whole number. Spaces are allowed. Only the first number is returned: The parseFloat() method -> parseFloat() parses a string and returns a number. Spaces are allowed. Only the first number is returned: If the number cannot be converted, NaN (Not a Number) is returned Number Properties Property Description MAX_VALUE Returns the largest number possible in JavaScript MIN_VALUE Returns the smallest number possible in JavaScript POSITIVE_INFINITY Represents infinity (returned on overflow) NEGATIVE_INFINITY Represents negative infinity (returned on overflow) NaN Represents a "Not-a-Number" value Number Properties Cannot be Used on Variables Number properties belongs to the JavaScript's number object wrapper called Number. These properties can only be accessed as Number.MAX_VALUE. Using myNumber.MAX_VALUE, where myNumber is a variable, expression, or value, will return undefined:

Back

The toPrecision() Method

Front

returns string var x = 9.656; x.toPrecision(); // returns 9.656 x.toPrecision(2); // returns 9.7 x.toPrecision(4); // returns 9.656 x.toPrecision(6); // returns 9.65600

Back

comparison operators

Front

Operator Description == 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

Back

replace()

Front

The replace() method does not change the string it is called on. It returns a new string. the replace() method replaces only the first match:

Back

undefined null

Front

undefined has both undefined value and type null has null value, but object type

Back

JS String Operators

Front

when used on strings, the + operator is called the concatenation operator.

Back

backslash escape character

Front

The backslash (\) escape character turns special characters into string characters: Code Result Description \' ' Single quote \" " Double quote \\ \ Backslash

Back

Operator Precedence Values

Front

in general (highest first): ( ) -> expression grouping accessing the attribute ++ ! typeOf normal arithmetic operations non equal comparison operations in instanceof equal/unequal comparison operations tertiary operation assignment

Back

complex data

Front

typeof can return one of two complex types: function object -> both objects, arrays and null, in javascript arrays are objects

Back

Arrays are Objects

Front

Arrays are a special type of objects. The typeof operator in JavaScript returns "object" for arrays. Because of this, you can have variables of different types in the same Array. But, JavaScript arrays are best described as arrays. Arrays use numbers to access its "elements". In this example, person[0] returns John: Objects use names to access its "members". In this example, person.firstName returns John:

Back

To replace case insensitive, use a regular expression with an /i flag (insensitive):

Front

str = "Please visit Microsoft!"; var n = str.replace(/MICROSOFT/i, "W3Schools");

Back

You can declare many variables in one statement

Front

var person = "John Doe", carName = "Volvo", price = 200; A declaration can span multiple lines var person = "John Doe", carName = "Volvo", price = 200;

Back

typeof Infinity; // returns "number"

Front

Back

x.toString();

Front

Back

Arrays properties and methos

Front

.length .sort() accessing the last element of array, array doesn't take in negative index fruits = ["Banana", "Orange", "Apple", "Mango"]; var last = fruits[fruits.length - 1]; .forEach(function) .push(element) -> add add the end; use [] may create holes, empty Array.isArray(array) fruits instanceof Array; // returns true

Back

Type Operators

Front

Operator Description typeof Returns the type of a variable instanceof Returns true if an object is an instance of an object type

Back

str.length

Front

returns the number of characters in the given string (int)

Back

There are 3 methods for extracting string characters: charAt(position) charCodeAt(position) Property access [ ]

Front

Back

A string can be converted to an array with the split() method:

Front

var txt = "a,b,c,d,e"; // String txt.split(","); // Split on commas txt.split(" "); // Split on spaces txt.split("|"); // Split on pipe If the separator is omitted, the returned array will contain the whole string in index [0]. If the separator is "", the returned array will be an array of single characters:

Back

JavaScript Numbers are Always 64-bit Floating Point

Front

The maximum number of decimals is 17, but floating point arithmetic is not always 100% accurate: var x = 0.2 + 0.1; // x will be 0.30000000000000004 var x = (0.2 10 + 0.1 10) / 10; // x will be 0.3

Back

lastIndexOf()

Front

returns the index of the last occurrence of a specified text in a string Both methods accept a second parameter as the starting position for the search:

Back

Comparing two JavaScript objects will always return false.

Front

Comparing two JavaScript objects will always return false.

Back

JavaScript Types are Dynamic

Front

same variable can be used to hold different data types: var x; // Now x is undefined x = 5; // Now x is a Number x = "John"; // Now x is a String

Back

All string methods return a new string. They don't modify the original string. Formally said: Strings are immutable: Strings cannot be changed, only replaced

Front

var text2 = text1.toUpperCase(); var text2 = text1.toLowerCase(); var text3 = text1.concat(" ", text2); The trim() method removes whitespace from both sides of a string:

Back

Infinity (or -Infinity) is the value JavaScript will return if you calculate a number outside the largest possible number.

Front

var x = 2 / 0; // x will be Infinity var y = -2 / 0; // y will be -Infinity

Back

var x = "100"; var y = "10"; var z = x / y; // z will be 10 var x = "100"; var y = "10"; var z = x - y; // z will be 90 but not with +

Front

JavaScript will try to convert strings to numbers in all numeric operations:

Back

A safer way to break up a string, is to use string addition:

Front

document.getElementById("demo").innerHTML = "Hello " + "Dolly!";

Back

Integers (numbers without a period or exponent notation) are accurate up to 15 digits.

Front

var x = (0.2 10 + 0.1 10) / 10; // x will be 0.3

Back

var str = "Please locate where 'locate' occurs!"; var pos = str.search("locate");

Front

the search() method searches a string for a specified value and returns the position of the match:

Back

The Number() Method

Front

Number(true); // returns 1 Number(false); // returns 0 Number("10"); // returns 10 Number(" 10"); // returns 10 Number("10 "); // returns 10 Number(" 10 "); // returns 10 Number("10.33"); // returns 10.33 Number("10,33"); // returns NaN Number("10 33"); // returns NaN Number("John"); // returns NaN

Back

substring(start, end) substr(start, length)

Front

The difference is that substring() cannot accept negative indexes. substr - The difference is that the second parameter specifies the length of the extracted part.

Back

logical operators

Front

Operator Description && logical and || logical or ! logical not

Back

indexOf(

Front

returns the index of (the position of) the first occurrence of a specified text in a string: Both methods accept a second parameter as the starting position for the search:

Back

var x = 100 / "Apple"; isNaN(x); // returns true because x is Not a Number

Front

global JavaScript function isNaN()

Back

Arithmetic Operators

Front

+, -, *, /, %, ++, --

Back

x.toExponential(2);

Front

Back

parseFloat()

Front

parseFloat() parses a string and returns a number. Spaces are allowed. Only the first number is returned: parseFloat("10"); // returns 10 parseFloat("10.33"); // returns 10.33 parseFloat("10 20 30"); // returns 10 parseFloat("10 years"); // returns 10 parseFloat("years 10"); // returns NaN

Back

declaring a variable

Front

after the declaration, the variable has no value, or has the value of undefined

Back

Primitive Data

Front

typeof can return one of these primitive types string number boolean undefined

Back

list String methos

Front

All string methods return a new string. They don't modify the original string. Formally said: Strings are immutable: Strings cannot be changed, only replaced. - length find a string in a string: - indexOf(str, start(optional)) - lastIndexOf(str, start(optional)) - search(str/regex) extracting string parts - slice (start, end(optional, end not included)) -> returns the sliced string, (takes negative index, Negative positions do not work in Internet Explorer 8 and earlier. ) - substring (start, end (optional)) -> similar to slice but can't accept negative indexes - substr (start, length(optional)) -> takes negative parameter for the start replace a string content - replace(toBeReplaced, new str) -> only replace the first match, and the updated string is returned, the string it called on is not changed - can use regex to replace insensitive and global matches - .toUpperCase() - .toLowerCase() - the original string is not changed var text3 = text1.concat(" ",text2,"check","another one"); -> join two or more strings String.trim() -> removes white spaces on both sides of the string You can also use the replace solution above to add a trim function to the JavaScript String.prototype: Extracting String Characters - charAt(position) - charCodeAt(position) - Property access [ ] //not recommend Converting a String to an Array txt.split("char") If the separator is omitted, the returned array will contain the whole string in index [0]. If the separator is "", the returned array will be an array of single characters:

Back

The valueOf() Method

Front

valueOf() returns a number as a number. var x = 123; x.valueOf(); // returns 123 from variable x (123).valueOf(); // returns 123 from literal 123 (100 + 23).valueOf(); // returns 123 from expression 100 + 23

Back

To replace all matches, use a regular expression with a /g flag (global match):

Front

str = "Please visit Microsoft and Microsoft!"; var n = str.replace(/Microsoft/g, "W3Schools");

Back

You can also break up a code line within a text string with a single backslash:

Front

document.getElementById("demo").innerHTML = "Hello \ Dolly!"; The \ method is not the preferred method. It might not have universal support. Some browsers do not allow spaces behind the \ character.

Back

The parseInt() Method

Front

parseInt() parses a string and returns a whole number. Spaces are allowed. Only the first number is returned: parseInt("10"); // returns 10 parseInt("10.33"); // returns 10 parseInt("10 20 30"); // returns 10 parseInt("10 years"); // returns 10 parseInt("years 10"); // returns NaN

Back

toFixed()

Front

toFixed() returns a string, with the number written with a specified number of decimals: var x = 9.656; x.toFixed(0); // returns 10 x.toFixed(2); // returns 9.66 x.toFixed(4); // returns 9.6560 x.toFixed(6); // returns 9.656000

Back

String methods

Front

Primitive values, like "John Doe", cannot have properties or methods (because they are not objects). But with JavaScript, methods and properties are also available to primitive values, because JavaScript treats primitive values as objects when executing methods and properties.

Back

Section 3

(50 cards)

Array.reduce()

Front

The reduce() method does not reduce the original array. var numbers1 = [45, 4, 9, 16, 25]; var sum = numbers1.reduce(myFunction); function myFunction(total, value, index, array) { return total + value; } The reduce() method can accept an initial value: var sum = numbers1.reduce(myFunction, 100);

Back

The Compare Function

Front

The purpose of the compare function is to define an alternative sort order. The compare function should return a negative, zero, or positive value, depending on the arguments: function(a, b){return a - b} When the sort() function compares two values, it sends the values to the compare function, and sorts the values according to the returned (negative, zero, positive) value. If the result is negative a is sorted before b. If the result is positive b is sorted before a. If the result is 0 no changes is done with the sort order of the two values.

Back

var fruits = ["Banana", "Orange", "Apple", "Mango"]; fruits.splice(2, 0, "Lemon", "Kiwi");

Front

The first parameter (2) defines the position where new elements should be added (spliced in). The second parameter (0) defines how many elements should be removed. The rest of the parameters ("Lemon" , "Kiwi") define the new elements to be added. The splice() method returns an array with the deleted items:

Back

In JavaScript, arrays always use numbered indexes.

Front

Back

Array.some(function)

Front

The some() method check if some array values pass a test.

Back

var fruits = ["Banana", "Orange", "Apple", "Mango"]; fruits.sort(); // First sort the elements of fruits fruits.reverse(); // Then reverse the order of the elements

Front

Back

Everything With a "Value" is True

Front

Everything Without a "Value" is False

Back

Numeric Sort By default, the sort() function sorts values as strings. This works well for strings ("Apple" comes before "Banana"). However, if numbers are sorted as strings, "25" is bigger than "100", because "2" is bigger than "1". Because of this, the sort() method will produce incorrect result when sorting numbers. You can fix this by providing a compare function:

Front

var points = [40, 100, 1, 5, 25, 10]; points.sort(function(a, b){return a - b});

Back

for loop

Front

for (i = 0; i < 5; i++) { text += "The number is " + i + "<br>"; } statement 1 is optional, can initialize multiple values or initialize it outside of the loop statement 2 is also optional, always returns true statement 3 can be optional and the couter value can be edited inside the loop

Back

Find the Highest (or Lowest) Array Value

Front

There are no built-in functions for finding the max or min value in an array. However, after you have sorted an array, you can use the index to obtain the highest and lowest values. Sorting a whole array is a very inefficient method if you only want to find the highest (or lowest) value. Math.max.apply(null, [1, 2, 3]) is equivalent to Math.max(1, 2, 3). Math.min.apply(null, [1, 2, 3]) is equivalent to Math.min(1, 2, 3). The fastest solution is to use a "home made" method. function myArrayMax(arr) { var len = arr.length var max = -Infinity; while (len--) { if (arr[len] > max) { max = arr[len]; } } return max; }

Back

Array.findIndex()

Front

The findIndex() method returns the index of the first array element that passes a test function.

Back

pop()

Front

The pop() method removes the last element from an array: The pop() method returns the value that was "popped out":

Back

Comparing Different Types

Front

When comparing a string with a number, JavaScript will convert the string to a number when doing the comparison. An empty string converts to 0. A non-numeric string converts to NaN which is always false. When comparing two strings, "2" will be greater than "12", because (alphabetically) 1 is less than 2.

Back

JavaScript Break and Continue

Front

The break statement "jumps out" of a loop. The continue statement "jumps over" one iteration in the loop.

Back

In JavaScript, arrays use numbered indexes. In JavaScript, objects use named indexes.

Front

Back

Merging (Concatenating) Arrays

Front

var myGirls = ["Cecilie", "Lone"]; var myBoys = ["Emil", "Tobias", "Linus"]; var myChildren = myGirls.concat(myBoys); // Concatenates (joins) myGirls and myBoys

Back

Array.forEach(function)

Front

var txt = ""; var numbers = [45, 4, 9, 16, 25]; numbers.forEach(myFunction); function myFunction(value, index, array) { txt = txt + value + "<br>"; } Note that the function can take 3 arguments: The item value The item index The array itself

Back

Array.map(function)

Front

The map() method creates a new array by performing a function on each array element. The map() method does not execute the function for array elements without values. The map() method does not change the original array.

Back

JS Math Object

Front

Math.PI Math.round() -> returns the value of x rounded to its nearest integer Math.pow(base, power) Math.sqrt() Math.abs() Math.ceil() Math.floor() Math.min() and Math.max() Math.random() returns a random number between 0 (inclusive), and 1 (exclusive):

Back

Sorting Object Arrays

Front

cars.sort(function(a, b){return a.year - b.year}); Comparing string properties is a little more complex: cars.sort(function(a, b){ var x = a.type.toLowerCase(); var y = b.type.toLowerCase(); if (x < y) {return -1;} if (x > y) {return 1;} return 0; });

Back

comparison operators

Front

if (age < 18) text = "Too young";

Back

Array.reduceRight()

Front

The reduceRight() works from right-to-left in the array. See also reduce().

Back

The unshift() method adds a new element to an array (at the beginning), and "unshifts" older elements:

Front

The unshift() method returns the new array length.

Back

fruits.join(" * ");

Front

The join() method also joins all array elements into a string. It behaves just like toString(), but in addition you can specify the separator:

Back

Array methods

Front

array.toString() -> Banana,Orange,Apple,Mango array.join(separator) -> without separator works like toString array.pop() -> pops out the last element array.push() -> adds a new element, and returns the array length array.shift() -> removes the first element array.unshift -> adds a new element to array, and returns the array length fruits[0] = "Kiwi"; -> change element delete fruits[0]; -> change the first element to undefined, empty array.splice(start, # removed, ...newelements to be added (optional)) -> returns an array with the deleted items slice(start, end(optional)) The slice() method creates a new array. It does not remove any elements from the source array. array1.concat(array2, arr3...(any number))-> does not change the existing arrays, it always returns a new array There are no built-in functions for finding the highest or lowest value in a JavaScript array.

Back

shift() method removes the first array element and "shifts" all other elements to a lower index.

Front

The shift() method returns the string that was "shifted out":

Back

Array.reduce(function)

Front

The reduce() method runs a function on each array element to produce (reduce it to) a single value. The reduce() method works from left-to-right in the array. See also reduceRight(). The reduce() method does not reduce the original array. var numbers1 = [45, 4, 9, 16, 25]; var sum = numbers1.reduce(myFunction); function myFunction(total, value, index, array) { return total + value; } gives the sum 99

Back

Math.max.apply(null, [1, 2, 3]) is equivalent to Math.max(1, 2, 3).

Front

You can use Math.min.apply to find the lowest number in an array:

Back

Array.reduceRight(function)

Front

The reduceRight() works from right-to-left in the array.

Back

Arrays

Front

Access the Elements of an Array var item = array[index] changing an element array[index] = item

Back

Array.find(function)

Front

The find() method returns the value of the first array element that passes a test function. This example finds (returns the value of) the first element that is larger than 18: var numbers = [4, 9, 16, 25, 29]; var first = numbers.find(myFunction); function myFunction(value, index, array) { return value > 18; } returns 25

Back

The Do/While Loop

Front

do { // code block to be executed } while (condition);

Back

switch statement

Front

switch(expression) { case x: // code block break; case y: // code block break; default: // code block } The default keyword specifies the code to run if there is no case match: The default case does not have to be the last case in a switch block: If it is not to the end, end it with a break. Note: If you omit the break statement, the next case will be executed even if the evaluation does not match the case.

Back

The For/In Loop

Front

The JavaScript for/in statement loops through the properties of an object: var person = {fname:"John", lname:"Doe", age:25};

Back

JS Array Iteration Methods

Front

function myFunction(value, index, array) { txt = txt + value + "<br>"; } Array.forEach(function) -> method calls a function (a callback function) once for each array element. newArray = Array.map(function) -> creates a new array -> return value * 2; Array.filter(function) -> return value > 18, creates a new array with array elements that passes a test Array.reduce() Array.reduceRight() result = Array.every(function) -> checks if all array values pass as test; result is true or false result = Array.some(function) -> checks if some array values pass a test; result returns true or false array.indexOf(element, start(optional, can be -)) -> return element's position; returns -1 if the item is not found array.lastIndexOf(item, start(optional, can be negative)) array.find(function) -> returns the value of the first array element that passes a test function Array.findIndex(function) -> returns the index of the first array element that passes a test function

Back

Array.every(function)

Front

var numbers = [45, 4, 9, 16, 25]; var allOver18 = numbers.every(myFunction); //return true or false, depend on if all numbers pass the test function myFunction(value, index, array) { return value > 18; }

Back

Sometimes you will want different switch cases to use the same code.

Front

switch (new Date().getDay()) { case 4: case 5: text = "Soon it is Weekend"; break; case 0: case 6: text = "It is Weekend"; break; default: text = "Looking forward to the Weekend"; } Switch cases use strict comparison (===).

Back

Array.isArray(fruits); // returns true

Front

Back

slice() method slices out a piece of an array into a new array.

Front

The slice() method can take two arguments like slice(1, 3). The method then selects elements from the start argument, and up to (but not including) the end argument. If the end argument is omitted, like in the first examples, the slice() method slices out the rest of the array.

Back

Converting Arrays to Strings

Front

The JavaScript method toString() converts an array to a string of (comma separated) array values. Banana,Orange,Apple,Mango

Back

JS Array Sort

Front

array.sort() array.reverse() reverse the order of the lements By default, the sort() function sorts values as strings. This works well for strings ("Apple" comes before "Banana"). However, if numbers are sorted as strings, "25" is bigger than "100", because "2" is bigger than "1". it's best to sort numbers using a compare function var points = [40, 100, 1, 5, 25, 10]; points.sort(function(a, b){return a - b}); If the result is negative a is sorted before b. If the result is positive b is sorted before a. If the result is 0 no changes is done with the sort order of the two values.

Back

Sorting Object Arrays

Front

Even if objects have properties of different data types, the sort() method can be used to sort the array. The solution is to write a compare function to compare the property values: cars.sort(function(a, b){return a.year - b.year}); comparing string properties is a little more complex: cars.sort(function(a, b){ var x = a.type.toLowerCase(); var y = b.type.toLowerCase(); if (x < y) {return -1;} if (x > y) {return 1;} return 0; });

Back

array.sort()

Front

Back

whileloop

Front

while (i < 10) { text += "The number is " + i; i++; }

Back

if statement

Front

if (condition1) { // block of code to be executed if condition1 is true } else if (condition2) { // block of code to be executed if the condition1 is false and condition2 is true } else { // block of code to be executed if the condition1 is false and condition2 is false }

Back

Array.filter(function)

Front

The filter() method creates a new array with array elements that passes a test.

Back

push() method adds a new element to an array (at the end):

Front

The push() method returns the new array length:

Back

Conditional (Ternary) Operator

Front

variablename = (condition) ? value1:value2 var voteable = (age < 18) ? "Too young":"Old enough";

Back

Finding Max and Min Values in an Array

Front

There are no built-in functions for finding the highest or lowest value in a JavaScript array.

Back

array.indexOf(item, start) array.lastIndexOf(item, start)

Front

Array.lastIndexOf() is the same as Array.indexOf(), but searches from the end of the array.

Back

Section 4

(35 cards)

Semicolons ;

Front

Semicolons separate JavaScript statements. Add a semicolon at the end of each executable statement: When separated by semicolons, multiple statements on one line are allowed: a = 5; b = 6; c = a + b; On the web, you might see examples without semicolons. Ending statements with semicolon is not required, but highly recommended.

Back

JavaScript Errors - Throw and Try to Catch try { Block of code to try } catch(err) { Block of code to handle errors }

Front

The try statement lets you test a block of code for errors. The catch statement lets you handle the error. The throw statement lets you create custom errors. The finally statement lets you execute code, after try and catch, regardless of the result. When an error occurs, JavaScript will normally stop and generate an error message. The technical term for this is: JavaScript will throw an exception (throw an error). JavaScript will actually create an Error object with two properties: name and message.

Back

JS Labels

Front

To label JavaScript statements you precede the statements with a label name and a colon: label: statements var cars = ["BMW", "Volvo", "Saab", "Ford"]; list: { text += cars[0] + "<br>"; text += cars[1] + "<br>"; break list; text += cars[2] + "<br>"; text += cars[3] + "<br>"; } The continue statement (with or without a label reference) can only be used to skip one loop iteration. The break statement, without a label reference, can only be used to jump out of a loop or a switch. With a label reference, the break statement can be used to jump out of any code block:

Back

this Keyword

Front

It has different values depending on where it is used: In a method, this refers to the owner object. Alone, this refers to the global object. In a function, this refers to the global object. In a function, in strict mode, this is undefined. In an event, this refers to the element that received the event. Methods like call(), and apply() can refer this to any object.

Back

JavaScript Function Scope

Front

In JavaScript there are two types of scope: Local scope Global scope JavaScript has function scope: Each function creates a new scope. Variables declared within a JavaScript function, become LOCAL to the function. Local variables have Function scope: They can only be accessed from within the function. Global variables can be accessed from anywhere in a JavaScript program.

Back

Arrow Functions

Front

Arrow functions allows a short syntax for writing function expressions. // ES5 var x = function(x, y) { return x * y; } // ES6 const x = (x, y) => x * y; Arrow functions do not have their own this. They are not well suited for defining object methods. Arrow functions are not hoisted. They must be defined before they are used. Using const is safer than using var, because a function expression is always constant value. You can only omit the return keyword and the curly brackets if the function is a single statement. Because of this, it might be a good habit to always keep them:

Back

JavaScript Let

Front

S2015 introduced two important new JavaScript keywords: let and const. let is not hoisted These two keywords provide Block Scope variables (and constants) in JavaScript.

Back

const

Front

JavaScript const variables must be assigned a value when they are declared: Incorrect const PI; PI = 3.14159265359; Correct const PI = 3.14159265359; It does NOT define a constant value. It defines a constant reference to a value. Because of this, we cannot change constant primitive values, but we can change the properties of constant objects.

Back

The global method Number() can convert strings to numbers.

Front

Number("3.14") // returns 3.14 Number(" ") // returns 0 Number("") // returns 0 Number("99 88") // returns NaN

Back

Errors

Front

EvalError An error has occurred in the eval() function RangeError A number "out of range" has occurred ReferenceError An illegal reference has occurred SyntaxError A syntax error has occurred TypeError A type error has occurred URIError An error in encodeURI() has occurred

Back

Constant Arrays can Change

Front

// You can create a constant array: const cars = ["Saab", "Volvo", "BMW"]; // You can change an element: cars[0] = "Toyota"; // You can add an element: cars.push("Audi"); But you can NOT reassign a constant array: const cars = ["Saab", "Volvo", "BMW"]; cars = ["Toyota", "Volvo", "Audi"]; // ERROR

Back

all functions have access to the scope "above" them.

Front

Back

JavaScript Performance

Front

Reduce Activity in Loops Bad: var i; for (i = 0; i < arr.length; i++) { Better Code: var i; var l = arr.length; for (i = 0; i < l; i++) { Reduce DOM Access - Keep the number of elements in the HTML DOM small. Reduce DOM Size Avoid Unnecessary Variables

Back

type conversion

Front

https://www.w3schools.com/js/js_type_conversion.asp

Back

The unary + operator can be used to convert a variable to a number:

Front

var y = "5"; // y is a string var x = + y; // x is a number var y = "John"; // y is a string var x = + y; // x is a number (NaN)

Back

strict mode "use strict"

Front

JavaScript in strict mode does not allow variables to be used if they are not declared.

Back

JavaScript Type Conversion

Front

Number() converts to a Number, parseFloat() Parses a string and returns a floating point number parseInt() Parses a string and returns an integer String() converts to a String, The Number method toString() does the same. Boolean() converts to a Boolean.

Back

Variables created without the keyword var, are always global, even if they are created inside a function.

Front

Back

Function Scope

Front

// code here can NOT use carName function myFunction() { var carName = "Volvo"; // code here CAN use carName } // code here can NOT use carName Local variables can only be accessed from inside the function where they are declared.

Back

a closure

Front

A closure is a function having access to the parent scope, even after the parent function has closed.

Back

var arr1 = "john".split(''); var arr2 = arr1.reverse(); var arr3 = "jones".split('');

Front

arr1 and arr2 are the same (i.e. ['n','h','o','j', ['j','o','n','e','s'] ]) after the above code is executed for the following reasons: Calling an array object's reverse() method doesn't only return the array in reverse order, it also reverses the order of the array itself (i.e., in this case, arr1). The reverse() method returns a reference to the array itself (i.e., in this case, arr1). As a result, arr2 is simply a reference to (rather than a copy of) arr1. Therefore, when anything is done to arr2 (i.e., when we invoke arr2.push(arr3);), arr1 will be affected as well since arr1 and arr2 are simply references to the same object.

Back

JavaScript White Space

Front

JS ignores multiple spaces

Back

JavaScript function can be in both <body> and <head> tags

Front

When in body tag, it is best to place the function near the bottom of the tag because function interpretation would slowdown the display speed.

Back

Explicit Function Binding

Front

Explicit Function Binding The call() and apply() methods are predefined JavaScript methods. They can both be used to call an object method with another object as argument. In the example below, when calling person1.fullName with person2 as argument, this will refer to person2, even if it is a method of person1: person1.fullName.call(person2); // Will return person2's name

Back

Constant Objects can Change

Front

// You can create a const object: const car = {type:"Fiat", model:"500", color:"white"}; // You can change a property: car.color = "red"; // You can add a property: car.owner = "Johnson"; But you can NOT reassign a constant object: const car = {type:"Fiat", model:"500", color:"white"}; car = {type:"Volvo", model:"EX60", color:"red"}; // ERROR

Back

JavaScript Declarations are Hoisted

Front

hoisting is JavaScript's default behavior of moving all declarations to the top of the current scope (to the top of the current script or the current function). Variables and constants declared with let or const are not hoisted! Read more about let and const in JS Let / Const. JavaScript Initializations are Not Hoisted

Back

JavaScript Programs

Front

A computer program is a list of "instructions" to be "executed" by a computer. In a programming language, these programming instructions are called statements. A JavaScript program is a list of programming statements.

Back

External script

Front

external script is practical when the same code is used in many different web pages.

Back

closure example 2

Front

var nodes = document.getElementsByTagName('button'); for (var i = 0; i < nodes.length; i++) { nodes[i].addEventListener('click', (function(i) { return function() { console.log('You clicked element #' + i); } })(i)); }

Back

Automatically Global

Front

If you assign a value to a variable that has not been declared, it will automatically become a GLOBAL variable. except in Strict Mode

Back

JavaScript Best Practices

Front

Avoid Global Variables Always Declare Local Variables Declarations on Top

Back

closure example

Front

var add = (function () { var counter = 0; return function () {counter += 1; return counter} })(); add(); add(); add(); // the counter is now 3

Back

data types

Front

In JavaScript there are 5 different data types that can contain values: string number boolean object function There are 6 types of objects: Object Date Array String Number Boolean And 2 data types that cannot contain values: null undefined The data type of NaN is number The data type of an array is object The data type of a date is object The data type of null is object The data type of an undefined variable is undefined * The data type of a variable that has not been assigned a value is also undefined *

Back

Variables declared Globally (outside any function) have Global Scope.

Front

var carName = "Volvo"; // code here can use carName function myFunction() { // code here can also use carName }

Back

JavaScript Block Scope

Front

Variables declared with the var keyword can not have Block Scope. Variables declared inside a block {} can be accessed from outside the block. Before ES2015 JavaScript did not have Block Scope. Variables declared with the let keyword can have Block Scope.

Back