Javascript

¡Supera tus tareas y exámenes ahora con Quizwiz!

Array.every()

Array.every() The every() method check if all array values pass a test. This example check if all array values are larger than 18: Example var numbers = [45, 4, 9, 16, 25]; var allOver18 = numbers.every(myFunction); function myFunction(value, index, array) { return value > 18; }

Array.filter()

Array.filter() The filter() method creates a new array with array elements that passes a test. This example creates a new array from elements with a value larger than 18: Example var numbers = [45, 4, 9, 16, 25]; var over18 = numbers.filter(myFunction); function myFunction(value, index, array) { return value > 18; }// 45,25

Array.find()

Array.find() 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; }

Array.findIndex()

Array.findIndex() The findIndex() method returns the index of the first array element that passes a test function. This example finds the index of the first element that is larger than 18:

Array.forEach()

Array.forEach() The forEach() method calls a function (a callback function) once for each array element. Example var txt = ""; var numbers = [45, 4, 9, 16, 25]; numbers.forEach(myFunction); function myFunction(value, index, array) { txt = txt + value + "<br>"; }// 45 4 9 16 25

Searching for a String in a String

The search() method searches a string for a specified value and returns the position of the match: The search() method cannot take a second start position argument. The indexOf() method cannot take powerful search values (regular expressions).

The slice() method can take two arguments like

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. Example var fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"]; var citrus = fruits.slice(1, 3); //Orange,Lemon

Difference Between Undefined and Null

Undefined and null are equal in value but different in type: typeof undefined // undefined typeof null // object null === undefined // false null == undefined // true

Access the Elements of an Array

You access an array element by referring to the index number. This statement accesses the value of the first element in cars: var name = cars[0];

var person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"}; person = undefined; // Now both value and type is undefined

You can also empty an object by setting it to undefined:

Array Elements Can Be Objects

You can have objects in an Array. You can have functions in an Array. You can have arrays in an Array:

isNaN()

You can use the global JavaScript function isNaN() to find out if a value is a number:

Complex Data

function object typeof {name:'John', age:34} // Returns "object" typeof [1,2,3,4] // Returns "object" (not "array", see note below) typeof null // Returns "object" typeof function myFunc(){} // Returns "function"

Example Conditional Statements

