Javascript Review
window.alert()
Creates a pop-up window to display data
Why do we use functions?
Functions are useful because you can reuse code. Define the function once, and then reuse it many times later on with different arguments to produce different results.
toFixed() method
Good for working with money. Returns a string with the number written with the specified number of decimal places. 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
Identifiers
Identifiers are names, used to name variables, functions, and labels. First character must be a letter, an underscore, or a dollar sign. Numbers can be used, but not as the first character. All identifiers are case sensitive.
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: var x = 9.656; x.toExponential(2); // returns 9.66e+0 x.toExponential(4); // returns 9.6560e+0 x.toExponential(6); // returns 9.656000e+0
debugger
stops the execution of Javascript, and calls (if available) the debugger function.
try...catch
implements error handling to a block of statements
What can Javascript do?
-Can change HTMl content -Can change HTML attributes -Can change HTML styles (CSS) -Can hide/show HTML elements
if...else
Marks a block of statements to be executed, depending on a condition.
do...while
executes a block of statements, and repeats the block, while a condition is true.
return
exits a function
Accessing Object Properties
Can be done in two ways: objectName.propertyName or objectName["propertyName"] Ex: var person = { firstName:"John"; lastName:"Doe"; } document.getElementById("demo").innerHTML = person.firstName + " " + person.lastName; Causes the name "John Doe" to be written in the element with class "demo"
Number() method
Can be used to convert Javascript variables into numbers: x = true; Number(x); // returns 1 x = false; Number(x); // returns 0 x = new Date(); Number(x); // returns 1404568027739 x = "10" Number(x); // returns 10 x = "10 20" Number(x); // returns NaN
Comments
Code that is not executed. Useful to explain what sections of code is doing, and can be placed in front of a section of code to keep it from being executed. after // or between /* */
Statements
Composed of values, operators, expressions, keywords, and comments. Separated by semicolons. Multiple statements can be combined into large blocks using curly brackets {}, such as in functions.
Variables
Containers for storing values. Use the keyword "var". Work very much like algebra, have stuff represent something else. It is good practice to declare all variables at the start of the script. Many variables can be in one statement as long as they are separated by a comma. Can be in a single line or can be on multiple lines. var person = "JohnDoe", carName = "Volvo", price = 200;
Math.random()
Creates a random number between 0 (inclusive) and 1 (exclusive).
Data Types
Data can be numbers, strings, objects, booleans, or arrays. When adding a number and a string together, Javascript treats the number as a string. Ex: 16 + "Volvo" = 16Volvo Javascript evaluates expressions from left to right, which can produce different values: Ex: 16 + 4 + "Volvo" = 20Volvo Ex: "Volvo" + 16 + 4 = Volvo164. This is because all of the numbers are treated as strings after Volvo. Since the first operand is a string, all of the others are treated as strings.
What can event handlers do?
Event handlers can be used to handle, and verify, user input, user actions, and browser actions: Things that should be done every time a page loads Things that should be done when the page is closed Action that should be performed when a user clicks a button Content that should be verified when a user inputs data And more ... Many different methods can be used to let JavaScript work with events: HTML event attributes can execute JavaScript code directly HTML event attributes can call JavaScript functions You can assign your own event handler functions to HTML elements You can prevent events from being sent or being handled
*= operator
Ex: x *= y Same as x = x*y
+= operator
Ex: x += y Same as x = x + y
-= operator
Ex: x -= y Same as x = x - y
/= operator
Ex: x /= y Same as x = x/y
slice() method
Extracts a part of a string and returns the extracted part in a new string. 2 parameters, the starting index and the ending index positions: var str = "Apple, Banana, Kiwi"; var res = str.slice(7, 13); returns "Banana" If parameters are negative, it starts from the end of the string. If you omit the second parameter, the method will slice out the rest of the string.
Events
HMTL events are "things" that happen to HTML elements. When javascript is used in HTML pages, Javascript can react on these events. An HTML event can be something the browser does, or something a user does. Here are some examples of HTML events: An HTML web page has finished loading An HTML input field was changed An HTML button was clicked Often, when events happen, you may want to do something. JavaScript lets you execute code when events are detected. HTML allows event handler attributes, with JavaScript code, to be added to HTML elements. Ex: <button onclick="document.getElementById("demo").innerHTML = function">buttontext</button> SInce JS code is usually long, it is more common to see event attributes calling functions, rather than this long code above.
Using Javascript
In HTML, JS code must be inserted between these tags <script></script> <script type="text/javascript"> the type attribute is not necessary since JS is the default scripting language in HTML. Can be placed in the head or the body. When placed at the bottom of the body, display speeds are quicker since script compilation slows down the display. External: <script src="myScript.js"></script>, can be placed in head or body.
Local Variables
In Javascript, scope is the set of variables, objects, and functions that you have access to. Local variables have local scope, which means they can only be accessed within the function. Ex: // code here can not use carName function myFunction() { var carName = "Volvo"; // code here can use carName } Since local variables are only recognized inside their functions, variables with the same name can be used in different functions. Local variables are created when a function starts, and deleted when the function is completed.
Case and Character Set
JS is usually written with lower camel case (getElementById) Uses Unicode character set, covers almost all characters, punctuations, and symbols in the world.
Objects
Javascript objects are like values, except that they can contain many values, which are written as name:value pairs. Javascript objects are containers for named values. Ex: var car = {type:"Fiat", model:"500", color:"white"} Enclosed in curly brackets, separated by a comma.
switch
Marks a block of statements to be executed, depending on different cases
Math Properties (Constants)
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(x) returns the absolute (positive) value of x: Math.abs(-4.7); // returns 4.7
Math.ceil()
Math.ceil(x) returns the value of x rounded up to its nearest integer: Math.ceil(4.4); // returns 5
Math.cos()
Math.cos(x) returns the cosine (a value between -1 and 1) of the angle x (given in radians). If you want to use degrees instead of radians, you have to convert degrees to radians: Angle in radians = Angle in degrees x PI / 180. Math.cos(0 * Math.PI / 180); // returns 1 (the cos of 0 degrees)
JavaScript Random Integers
Math.floor(Math.random() * 10); // returns a number between 0 and 9 Math.floor(Math.random() * 11); // returns a number between 0 and 10 Math.floor(Math.random() * 10) + 1; // returns a number between 1 and 10 Math.floor(Math.random() * 100) + 1; // returns a number between 1 and 100
Math.floor()
Math.floor(x) returns the value of x rounded down to its nearest integer: Math.floor(4.7); // returns 4
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: Math.min(0, 150, 30, 20, -8, -200); // returns -200 Math.max(0, 150, 30, 20, -8, -200); // returns 150
Math.pow()
Math.pow(x, y) returns the value of x to the power of y: Math.pow(8, 2); // returns 64
Math.round()
Math.round(x) returns the value of x rounded to its nearest integer: Math.round(4.7); // returns 5 Math.round(4.4); // returns 4
Math.sin()
Math.sin(x) returns the sine (a value between -1 and 1) of the angle x (given in radians). If you want to use degrees instead of radians, you have to convert degrees to radians: Angle in radians = Angle in degrees x PI / 180. Math.sin(90 * Math.PI / 180); // returns 1 (the sine of 90 degrees)
Math.sqrt()
Math.sqrt(x) returns the square root of x: Math.sqrt(64); // returns 8
console.log()
Method of displaying data that is used for debugging purposes.
Object Methods
Methods are actions that can be performed on objects. Methods are stored in properties as method functions. A method is actually a function definition stored as a property value. Do not declare strings, booleans, or numbers as objects. When variables are declared with the keyword "new", they are declared as objects. This slows down the execution speed and complicates your code.
parseInt() method
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
valueOf() method
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 In JavaScript, a number can be a primitive value (typeof = number) or an object (typeof = object). 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.
search() method
Same thing as indexOf(), except that it can take on more powerful search values.
parseFloat() method
Similar to parseInt(), but it parses a string and returns a number. This number can include decimal places: 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
substring() method
Similar to the string method, but cannot take on negative parameters. If the second parameter is omitted, it will slice out the rest of the string.
Strings
String are a series of characters in quotes, such as "John Doe" or "the quick brown fox jumps over lazy dog" Quotes can be strings, as long as the phrase in quotes is in single quotes while the larger string is in double quotes. Or vice versa.
charAt() method
The charAt() method returns the character at a specified index (position) in a string: var str = "HELLO WORLD"; str.charAt(0); // returns H
charCodeAt() method
The charCodeAt() method returns the unicode of the character at a specified index in a string: var str = "HELLO WORLD"; str.charCodeAt(0); // returns 72
substr() method
The first parameter specifies the starting point, and the second parameter specifies the length of the string, from that starting point, that is to be extracted. If the second parameter is omitted, the rest of the string will be sliced.
indexOf() method
The indexOf() method returns the index of (the position of) the first occurrence of a specified text in a string. Returns -1 if the text is not found. Positions count from zero.
Functions
A Javascript function is a block of code designed to perform a particular task. A function is executed when something "invokes" it (calls it). The codes that are to be executed are in curly brackets. function name(parameter1, parameter2) {code} A function is made up of function, a name, and parantheses that specify the parameters. Parameters are the names listed in the function definition. The arguments are the real values received by the function when invoked. The arguments (parameters) behave as local variables in the function.
Expressions
A combination of values, variables, and operators which computes to a value. The computation is called an evaluation.
Converting a String to an Array
A string can be converted to an array with the split() method: 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].
Global Variables
A variable that is declared outside of a function is a global variable. A global variable has global scope, which means that all scripts and functions on a webpage can access it. Ex: var carName = " Volvo"; // code here can use carName function myFunction() { // code here can use carName } With JavaScript, the global scope is the complete JavaScript environment. In HTML, the global scope is the window object. All global variables belong to the window object. var carName = "Volvo"; // code here can use window.carName
innerHTML
A way JS can be displayed. Writes into an HTML element. To access an HTML element, use document.getElementById(id) Ex: document.getElementById(demo).innerHTML = text ---- Text is then put into the element with the id "demo"
document.write()
A way of displaying data, should only be used for testing purposes.
A note on string methods:
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.
Operators
Arithmetic operators (+ - * /) Assignment operators ( = )
Math Object Methods
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
concat() method
concat() joins two or more strings: var text1 = "Hello"; var text2 = "World"; text3 = text1.concat(" ", text2); 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!");
function
declares a function.
continue
jumps out of a loop and starts at the top
for
marks a block of statements to be executed, as long as a condition is true.
Creating Date Objects
new Date() new Date(milliseconds) new Date(dateString) new Date(year, month, day, hours, minutes, seconds, milliseconds) var d = new Date() d.toString() = default d.toDateString() = most readable d.toUTCString() = a date display standard
Common HTML Events
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
toPrecision() method
returns a string, with a number written with a specifed length: 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
Terms
syntax = set of rules computer program = a list of instructions to be executed by a computer. These program instructions are called statements. In HTML, Javascript programs are executed by the browser.
break
terminates a switch or loop.
toUpperCase() and toLowerCase()
var text1 = "Hello World!"; // String var text2 = text1.toUpperCase(); // text2 is text1 converted to upper var text1 = "Hello World!"; // String var text2 = text1.toLowerCase(); // text2 is text1 converted to lower
lastIndexOf() method
The lastIndexOf() method returns the index of the last occurrence of a specified text in a string. Returns -1 if the text is not found. Positions count from zero.
replace() method
The replace() method replaces a specified value with another value in a string: str = "Please visit Microsoft!"; var n = str.replace("Microsoft", "W3Schools"); By default, the replace() function replaces only the first match. To replace all matches, use a regular expression with a g flag (for global match): str = "Please visit Microsoft!"; var n = str.replace(/Microsoft/g, "W3Schools");
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.
A Proper Random Function
This JavaScript function always returns a random number between min (included) and max (excluded): function getRndInteger(min, max) { return Math.floor(Math.random() * (max - min) ) + min; } This JavaScript function always returns a random number between min and max (both included): function getRndInteger(min, max) { return Math.floor(Math.random() * (max - min + 1) ) + min; }
toString() method
This method returns a number as a string. All number methods can be used on any type of numbers (literals, variables, or expressions): var x = 123; x.toString(); // returns 123 from variable x (123).toString(); // returns 123 from literal 123 (100 + 23).toString(); // returns 123 from expression 100 + 23
JS values
Two types: fixed values = literals, such as strings and numbers variable values = variables
Javascript numbers
Unlike many other programming languages, JavaScript does not define different types of numbers, like integers, short, long, floating-point etc. JavaScript numbers are always stored as double precision floating point numbers, following the international IEEE 754 standard. This format stores numbers in 64 bits, where the number (the fraction) is stored in bits 0 to 51, the exponent in bits 52 to 62, and the sign in bit 63: Numbers are considered accurate up to 15 digits. The floating point arithmetic is not always accurate, so it is helpful to multiply into larger numbers and then divide out: var x = (0.2 * 10 + 0.1 * 10) / 10; // x will be 0.3 Never write a number with a leading zero, like 07. NaN and Infinity both return "number" values. Do not make number objects, similar to string objects. This slows down the execution.
Accessing Object Methods
Use the following syntax: objectName.objectMethod () Ex: var person = { firstName: "John", lastName : "Doe", id : 5566, fullName : function() { return this.firstName + " " + this.lastName; } }; document.getElementById("demo").innerHTML = person.fullName(); When you call this method, it performs the function that is stored as a property in the object and writes "John Doe"
Undeclared Variables
Variables can often be undeclared without a value. The value can be something that has to be calculated, or something that will be provided later, such as user input. If you re-declare a variable and don't give a value, it won't lose its original value.
Accessing a string as an array is unsafe
You might have seen code like this, accessing a string as an array: var str = "HELLO WORLD"; str[0]; // returns H This is unsafe and unpredictable: It does not work in all browsers (not in IE5, IE6, IE7) It makes strings look like arrays (but they are not) str[0] = "H" does not give an error (but does not work) If you want to read a string as an array, convert it to an array first.