function myFunction() { var greeting; var time = new Date().getHours(); if (time < 10) { greeting = "Good morning"; } else if (time < 20) { greeting = "Good day"; } else { greeting = "Good evening"; } document.getElementById("demo").innerHTML = greeting;

Accessing Object Methods You access an object method with the following syntax:

objectName.methodName()

Accessing Object Properties You can access object properties in two ways:

objectName.propertyName or objectName["propertyName"]

The parseFloat() Method

parseFloat() parses a string and returns a number. Spaces are allowed. Only the first number is returned: Example 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

The parseInt() Method

parseInt() parses a string and returns a whole number. Spaces are allowed. Only the first number is returned: Example 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

Primitive Data

string, number, boolean, undefined typeof "John" // Returns "string" typeof 3.14 // Returns "number" typeof true // Returns "boolean" typeof false // Returns "boolean" typeof x // Returns "undefined" (if x has no value)

Changing base no By default, JavaScript displays numbers as base 10 decimals.

var myNumber = 32; myNumber.toString(10); // returns 32 myNumber.toString(32); // returns 10 myNumber.toString(16); // returns 20 myNumber.toString(8); // returns 40 myNumber.toString(2); // returns 100000

Conditional (Ternary) Operator JavaScript also contains a conditional operator that assigns a value to a variable based on some condition.

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

COMPARE var x = NaN; var y = "5"; var z = x + y; // z will be NaN5

var x = NaN; var y = 5; var z = x + y; // z will be NaN

Comparing two JavaScript objects will always return false.

var x = new String("John"); var y = new String("John"); // (x === y) is false because x and y are different objects Note the difference between (x==y) and (x===y). Comparing two JavaScript objects will always return false.

exponentiation operator

x ** y produces the same result as Math.pow(x,y):

Null

In JavaScript null is "nothing". It is supposed to be something that doesn't exist. Unfortunately, in JavaScript, the data type of null is an object. You can empty an object by setting it to null: var person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"}; person = null; // Now value is null, but type is still an object

JavaScript Booleans

JavaScript Booleans A JavaScript Boolean represents one of two values: true or false. Boolean Values Very often, in programming, you will need a data type that can only have one of two values, like YES / NO ON / OFF TRUE / FALSE For this, JavaScript has a Boolean data type. It can only take the values true or false.

When to Use Arrays. When to use Objects.

JavaScript does not support associative arrays. You should use objects when you want the element names to be strings (text). You should use arrays when you want the element names to be numbers.

NUMBERS

JavaScript has only one type of number. Numbers can be written with or without decimals. JavaScript Numbers are Always 64-bit Floating Point JavaScript numbers are always stored as double precision floating point numbers, following the international IEEE 754 standard. Integers (numbers without a period or exponent notation) are accurate up to 15 digits. The maximum number of decimals is 17, but floating point arithmetic is not always 100% accurate:

Hexadecimal

JavaScript interprets numeric constants as hexadecimal if they are preceded by 0x. Never write a number with a leading zero (like 07). Some JavaScript versions interpret numbers as octal if they are written with a leading zero. By default, JavaScript displays numbers as base 10 decimals.

JavaScript Keywords

JavaScript keywords are used to identify actions to be performed. The var keyword tells the browser to create variables:

Object Definition

JavaScript objects are containers for named values called properties or methods. You define (and create) a JavaScript object with an object literal:

JavaScript Strings

JavaScript strings are used for storing and manipulating text. A JavaScript string is zero or more characters written inside quotes.

JavaScript

JavaScript to program the behavior of web pages

What is variables in js?

JavaScript variables are containers for storing data values.

Numeric Strings

JavaScript will try to convert strings to numbers in all numeric operations 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

Logical Operators

Logical Operators Logical operators are used to determine the logic between variables or values. &&, ||, !

Math Constructor Unlike other global objects, the Math object has no constructor. Methods and properties are static. All methods and properties (constants) can be used without creating a Math object first.

Math Object Methods Method Description abs(x) Returns the absolute value of x acos(x) Returns the arccosine of x, in radians asin(x) Returns the arcsine of x, in radians atan(x) Returns the arctangent of x as a numeric value between -PI/2 and PI/2 radians atan2(y, x) Returns the arctangent of the quotient of its arguments ceil(x) Returns the value of x rounded up to its nearest integer cos(x) Returns the cosine of x (x is in radians) exp(x) Returns the value of Ex floor(x) Returns the value of x rounded down to its nearest integer log(x) Returns the natural logarithm (base E) of x max(x, y, z, ..., n) Returns the number with the highest value min(x, y, z, ..., n) Returns the number with the lowest value pow(x, y) Returns the value of x to the power of y random() Returns a random number between 0 and 1 round(x) Returns the value of x rounded to its nearest integer sin(x) Returns the sine of x (x is in radians) sqrt(x) Returns the square root of x tan(x) Returns the tangent of an angle

Math Properties (Constants)

Math Properties (Constants) JavaScript provides 8 mathematical constants that can be accessed with the Math object: Example Math.E // returns Euler's number Math.PI // returns PI Math.SQRT2 // returns the square root of 2 Math.SQRT1_2 // returns the square root of 1/2 Math.LN2 // returns the natural logarithm of 2 Math.LN10 // returns the natural logarithm of 10 Math.LOG2E // returns base 2 logarithm of E Math.LOG10E // returns base 10 logarithm of E

Math.abs()

Math.abs() Math.abs(x) returns the absolute (positive) value of x: Example Math.abs(-4.7); // returns 4.7

Math.ceil()

Math.ceil() Math.ceil(x) returns the value of x rounded up to its nearest integer: Example Math.ceil(4.4); // returns 5

Math.floor()

Math.floor() Math.floor(x) returns the value of x rounded down to its nearest integer: Example Math.floor(4.7); // returns 4

Math.min() and Math.max()

Math.min() and Math.max() Math.min() and Math.max() can be used to find the lowest or highest value in a list of arguments: Example Math.min(0, 150, 30, 20, -8, -200); // returns -200

Math.pow()

Math.pow(x, y) returns the value of x to the power of y: Example Math.pow(8, 2); // returns 64

Math.random()

Math.random() Math.random() returns a random number between 0 (inclusive), and 1 (exclusive): Example Math.random(); // returns a random number

Math.round()

Math.round() Math.round(x) returns the value of x rounded to its nearest integer: Example Math.round(4.7); // returns 5 Math.round(4.4); // returns 4

Math.sin()& Math.cos()

Math.sin() Math.sin(x) returns the sine (a value between -1 and 1) of the angle x (given in radians). Math.cos() Math.cos(x) returns the cosine (a value between -1 and 1) of the angle x (given in radians).

Math.sqrt()

Math.sqrt() Math.sqrt(x) returns the square root of x: Example Math.sqrt(64); // returns 8

Merging (Concatenating) Arrays

Merging (Concatenating) Arrays The concat() method creates a new array by merging (concatenating) existing arrays: The concat() method does not change the existing arrays. It always returns a new array. The concat() method can take any number of array arguments: var myChildren = arr1.concat(arr2, arr3); // Concatenates arr1 with arr2 and arr3

JavaScript Get Date Methods

Method Description getFullYear() Get the year as a four digit number (yyyy) getMonth() Get the month as a number (0-11) getDate() Get the day as a number (1-31) getHours() Get the hour (0-23) getMinutes() Get the minute (0-59) getSeconds() Get the second (0-59) getMilliseconds() Get the millisecond (0-999) getTime() Get the time (milliseconds since January 1, 1970) getDay() Get the weekday as a number (0-6) Date.now() Get the time. ECMAScript 5. getUTCDate() Same as getDate(), but returns the UTC date

Set Date Methods

Method Description setDate() Set the day as a number (1-31) setFullYear() Set the year (optionally month and day) setHours() Set the hour (0-23) setMilliseconds() Set the milliseconds (0-999) setMinutes() Set the minutes (0-59) setMonth() Set the month (0-11) setSeconds() Set the seconds (0-59) setTime() Set the time (milliseconds since January 1, 1970)

Object Methods Objects can also have methods.

Methods are actions that can be performed on objects. Methods are stored in properties as function definitions. A method is a function stored as a property.

NaN - Not a Number

NaN is a JavaScript reserved word indicating that a number is not a legal number. Trying to do arithmetic with a non-numeric string will result in NaN (Not a Number): Example var x = 100 / "Apple"; // x will be NaN (Not a Number) However, if the string contains a numeric value , the result will be a number var x = 100 / "10"; // x will be 10

Numbers Can be Objects

Normally JavaScript numbers are primitive values created from literals: var x = 123; But numbers can also be defined as objects with the keyword new: var y = new Number(123); var x = 500; var y = new Number(500); // (x === y) is false because x and y have different types though equal value Note the difference between (x==y) and (x===y). Comparing two JavaScript objects will always return false. because objects cannot be compared.

JavaScript Stores Dates as Milliseconds

Now the time is: 1546468274870 milliseconds past January 01, 1970 The toDateString() method converts a date to a more readable format:

Number Properties Cannot be Used on Variables

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. Example var x = 6; var y = x.MAX_VALUE; // y becomes undefined

JavaScript Number Methods

Number methods help you work with numbers. Primitive values (like 3.14 or 2014), cannot have properties and 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.

The Number() Method

Number() can be used to convert JavaScript variables to numbers: Number("10.33"); // returns 10.33 Number("10,33"); // returns NaN Number("10 33"); // returns NaN Number("John"); // returns NaN Number() can also convert a date to a number: Number(new Date("2017-09-30")); // returns 1506729600000 The Number() method above returns the number of milliseconds since 1.1.1970.

Numeric Sort

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:

External JavaScript Advantages

Placing scripts in external files has some advantages: It separates HTML and code It makes HTML and JavaScript easier to read and maintain Cached JavaScript files can speed up page loads

The pop()

Popping The pop() method removes the last element from an array: The pop() method returns the value that was "popped out": Example var fruits = ["Banana", "Orange", "Apple", "Mango"]; var x = fruits.pop(); // the value of x is "Mango"

String Methods and Properties

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. String methods help you to work with strings.

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

Pushing The push() method

Pushing The push() method adds a new element to an array (at the end): The push() method returns the new array length: Example var fruits = ["Banana", "Orange", "Apple", "Mango"]; var x = fruits.push("Kiwi"); // the value of x is 5

The Continue Statement

The Continue Statement The continue statement breaks one iteration (in the loop), if a specified condition occurs, and continues with the next iteration in the loop. This example skips the value of 3: Example for (i = 0; i < 10; i++) { if (i === 3) { continue; } text += "The number is " + i + "<br>"; } A loop which will skip the step where i = 3.

The Do/While Loop

The Do/While Loop The do/while loop is a variant of the while loop. This loop will execute the code block once, before checking if the condition is true, then it will repeat the loop as long as the condition is true. while (condition); Example The example below uses a do/while loop. The loop will always be executed at least once, even if the condition is false, because the code block is executed before the condition is tested: Example do { text += "The number is " + i; i++; } while (i < 10); Do not forget to increase the variable used in the condition, otherwise the loop will never end!

The For/In Loop

The For/In Loop The JavaScript for/in statement loops through the properties of an object: Example var person = {fname:"John", lname:"Doe", age:25}; var text = ""; var x; for (x in person) { text += person[x];

The concat() Method

The concat() method can be used instead of the plus operator. These two lines do the same: var text = "Hello" + " " + "World!"; var text = "Hello".concat(" ", "World!"); //Hello World!

The default case does

The default case does not have to be the last case in a switch block: Example switch (new Date().getDay()) { default: text = "Looking forward to the Weekend"; break; case 6: text = "Today is Saturday"; break; case 0: text = "Today is Sunday"; } If default is not the last case in the switch block, remember to end the default case with a break.

The join()

The join() method also joins all array elements into a string. It behaves just like toString(), but in addition you can specify the separator: Example var fruits = ["Banana", "Orange", "Apple", "Mango"]; document.getElementById("demo").innerHTML = fruits.join(" * "); Result Banana * Orange * Apple * Mango

Array Properties and Methods

The real strength of JavaScript arrays are the built-in array properties and methods. var x = cars.length; // The length property returns the number of elements var y = cars.sort(); // The sort() method sorts arrays

Array.reduce()

The reduce() method can accept an initial value: var numbers1 = [45, 4, 9, 16, 25]; 100 will be added with them

Replacing String Content

The replace() method replaces a specified value with another value in a string: Example str = "Please visit Microsoft!"; var n = str.replace("Microsoft", "W3Schools"); //Please visit W3Schools! By default, the replace() function replaces only the first match: To replace case insensitive, use a regular expression with an /i flag (insensitive): EG. var n = str.replace(/MICROSOFT/i, "W3Schools"); To replace all matches, use a regular expression with a /g flag (global match): EG. var n = str.replace(/Microsoft/g, "W3Schools");

Reversing an Array

The reverse() method reverses the elements in an array. You can use it to sort an array in descending order:

Looping Array Elements

The safest way to loop through an array, is using a "for" loop: You can also use the Array.forEach() function:

String.trim()

String.trim() removes whitespace from both sides of a string.

Switching Details

Switching Details If multiple cases matches a case value, the first case is selected. If no matching cases are found, the program continues to the default label. If no default label is found, the program continues to the statement(s) after the switch.

The Boolean() Function

The Boolean() Function You can use the Boolean() function to find out if an expression (or a variable) is true: Example Boolean(10 > 9) // returns true Or even easier: Example (10 > 9) // also returns true 10 > 9 // also returns true The Boolean value of an expression is the basis for all JavaScript comparisons and conditions.

The Break Statement

The Break Statement You have already seen the break statement used in an earlier chapter of this tutorial. It was used to "jump out" of a switch() statement. The break statement can also be used to jump out of a loop. The break statement breaks the loop and continues executing the code after the loop (if any): Example for (i = 0; i < 10; i++) { if (i === 3) { break; } text += "The number is " + i + "<br>"; } // The number is 0 The number is 1 The number is

The Compare Function

The Compare Function 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. var points = [40, 100, 1, 5, 25, 10]; points.sort(function(a, b){return a - b}); Use the same trick to sort an array descending: Example var points = [40, 100, 1, 5, 25, 10]; points.sort(function(a, b){return b - a});

Changing an Array Element

This statement changes the value of the first element in cars: var cars = ["Saab", "Volvo", "BMW"]; cars[0] = "Opel";

not equal

!== not equal value or not equal type ? ternary operator

JavaScript Expressions

An expression is a combination of values, variables, and operators, which computes to a value. The computation is called an evaluation. For example, 5 * 10 evaluates to 50:

break up a string

A safer way to break up a string, is to use string addition: Example document.getElementById("demo").innerHTML = "Hello " + "Dolly!";

JavaScript Can Change HTML Attribute Values

<button onclick="document.getElementById('myImage').src='pic_bulbon.gif'">Turn on the light</button> In this example JavaScript changes the value of the src (source) attribute of an <img> tag:

JavaScript Functions and Events

A JavaScript function is a block of JavaScript code, that can be executed when "called" for. For example, a function can be called when an event occurs, like when the user clicks a button.

A Proper Random Function

A Proper Random Function As you can see from the examples above, it might be a good idea to create a proper random function to use for all random integer purposes. This JavaScript function always returns a random number between min (included) and max (excluded): Example function getRndInteger(min, max) { return Math.floor(Math.random() * (max - min) ) + min;

what is statement?

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.

Converting a String to an Array

A string can be converted to an array with the split() method: Example 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:

Value = undefined var car;

A variable declared without a value will have the value undefined.

Adding Array Elements

Adding Array Elements The easiest way to add a new element to an array is using the push method: fruits.push("Lemon"); // adds a new element (Lemon) to fruits New element can also be added to an array using the length property: fruits[fruits.length] = "Lemon"; // adds a new element (Lemon) to fruits

JavaScript Identifiers Identifiers are names.

All JavaScript variables must be identified with unique names. These unique names are called identifiers. In JavaScript, identifiers are used to name variables (and keywords, and functions, and labels). The rules for legal names are much the same in most programming languages.

PRINCIPLE

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.

Array.indexOf()

Array.indexOf() Search an array for an element value and returns its position. Note: The first item has position 0, the second item has position 1, and so on. array.indexOf(item, start) item Required. The item to search for. start Optional. Where to start the search. Negative values will start at the given position counting from the end, and search to the end. Array.indexOf() returns -1 if the item is not found. If the item is present more than once, it returns the position of the first occurrence.

Array.lastIndexOf()

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

Array.map()

Array.map() 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. This example multiplies each array value by 2: var numbers1 = [45, 4, 9, 16, 25]; var numbers2 = numbers1.map(myFunction); function myFunction(value, index, array) { return value * 2; }// 90,8,18,32,50

Array.reduce()

Array.reduce() 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. This example finds the sum of all numbers in an array var numbers1 = [45, 4, 9, 16, 25]; var sum = numbers1.reduce(myFunction);

Array.reduceRight()

Array.reduceRight() The reduceRight() method runs a function on each array element to produce (reduce it to) a single value. The reduceRight() works from right-to-left in the array. See also reduce(). The reduceRight() method does not reduce the original array. This example finds the sum of all numbers in an array:

Array.some()

Array.some() The some() method check if some array values pass a test. This example check if some array values are larger than 18:

Arrays are Objects

Arrays are a special type of objects. The typeof operator in JavaScript returns "object" for arrays. But, JavaScript arrays are best described as arrays. Arrays use numbers to access its "elements". In this example, person[0] returns John: Array: var person = ["John", "Doe", 46]; Objects use names to access its "members". In this example, person.firstName returns John:

Associative Arrays

Associative Arrays Many programming languages support arrays with named indexes. Arrays with named indexes are called associative arrays (or hashes). JavaScript does not support arrays with named indexes. In JavaScript, arrays always use numbered indexes. WARNING !! If you use named indexes, JavaScript will redefine the array to a standard object. After that, some array methods and properties will produce incorrect results. Example: var person = []; person["firstName"] = "John";

Automatic toString()

Automatic toString() JavaScript automatically converts an array to a comma separated string when a primitive value is expected. This is always the case when you try to output an array. These two examples will produce the same result: Example var fruits = ["Banana", "Orange", "Apple", "Mango"]; document.getElementById("demo").innerHTML = fruits.toString(); Example var fruits = ["Banana", "Orange", "Apple", "Mango"]; document.getElementById("demo").innerHTML = fruits;

Booleans Can be Objects

Booleans Can be Objects Normally JavaScript booleans are primitive values created from literals: var x = false; But booleans can also be defined as objects with the keyword new: var y = new Boolean(false); Example var x = false; var y = new Boolean(false); // typeof x returns boolean // typeof y returns object

Strings Can be Objects

But strings can also be defined as objects with the keyword new: var firstName = new String("John"); EG. var x = "John"; var y = new String("John"); // (x == y) is true because x and y have equal values // (x === y) is false because x and y have different types (string and object)

Changing Elements

Changing Elements Array elements are accessed using their index number: var fruits = ["Banana", "Orange", "Apple", "Mango"]; fruits[0] = "Kiwi"; // Changes the first element of fruits to "Kiwi"

Comparing Different Types

Comparing Different Types Comparing data of different types may give unexpected results. 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.

Conditional Statements

Conditional Statements Very often when you write code, you want to perform different actions for different decisions. You can use conditional statements in your code to do this. In JavaScript we have the following conditional statements: Use if to specify a block of code to be executed, if a specified condition is true Use else to specify a block of code to be executed, if the same condition is false Use else if to specify a new condition to test, if the first condition is false Use switch to specify many alternative blocks of code to be executed

Converting Arrays to Strings toString()

Converting Arrays to Strings The JavaScript method toString() converts an array to a string of (comma separated) array values. var fruits = ["Banana", "Orange", "Apple", "Mango"]; document.getElementById("demo").innerHTML = fruits.toString(); Result Banana,Orange,Apple,Mango NOTE JavaScript automatically converts an array to a comma separated string when a primitive value is expected. This is always the case when you try to output an array.

Converting Variables to Numbers

Converting Variables to Numbers There are 3 JavaScript methods that can be used to convert variables to numbers: The Number() method The parseInt() method The parseFloat() method These methods are not number methods, but global JavaScript methods.

Creating Date Objects

Creating Date Objects Date objects are created with the new Date() constructor. There are 4 ways to create a new date object: new Date() creates a new date object with the current date and time: new Date(year, month, ...) creates a new date object with a specified date and time. var d = new Date(2018, 11, 24, 10, 33, 30, 0); JavaScript counts months from 0 to 11. January is 0. December is 11.

Deleting Elements

Deleting Elements Since JavaScript arrays are objects, elements can be deleted by using the JavaScript operator delete: Example var fruits = ["Banana", "Orange", "Apple", "Mango"]; delete fruits[0]; // Changes the first element in fruits to undefined Using delete may leave undefined holes in the array. Use pop() or shift() instead.

Different Kinds of Loops

Different Kinds of Loops JavaScript supports different kinds of loops: for - loops through a block of code a number of times for/in - loops through the properties of an object while - loops through a block of code while a specified condition is true do/while - also loops through a block of code while a specified condition is true If you omit statement 2, you must provide a break inside the loop. Otherwise the loop will never end. This will crash your browser. Read about breaks in a later chapter of this tutorial.

Everything Without a "Value" is False

Everything Without a "Value" is False The Boolean value of 0 (zero) is false: var x = 0; Boolean(x); // returns false The Boolean value of -0 (minus zero) is false: var x = -0; Boolean(x); // returns false The Boolean value of "" (empty string) is false: var x = ""; Boolean(x); // returns false The Boolean value of undefined is false: var x; Boolean(x); // returns false The Boolean value of null is false: var x = null; Boolean(x); // returns false The Boolean value of false is (you guessed it) false: var x = false; Boolean(x); // returns false The Boolean value of NaN is false: var x = 10 / "H"; Boolean(x); // returns false

example JavaScript While Loop

Example In the following example, the code in the loop will run, over and over again, as long as a variable (i) is less than 10: Example while (i < 10) { text += "The number is " + i; i++; } If you forget to increase the variable used in the condition, the loop will never end. This will crash your browser.

Accessing the Last Array Element

Example fruits = ["Banana", "Orange", "Apple", "Mango"]; var last = fruits[fruits.length - 1];

My Min / Max JavaScript Methods The fastest solution is to use a "home made" method. This function loops through an array comparing each value with the highest value found:

Example (Find Max) function myArrayMax(arr) { var len = arr.length var max = -Infinity; while (len--) { if (arr[len] > max) { max = arr[len]; } } return max; } Example (Find Min) function myArrayMin(arr) { var len = arr.length var min = Infinity; while (len--) { if (arr[len] < min) { min = arr[len]; } } return min; }

Find the Highest (or Lowest) Array Value

Find the Highest (or Lowest) Array Value 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 ascending: Example var points = [40, 100, 1, 5, 25, 10]; points.sort(function(a, b){return a - b}); // now points[0] contains the lowest value // and points[points.length-1] contains the highest value

Finding a String in a String

Finding a String in a String The indexOf() method returns the index of (the position of) the first occurrence of a specified text in a string: Example var str = "Please locate where 'locate' occurs!"; var pos = str.indexOf("locate"); //7

Function Invocation

Function Invocation The code inside the function will execute when "something" invokes (calls) the function: When an event occurs (when a user clicks a button) When it is invoked (called) from JavaScript code Automatically (self invoked)

Function parameters

Function parameters are listed inside the parentheses () in the function definition. Function arguments are the values received by the function when it is invoked. Inside the function, the arguments (the parameters) behave as local variables.

String Length

String Length The length property returns the length of a string:

The Difference Between Arrays and Objects

In JavaScript, arrays use numbered indexes. In JavaScript, objects use named indexes. Arrays are a special kind of objects, with numbered indexes.

Infinity

Infinity (or -Infinity) is the value JavaScript will return if you calculate a number outside the largest possible number. Division by 0 (zero) also generates Infinity: typeof Infinity; // returns "number"

JavaScript Array Iteration Methods

JavaScript Array Iteration Methods

JavaScript Comparison and Logical Operators

JavaScript Comparison and Logical Operators Comparison and Logical operators are used to test for true or false. Comparison Operators Comparison operators are used in logical statements to determine equality or difference between variables or values. Given that x = 5, the table below explains the comparison operators: Comparison operators can be used in conditional statements to compare values and take action depending on the result: if (age < 18) text = "Too young";

JavaScript Date Output

JavaScript Date Output By default, JavaScript will use the browser's time zone and display a date as a full text string: Wed Jan 02 2019 14:31:14 GMT-0800 (Pacific Standard Time)

JavaScript Events

JavaScript Events HTML events are "things" that happen to HTML elements. When JavaScript is used in HTML pages, JavaScript can "react" on these events. HTML allows event handler attributes, with JavaScript code, to be added to HTML elements.

JavaScript For Loop

JavaScript For Loop Loops can execute a block of code a number of times. JavaScript Loops Loops are handy, if you want to run the same code over and over again, each time with a different value. Often this is the case when working with arrays:

JavaScript Random

JavaScript Random Math.random() Math.random() returns a random number between 0 (inclusive), and 1 (exclusive): Example Math.random(); // returns a random number Math.random() always returns a number lower than 1. JavaScript Random Integers Math.random() used with Math.floor() can be used to return random integers. Example Math.floor(Math.random() * 10); // returns a random integer from 0 to 9 Example Math.floor(Math.random() * 11); // returns a random integer from 0 to 10 Example Math.floor(Math.random() * 100); // returns a random integer from 0 to 99 Example Math.floor(Math.random() * 101); // returns a random integer from 0 to 100 Example Math.floor(Math.random() * 10) + 1; // returns a random integer from 1 to 10 Example Math.floor(Math.random() * 100) + 1; // returns a random integer from 1 to 100

JavaScript Switch Statement

JavaScript Switch Statement The switch statement is used to perform different actions based on different conditions. The break Keyword When JavaScript reaches a break keyword, it breaks out of the switch block. This will stop the execution of more code and case testing inside the block. When a match is found, and the job is done, it's time for a break. There is no need for more testing. A break can save a lot of execution time because it "ignores" the execution of all the rest of the code in the switch block. It is not necessary to break the last case in a switch block. The block breaks (ends) there anyway. The default Keyword 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 default is not the last case in the switch block, remember to end the default case with a break.

JavaScript While Loop

JavaScript While Loop Loops can execute a block of code as long as a specified condition is true. The While Loop The while loop loops through a block of code as long as a specified condition is true.

JavaScript Arrays

JavaScript arrays are used to store multiple values in a single variable. An array is a special variable, which can hold more than one value at a time.

JavaScript Display Possibilities

JavaScript can "display" data in different ways: Writing into an HTML element, using innerHTML. Writing into the HTML output using document.write(). Writing into an alert box, using window.alert(). Writing into the browser console, using console.log().

JavaScript

Scripts can be placed in the <body>, or in the <head> section of an HTML page, or in both. Scripts can also be placed in external files:

Shifting Elements

Shifting is equivalent to popping, working on the first element instead of the last. The shift() method removes the first array element and "shifts" all other elements to a lower index. The shift() method returns the string that was "shifted out": Example var fruits = ["Banana", "Orange", "Apple", "Mango"]; var x = fruits.shift(); // the value of x is "Banana"

Slicing an Array The slice() method

Slicing an Array The slice() method slices out a piece of an array into a new array. This example slices out a part of an array starting from array element 1 ("Orange"): var fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"]; var citrus = fruits.slice(1); The slice() method creates a new array. It does not remove any elements from the source array.

Sorting an Array

Sorting an Array The sort() method sorts an array alphabetically:

Sorting an Array in Random Order

Sorting an Array in Random Order Example var points = [40, 100, 1, 5, 25, 10]; points.sort(function(a, b){return 0.5 - Math.random()}); //5,10,40,25,100,1

Splicing an Array The splice()

Splicing an Array The splice() method can be used to add new items to an array: Example var fruits = ["Banana", "Orange", "Apple", "Mango"]; fruits.splice(2, 0, "Lemon", "Kiwi"); 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: var fruits = ["Banana", "Orange", "Apple", "Mango"]; x= fruits.splice(2, 2, "Lemon", "Kiwi"); //Apple,Mango

JavaScript Math Object

The JavaScript Math object allows you to perform mathematical tasks on numbers. Math.PI; // returns 3.141592653589793

JavaScript Values

The JavaScript syntax defines two types of values: Fixed values and variable values. Fixed values are called literals. Variable values are called variables. Literals: 1,Numbers are written with or without decimals: 2, Strings are text, written within double or single quotes:

JavaScript Labels To label JavaScript statements you precede the statements with a label name and a colon:

The break and the continue statements are the only JavaScript statements that can "jump out of" a code block. Syntax: break labelname; continue labelname; 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:

JavaScript Break and Continue

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

Merging an Array with Values

The concat() method can also take values as arguments: Example (Merging an Array with Values) var arr1 = ["Cecilie", "Lone"]; var myChildren = arr1.concat(["Emil", "Tobias", "Linus"]);

The lastIndexOf()

The lastIndexOf() method returns the index of the last occurrence of a specified text in a string: Both indexOf(), and lastIndexOf() return -1 if the text is not found. Both methods accept a second parameter as the starting position for the search: var pos = str.indexOf("locate",15);

String Length

The length of a string is found in the built in property length: Example var txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; var sln = txt.length;

Append

The length property provides an easy way to append a new element to an array: var fruits = ["Banana", "Orange", "Apple", "Mango"]; fruits[fruits.length] = "Kiwi"; // Appends "Kiwi" to fruits

Avoid new Array()

The new keyword only complicates the code. It can also produce some unexpected results: var points = new Array(40, 100); // Creates an array with two elements (40 and 100) What if I remove one of the elements? var points = new Array(40); // Creates an array with 40 undefined elements !!!!! var points = new Array(); // Bad var points = []; // Good

How to Recognize an Array

The problem is that the JavaScript operator typeof returns "object": Solution 1: To solve this problem ECMAScript 5 defines a new method Array.isArray(): Array.isArray(fruits); // returns true To solve this problem you can create your own isArray() function: function isArray(x) { return x.constructor.toString().indexOf("Array") > -1; } Solution 3: The instanceof operator returns true if an object is created by a given constructor: var fruits = ["Banana", "Orange", "Apple", "Mango"]; fruits instanceof Array; // returns true

The typeof Operator

The typeof operator returns the type of a variable or an expression: typeof "John Doe" // Returns "string" typeof 314 // Returns "number"

The unshift()

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

The valueOf() Method

The valueOf() Method 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.

Extracting String Parts

There are 3 methods for extracting a part of a string: slice(start, end) ... returns the extracted part in a new string. If a parameter is negative, the position is counted from the end of the string. If you omit the second parameter, the method will slice out the rest of the string: substring(start, end).... similar to slice(). The difference is that substring() cannot accept negative indexes. substr(start, length)...similar to slice(). The difference is that the second parameter specifies the length of the extracted part.

Extracting String Characters

There are 3 methods for extracting string characters: charAt(position)....The charAt() method returns the character at a specified index (position) in a string: E.G var str = "HELLO WORLD"; str.charAt(0); // returns H charCodeAt(position)....The charCodeAt() method returns the unicode of the character at a specified index in a string: EG. str.charCodeAt(0); // returns 72 Property access [ ]....str[0]; // returns H It makes strings look like arrays (but they are not) If no character is found, [ ] returns undefined, while charAt() returns an empty string.

The document.write() method should only be used for testing.

Using document.write() after an HTML document is loaded, will delete all existing HTML:

Using splice() to Remove Elements

Using splice() to Remove Elements With clever parameter setting, you can use splice() to remove elements without leaving "holes" in the array: Example var fruits = ["Banana", "Orange", "Apple", "Mango"]; fruits.splice(0, 1); // Removes the first element of fruits

Local Variables

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

Adding Numbers and Strings

WARNING !! JavaScript uses the + operator for both addition and concatenation. Numbers are added. Strings are concatenated.

Do Not Declare Strings, Numbers, and Booleans as Objects!

When a JavaScript variable is declared with the keyword "new", the variable is created as an object: var x = new String(); // Declares x as a String object

When comparing two strings

When comparing two strings, "2" will be greater than "12", because (alphabetically) 1 is less than 2. To secure a proper result, variables should be converted to the proper type before comparison:

concatenation

When used on strings, the + operator is called the concatenation operator. If you add a number and a string, the result will be a string!

equal booleans

When using the == operator, equal booleans are equal: When using the === operator, equal booleans are not equal, because the === operator expects equality in both type and value. Example var x = false; var y = new Boolean(false); // (x === y) is false because x and y have different types Or even worse. Objects cannot be compared: Example var x = new Boolean(false); var y = new Boolean(false); // (x == y) is false because objects cannot be compared

Why Functions?

Why Functions? You can reuse code: Define the code once, and use it many times. You can use the same code many times with different arguments, to produce different results.

Access the Full Array

With JavaScript, the full array can be accessed by referring to the array name:

JavaScript Can Change HTML Content

document.getElementById("demo").innerHTML = "Hello JavaScript";

JavaScript Can Hide HTML Elements

document.getElementById("demo").style.display = "none"; Hiding HTML elements can be done by changing the display style: show: document.getElementById("demo").style.display = "block";

JavaScript Can Change HTML Styles (CSS)

document.getElementById("demo").style.fontSize = "35px"; Changing the style of an HTML element,

function toCelsius(fahrenheit) { return (5/9) * (fahrenheit-32); }

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:

The toExponential() Method

toExponential() returns a string, with a number rounded and written using exponential notation. A parameter defines the number of characters behind the decimal point: eg. var x = 9.656; x.toExponential(2); // returns 9.66e+0 x.toExponential(4); // returns 9.6560e+0 The parameter is optional. If you don't specify it, JavaScript will not round the number.

The toFixed() Method

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

The toPrecision() Method

toPrecision() returns a string, with a number written with a specified length: Example var x = 9.656; x.toPrecision(); // returns 9.656 x.toPrecision(2); // returns 9.7

The toString() Method

toString() returns a number as a string. All number methods can be used on any type of numbers (literals, variables, or expressions):

Converting to Upper and Lower Case

toUpperCase(): toLowerCase():

typeof and instanceof

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

Everything With a "Value" is True

var b1 = Boolean(100); var b2 = Boolean(3.14); var b3 = Boolean(-15); var b4 = Boolean("Hello"); var b5 = Boolean('false'); var b6 = Boolean(1 + 7 + 3.14); ANSWER 100 is true 3.14 is true -15 is true Any (not empty) string is true Even the string 'false' is true Any expression (except zero) is true

Sorting Object Arrays JavaScript arrays often contain objects: cars.sort(function(a, b){return a.year - b.year});

var cars = [ {type:"Volvo", year:2016}, {type:"Saab", year:2001}, {type:"BMW", year:2010} ]; displayCars(); function myFunction() { cars.sort(function(a, b){return a.year - b.year}); displayCars(); } function displayCars() { document.getElementById("demo").innerHTML = cars[0].type + " " + cars[0].year + "<br>" + cars[1].type + " " + cars[1].year + "<br>" + cars[2].type + " " + cars[2].year; }

With a label reference, the break statement can be used to jump out of any code block:

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>"; }// BMW Volvo A code block is a block of code between { and }.


Conjuntos de estudio relacionados

Series 6: Chapter 5:3 Variable Annuities

View Set

Instructions & Programs: Crash Course Computer Science #8

View Set

EUROPEAN HISTORY SECTION I, Part A Time -- 55 minutes 55 Questions

View Set

Exam 2 WE-1-DP Drawing Interpretation 120102a

View Set

Psychology - Abnormal Behavior & Mental Disorders

View Set

Chapter 2: The Fall and the Promise of a Savior

View Set