Javascript ReDo

Réussis tes devoirs et examens dès maintenant avec Quizwiz!

search()

The search() method searches a string for a specified value and returns the position of the match: Example var str = "Please locate where 'locate' occurs!"; var pos = str.search("locate");

slice()

The slice() Method slice() extracts a part of a string and returns the extracted part in a new string. The method takes 2 parameters: the starting index (position), and the ending index (position). This example slices out a portion of a string from position 7 to position 13: Example var str = "Apple, Banana, Kiwi"; var res = str.slice(7, 13); The result of res will be: Banana

Sorting an Array

The sort() method sorts an array alphabetically: Example var fruits = ["Banana", "Orange", "Apple", "Mango"]; fruits.sort(); // Sorts the elements of fruits

JavaScript Statements

This statement tells the browser to write "Hello Dolly." inside an HTML element with id="demo": Example document.getElementById("demo").innerHTML = "Hello Dolly.";

JavaScript and Camel Case

Underscore: first_name, last_name, master_card, inter_city. Lower Camel Case: JavaScript programmers tend to use camel case that starts with a lowercase letter: firstName, lastName, masterCard, interCity.

One Statement, Many Variables

You can declare many variables in one statement. Start the statement with var and separate the variables by comma: var person = "John Doe", carName = "Volvo", price = 200;

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.

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

The typeof Operator

You can use the JavaScript typeof operator to find the type of a JavaScript variable. The typeof operator returns the type of a variable or an expression:

Access the Elements of an Array

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

The substr() Method

substr() is similar to slice(). The difference is that the second parameter specifies the length of the extracted part. Example var str = "Apple, Banana, Kiwi"; var res = str.substr(7, 6); The result of res will be: Banana

The substring() Method

substring() is similar to slice(). The difference is that substring() cannot accept negative indexes. Example var str = "Apple, Banana, Kiwi"; var res = str.substring(7, 13); The result of res will be: Banana Try it Yourself »

JavaScript Booleans

JavaScript Booleans Booleans can only have two values: true or false. Example var x = true; var y = false;

JavaScript evaluates expressions

JavaScript evaluates expressions from left to right. Different sequences can produce different results: JavaScript: var x = 16 + 4 + "Volvo"; Result: 20Volvo

Parameter Rules

JavaScript function definitions do not specify data types for parameters. JavaScript functions do not perform type checking on the passed arguments. JavaScript functions do not check the number of arguments received.

Functions Can Be Used as Values

JavaScript functions can be used as values: Example function myFunction(a, b) { return a * b; } var x = myFunction(4, 3);

JavaScript Types are Dynamic.

JavaScript has dynamic types. This means that the same variable can be used to hold different data types: Example var x; // Now x is undefined var x = 5; // Now x is a Number var x = "John"; // Now x is a String

JavaScript White Space

JavaScript ignores multiple spaces. You can add white space to your script to make it more readable. The following lines are equivalent:

JavaScript Keywords

JavaScript keywords are used to identify actions to be performed. The var keyword tells the browser to create variables: var x, y; x = 5 + 6; y = x * 10;

JavaScript Objects

JavaScript objects are written with curly braces. Object properties are written as name:value pairs, separated by commas. Example var person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};

JavaScript Code Blocks

JavaScript statements can be grouped together in code blocks, inside curly brackets {...}. The purpose of code blocks is to define statements to be executed together. One place you will find statements grouped together in blocks, is in JavaScript functions: Example function myFunction() { document.getElementById("demo1").innerHTML = "Hello Dolly."; document.getElementById("demo2").innerHTML = "How are you?"; }

JavaScript Keywords

JavaScript statements often start with a keyword to identify the JavaScript action to be performed. Here is a list of some of the keywords you will learn about in this tutorial: Keyword Description -break Terminates a switch or a loop -continue Jumps out of a loop and starts at the top -debugger Stops the execution of JavaScript, and calls (if available) the debugging function -do ... while Executes a block of statements, and repeats the block, while a condition is true -for Marks a block of statements to be executed, as long as a condition is true -function Declares a function -if ... else Marks a block of statements to be executed, depending on a condition -return Exits a function -switch Marks a block of statements to be executed, depending on different cases -try ... catch Implements error handling to a block of statements -var Declares a variable

JavaScript Strings

JavaScript strings are used for storing and manipulating text.

assignment operator

JavaScript uses an assignment operator ( = ) to assign values to variables:

JavaScript Character Set

JavaScript uses the Unicode character set. Unicode covers (almost) all the characters, punctuations, and symbols in the world.

Array Elements Can Be Objects

JavaScript variables can be objects. Arrays are special kinds of objects. Because of this, you can have variables of different types in the same Array. You can have objects in an Array. You can have functions in an Array. You can have arrays in an Array: myArray[0] = Date.now; myArray[1] = myFunction; myArray[2] = myCars;

JavaScript Data Types

JavaScript variables can hold many data types: numbers, strings, objects and more: var length = 16; // Number var lastName = "Johnson"; // String var x = {firstName:"John", lastName:"Doe"}; // Object

JavaScript Data Types

JavaScript variables can hold numbers like 100 and text values like "John Doe". In programming, text values are called text strings. JavaScript can handle many types of data, but for now, just think of numbers and strings. Strings are written inside double or single quotes. Numbers are written without quotes. If you put a number in quotes, it will be treated as a text string.

Logical Operators

Logical operators are used to determine the logic between variables or values. Given that x = 6 and y = 3, the table below explains the logical operators: Operator Description && and (x < 10 && y > 1) is true || or (x == 5 || y == 5) is false ! not !(x == y) is true

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 Try it Yourself » Example Math.max(0, 150, 30, 20, -8, -200); // returns 150

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

Adding and Deleting Elements

Method/Description document.createElement(element) Create an HTML element document.removeChild(element) Remove an HTML element document.appendChild(element) Add an HTML element document.replaceChild(element) Replace an HTML element document.write(text) Write into the HTML output stream

Changing HTML Elements

Method/Description element.innerHTML = new html content Change the inner HTML of an element element.attribute = new value Change the attribute value of an HTML element element.setAttribute(attribute, value) Change the attribute value of an HTML element element.style.property = new style Change the style of an HTML element

Finding HTML Elements

Method/Description document.getElementById(id) Find an element by element id document.getElementsByTagName(name) Find elements by tag name document.getElementsByClassName(name) Find elements by class name

Multi-line Comments

Multi-line comments start with /* and end with */. Any text between /* and */ will be ignored by JavaScript. This example uses a multi-line comment (a comment block) to explain the code: /* The code below will change the heading with id = "myH" and the paragraph with id = "myP" in my web page: */ document.getElementById("myH").innerHTML = "My First Page"; document.getElementById("myP").innerHTML = "My first paragraph.";

JavaScript Comments

Not all JavaScript statements are "executed". Code after double slashes // or between /* and */ is treated as a comment. Comments are ignored, and will not be executed: var x = 5; // I will be executed // var x = 6; I will NOT be executed

JavaScript Comparison Operators

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

JavaScript Assignment Operators Assignment operators assign values to JavaScript variables.

Operator Example Same As = x = y x = y += x += y x = x + y -= x -= y x = x - y *= x *= y x = x * y /= x /= y x = x / y %= x %= y x = x % y

Re-Declaring JavaScript

Re-Declaring JavaScript Variables If you re-declare a JavaScript variable, it will not lose its value. The variable carName will still have the value "Volvo" after the execution of these statements: Example var carName = "Volvo"; var carName;

What is the DOM?

The DOM is a W3C (World Wide Web Consortium) standard. The DOM defines a standard for accessing documents: "The W3C Document Object Model (DOM) is a platform and language-neutral interface that allows programs and scripts to dynamically access and update the content, structure, and style of a document." The W3C DOM standard is separated into 3 different parts: Core DOM - standard model for all document types XML DOM - standard model for XML documents HTML DOM - standard model for HTML documents

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. Syntax do { code block to be executed } 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); Try it Yourself »

JavaScript For Loop

The For Loop The for loop is often the tool you will use when you want to create a loop. The for loop has the following syntax: for (statement 1; statement 2; statement 3) { code block to be executed } Statement 1 is executed before the loop (the code block) starts. Statement 2 defines the condition for running the loop (the code block). Statement 3 is executed each time after the loop (the code block) has been executed. Example for (i = 0; i < 5; i++) { text += "The number is " + i + "<br>"; } From the example above, you can read: Statement 1 sets a variable before the loop starts (var i = 0). Statement 2 defines the condition for the loop to run (i must be less than 5). Statement 3 increases a value (i++) each time the code block in the loop has been executed. Statement 1 Normally you will use statement 1 to initialize the variable used in the loop (i = 0). This is not always the case, JavaScript doesn't care. Statement 1 is optional. You can initiate many values in statement 1 (separated by comma): Statement 2 Often statement 2 is used to evaluate the condition of the initial variable. This is not always the case, JavaScript doesn't care. Statement 2 is also optional. If statement 2 returns true, the loop will start over again, if it returns false, the loop will end. Statement 3 Often statement 3 increments the value of the initial variable. This is not always the case, JavaScript doesn't care, and statement 3 is optional. Statement 3 can do anything like negative increment (i--), positive increment (i = i + 15), or anything else. Statement 3 can also be omitted (like when you increment your values inside the loop):

The HTML DOM Document Object

The HTML DOM Document Object The document object represents your web page. If you want to access any element in an HTML page, you always start with accessing the document object. Below are some examples of how you can use the document object to access and manipulate HTML.

Adding Array Elements

The easiest way to add a new element to an array is using the push method: Example var fruits = ["Banana", "Orange", "Apple", "Mango"]; fruits.push("Lemon"); // adds a new element (Lemon) to fruits

finding HTML Element by Id

The easiest way to find an HTML element in the DOM, is by using the element id. This example finds the element with id="intro": Example var myElement = document.getElementById("intro");

The innerHTML Property

The easiest way to get the content of an element is by using the innerHTML property. The innerHTML property is useful for getting or replacing the content of HTML elements. The innerHTML property can be used to get or change any HTML element, including <html> and <body>.

getElementById Method

The getElementById Method The most common way to access an HTML element is to use the id of the element. In the example above the getElementById method used id="demo" to find the element.

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

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}

Pushing

The push() method adds a new element to an array (at the end): Example var fruits = ["Banana", "Orange", "Apple", "Mango"]; fruits.push("Kiwi"); // Adds a new element ("Kiwi") to fruits Try it Yourself »

Array Properties and Methods

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

replace() regular expression as the search value.

The replace() method can also take a regular expression as the search value. 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): Example str = "Please visit Microsoft!"; var n = str.replace(/Microsoft/g, "W3Schools"); Try it Yourself »

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");

Reversing an Array

The reverse() method reverses the elements in an array. You can use it to sort an array in descending order: Example var fruits = ["Banana", "Orange", "Apple", "Mango"]; fruits.sort(); // Sorts the elements of fruits fruits.reverse(); // Reverses the order of the elements

JavaScript Arithmetic Operators

Arithmetic operators are used to perform arithmetic on numbers: Operator Description + Addition - Subtraction * Multiplication / Division % Modulus ++ Increment -- Decrement

Empty Values

An empty value has nothing to do with undefined. An empty string variable has both a value and a type. Example var car = ""; // The value is "", the typeof is "string"

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.

JavaScript Date Formats

A JavaScript date can be written as a string: Sun Apr 16 2017 13:06:22 GMT-0500 (Central Daylight Time) or as a number: 1492365982427 Dates written as numbers, specifies the number of milliseconds since January 1, 1970, 00:00:00.

Function Expressions

A JavaScript function can also be defined using an expression. A function expression can be stored in a variable: Example var x = function (a, b) {return a * b};

JavaScript Function Parameters

A JavaScript function does not perform any checking on parameter values (arguments).

JavaScript Functions

A JavaScript function is a block of code designed to perform a particular task. A JavaScript function is executed when "something" invokes it (calls it). function myFunction(p1, p2) { return p1 * p2; // The function returns the product of p1 and p2

JavaScript Function Syntax

A JavaScript function is defined with the function keyword, followed by a name, followed by parentheses (). Function names can contain letters, digits, underscores, and dollar signs (same rules as variables). The parentheses may include parameter names separated by commas: (parameter1, parameter2, ...) The code to be executed, by the function, is placed inside curly brackets: {} function name(parameter1, parameter2, parameter3) { code to be executed } Function parameters are the names listed in the function definition. Function arguments are the real values received by the function when it is invoked. Inside the function, the arguments (the parameters) behave as local variables.

Primitive Data

A primitive data value is a single simple data value with no additional properties and methods. The typeof operator can return one of these primitive types: string number boolean null undefined Example typeof "John" // Returns "string" typeof 3.14 // Returns "number" typeof true // Returns "boolean" typeof false // Returns "boolean"

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:

Converting to Upper and Lower Case

A string is converted to upper case with toUpperCase(): Example var text1 = "Hello World!"; // String var text2 = text1.toUpperCase(); // text2 is text1 converted to upper

Global JavaScript Variables

A variable declared outside a function, becomes GLOBAL. A global variable has global scope: All scripts and functions on a web page can access it. var carName = " Volvo"; // code here can use carName function myFunction() { // code here can use carName }

Adding Events Handlers

Adding Events Handlers Method/Description document.getElementById(id).onclick = function(){code} Adding event handler code to an onclick event

What is an Array?

An array is a special variable, which can hold more than one value at a time. If you have a list of items (a list of car names, for example), storing the cars in single variables could look like this: var car1 = "Saab"; var car2 = "Volvo"; var car3 = "BMW"; However, what if you want to loop through the cars and find a specific one? And what if you had not 3 cars, but 300? The solution is an array! An array can hold many values under a single name, and you can access the values by referring to an index number.

JavaScript Arithmetic w/variables

As with algebra, you can do arithmetic with JavaScript variables, using operators like = and +: Example var x = 5 + 2 + 3; You can also add strings, but strings will be concatenated: Example var x = "John" + " " + "Doe"; Try it Yourself » var x = "5" + 2 + 3; Try it Yourself » If you put a number in quotes, the rest of the numbers will be treated as strings, and concatenated.

Special Characters

Because strings must be written within quotes, JavaScript will misunderstand this string: var y = "We are the so-called "Vikings" from the north." The string will be chopped to "We are the so-called ". The solution to avoid this problem, is to use the \ escape character. The backslash escape character turns special characters into string characters:

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

Java Conditions

Conditional statements are used to perform different actions based on different conditions.

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: Example var points = [40, 100, 1, 5, 25, 10]; points.sort(function(a, b){return a - b});

How Can Comparison Operators be Used

Comparison operators can be used in conditional statements to compare values and take action depending on the result: if (age < 18) text = "Too young";

Declaring (Creating) JavaScript Variables

Creating a variable in JavaScript is called "declaring" a variable. You declare a JavaScript variable with the var keyword: You declare a JavaScript variable with the var keyword: var carName; After the declaration, the variable has no value. (Technically it has the value of undefined) To assign a value to the variable, use the equal sign: carName = "Volvo"; You can also assign a value to the variable when you declare it: var carName = "Volvo";

Displaying Dates

Displaying Dates In this tutorial we use a script to display dates inside a <p> element with id="demo": <p id="demo"></p> <script> document.getElementById("demo").innerHTML = Date(); </script>

Do NOT create global variables unless you intend to. In "Strict Mode" automatically global variables will fail.

Do NOT create global variables unless you intend to. In "Strict Mode" automatically global variables will fail.

Function Hoisting

Earlier in this tutorial, you learned about "hoisting". Hoisting is JavaScript's default behavior of moving declarations to the top of the current scope. Hoisting applies to variable declarations and to function declarations. Because of this, JavaScript functions can be called before they are declared: myFunction(5); function myFunction(y) { return y * y; }

boolean

Everything With a "Real" Value is True var b1 = Boolean(100); var b2 = Boolean(3.14);

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

Finding HTML Elements

Finding HTML Elements Often, with JavaScript, you want to manipulate HTML elements. To do so, you have to find the elements first. There are a couple of ways to do this: Finding HTML elements by id Finding HTML elements by tag name Finding HTML elements by class name Finding HTML elements by CSS selectors Finding HTML elements by HTML object collections

Breaking Long Code Lines

For best readability, programmers often like to avoid code lines longer than 80 characters. If a JavaScript statement does not fit on one line, the best place to break it is after an operator: Example document.getElementById("demo").innerHTML = "Hello Dolly.";

JavaScript Line Length and Line Breaks

For best readability, programmers often like to avoid code lines longer than 80 characters. If a JavaScript statement does not fit on one line, the best place to break it, is after an operator: document.getElementById("demo").innerHTML = "Hello Dolly."; Try it Yourself »

Function Parameters and Arguments

Function Parameters and Arguments Earlier in this tutorial, you learned that functions can have parameters: functionName(parameter1, parameter2, parameter3) { code to be executed } Function parameters are the names listed in the function definition. Function arguments are the real values passed to (and received by) the function.

Function Arguments

Function arguments (parameters) work as local variables inside functions.

Self-Invoking Functions

Function expressions can be made "self-invoking". A self-invoking expression is invoked (started) automatically, without being called. Function expressions will execute automatically if the expression is followed by (). You cannot self-invoke a function declaration. You have to add parentheses around the function to indicate that it is a function expression: Example (function () { var x = "Hello!!"; // I will invoke myself })();

Find the Highest (or Lowest) Value

How to find the highest value in an array? Example var points = [40, 100, 1, 5, 25, 10]; points.sort(function(a, b){return b - a}); // now points[0] contains the highest value

JavaScript Identifiers

Identifiers are names. 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. In JavaScript, the first character must be a letter, an underscore (_), or a dollar sign ($). Subsequent characters may be letters, digits, underscores, or dollar signs.

Automatically Global

If you assign a value to a variable that has not been declared, it will automatically become a GLOBAL variable. This code example will declare a global variable carName, even if the value is assigned inside a function. Example myFunction(); // code here can use carName function myFunction() { carName = "Volvo"; }

Undefined

In JavaScript, a variable without a value, has the value undefined. The typeof is also undefined. Example var person; // Value is undefined, type is undefined Try it Yourself » Any variable can be emptied, by setting the value to undefined. The type will also be undefined.

JavaScript Scope

In JavaScript, objects and functions are also variables. In JavaScript, scope is the set of variables, objects, and functions you have access to. JavaScript has function scope: The scope changes inside functions.

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 consider it a bug in JavaScript that typeof null is an object. It should be null. You can empty an object by setting it to null: Example var person = null; // Value is null, but type is still an object

JavaScript Expressions

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 "John" + " " + "Doe"

JavaScript Literals

JavaScript Literals The most important rules for writing fixed values are: Numbers are written with or without decimals: 10.50; 1001; 'John Doe';

JavaScript Operators

JavaScript Operators JavaScript uses arithmetic operators ( + - * / ) to compute values:

JavaScript Programs

JavaScript Programs Most JavaScript programs contain many JavaScript statements. The statements are executed, one by one, in the same order as they are written. In this example x, y, and z are given values, and finally z is displayed: Example var x, y, z; x = 5; y = 6; z = x + y; document.getElementById("demo").innerHTML = z;

JavaScript Statements

JavaScript Statements JavaScript statements are composed of: Values, Operators, Expressions, Keywords, and Comments.

JavaScript Values

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.

JavaScript Variables

JavaScript Variables In a programming language, variables are used to store data values. JavaScript uses the var keyword to declare variables. An equal sign is used to assign values to variables. In this example, x is defined as a variable. Then, x is assigned (given) the value 6:

JavaScript Variables

JavaScript Variables JavaScript variables are containers for storing data values. In this example, x, y, and z, are variables: Example var x = 5; var y = 6; var z = x + y;

Conditional (Ternary) Operator

JavaScript also contains a conditional operator that assigns a value to a variable based on some condition. Syntax variablename = (condition) ? value1:value2 Example var voteable = (age < 18) ? "Too young":"Old enough";

JavaScript Arrays

JavaScript arrays are written with square brackets. Array items are separated by commas. The following code declares (creates) an array called cars, containing three items (car names): Example var cars = ["Saab", "Volvo", "BMW"];

Semicolons ;

Semicolons separate JavaScript statements. Add a semicolon at the end of each executable statement: var a, b, c;

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. Example var fruits = ["Banana", "Orange", "Apple", "Mango"]; fruits.shift(); // Removes the first element "Banana" from fruits Try it Yourself »

Single Line Comments

Single line comments start with //. Any text between // and the end of the line will be ignored by JavaScript (will not be executed). This example uses a single-line comment before each code line: // Change heading: document.getElementById("myH").innerHTML = "My First Page"; // Change paragraph: document.getElementById("myP").innerHTML = "My first paragraph.";

The DOM Programming Interface

The HTML DOM can be accessed with JavaScript (and with other programming languages). In the DOM, all HTML elements are defined as objects. The programming interface is the properties and methods of each object. A property is a value that you can get or set (like changing the content of an HTML element). A method is an action you can do (like add or deleting an HTML element). Example The following example changes the content (the innerHTML) of the <p> element with id="demo": Example <html> <body> <p id="demo"></p> <script> document.getElementById("demo").innerHTML = "Hello World!"; </script> </body> </html> In the example above, getElementById is a method, while innerHTML is a property.

JavaScript HTML DOM Document

The HTML DOM document object is the owner of all other objects in your web page.

What is the HTML DOM?

The HTML DOM is a standard object model and programming interface for HTML. It defines: The HTML elements as objects The properties of all HTML elements The methods to access all HTML elements The events for all HTML elements In other words: The HTML DOM is a standard for how to get, change, add, or delete HTML elements.

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]; }

JavaScript While Loop

The While Loop The while loop loops through a block of code as long as a specified condition is true. Syntax while (condition) { code block to be executed } 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++; }

Looping Array Elements

The best way to loop through an array, is using a "for" loop: Example var fruits, text, fLen, i; fruits = ["Banana", "Orange", "Apple", "Mango"]; fLen = fruits.length; text = "<ul>"; for (i = 0; i < fLen; i++) { text += "<li>" + fruits[i] + "</li>"; }

The charAt() Method

The charAt() method returns the character at a specified index (position) in a string: Example var str = "HELLO WORLD"; str.charAt(0); // returns H Try it Yourself »

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)

lastIndexOf()

The lastIndexOf() method returns the index of the last occurrence of a specified text in a string: Example var str = "Please locate where 'locate' occurs!"; var pos = str.lastIndexOf("locate"); Both the indexOf(), and the lastIndexOf() methods return -1 if the text is not found. JavaScript counts positions from zero. 0 is the first position in a string, 1 is the second, 2 is the third ... Both methods accept a second parameter as the starting position for the search.

String Length

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

The length Property

The length property of an array returns the length of an array (the number of array elements). Example var fruits = ["Banana", "Orange", "Apple", "Mango"]; fruits.length; // the length of fruits is 4 Try it Yourself »

Complex Data

The typeof operator can return one of two complex types: function object Example typeof [1,2,3,4] // Returns "object" (not "array", see note below) typeof {name:'John', age:34} // Returns "object" typeof function myFunc(){} // Returns "function"

Extracting String Characters

There are 2 safe methods for extracting string characters: charAt(position) charCodeAt(position)

Extracting String Parts

There are 3 methods for extracting a part of a string: slice(start, end) substring(start, end) substr(start, length)

The else if Statement

Use the else if statement to specify a new condition if the first condition is false. Syntax 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 } Example If time is less than 10:00, create a "Good morning" greeting, if not, but time is less than 20:00, create a "Good day" greeting, otherwise a "Good evening": if (time < 10) { greeting = "Good morning"; } else if (time < 20) { greeting = "Good day"; } else { greeting = "Good evening"; }

The else Statement

Use the else statement to specify a block of code to be executed if the condition is false. if (condition) { block of code to be executed if the condition is true } else { block of code to be executed if the condition is false } Example If the hour is less than 18, create a "Good day" greeting, otherwise "Good evening": if (hour < 18) { greeting = "Good day"; } else { greeting = "Good evening"; }

The if Statement

Use the if statement to specify a block of JavaScript code to be executed if a condition is true. Syntax if (condition) { block of code to be executed if the condition is true Example Make a "Good day" greeting if the hour is less than 18:00: if (hour < 18) { greeting = "Good day"; }

Creating an Array

Using an array literal is the easiest way to create a JavaScript Array. Syntax: var array_name = [item1, item2, ...];

Using Comments to Prevent Execution

Using comments to prevent execution of code is suitable for code testing. Adding // in front of a code line changes the code lines from an executable line to a comment. This example uses // to prevent execution of one of the code lines: Example //document.getElementById("myH").innerHTML = "My First Page"; document.getElementById("myP").innerHTML = "My first paragraph."; /* document.getElementById("myH").innerHTML = "My First Page"; document.getElementById("myP").innerHTML = "My first paragraph."; */

The () Operator Invokes the Function

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: Example function toCelsius(fahrenheit) { return (5/9) * (fahrenheit-32); } document.getElementById("demo").innerHTML = toCelsius;

Value = undefined

Value = undefined In computer programs, variables are often declared without a value. The value can be something that has to be calculated, or something that will be provided later, like user input. A variable declared without a value will have the value undefined. The variable carName will have the value undefined after the execution of this statement: Example var carName;

JavaScript Operator Precedence Values

Value Operator Description Example 19 ( ) Expression grouping (3 + 4) 18 . Member person.name 18 [] Member person["name"] 17 () Function call myFunction() 17 new Create new Date() 16 ++ Postfix Increment i++ 16 -- Postfix Decrement i-- 15 ++ Prefix Increment ++i 15 -- Prefix Decrement --i 15 ! Logical not !(x==y) 15 typeof Type typeof x 14 * Multiplication 10 * 5 14 / Division 10 / 5 14 % Modulo division 10 % 5 14 ** Exponentiation 10 ** 2 13 + Addition 10 + 5 13 - Subtraction 10 - 5 12 << Shift left x << 2 12 >> Shift right x >> 2 12 >>> Shift right (unsigned) x >>> 2 11 < Less than x < y 11 <= Less than or equal x <= y 11 > Greater than x > y 11 >= Greater than or equal x >= y 10 == Equal x == y 10 === Strict equal x === y 10 != Unequal x != y 10 !== Strict unequal x !== y 6 && Logical and x && y 5 || Logical or x || y 3 = Assignment x = y 3 += Assignment x += y 3 -= Assignment x -= y 3 *= Assignment x *= y 3 %= Assignment x %= y 3 <<= Assignment x <<= y 3 >>= Assignment x >>= y 3 >>>= Assignment x >>>= y 3 &= Assignment x &= y 3 ^= Assignment x ^= y 3 |= Assignment x |= y

Local JavaScript Variables

Variables declared within a JavaScript function, become LOCAL to the function. Local variables have local scope: They can only be accessed within the function. Example // code here can not use carName function myFunction() { var carName = "Volvo"; // code here can use carName }

Function Return

When JavaScript reaches a return statement, the function will stop executing. If the function was invoked from a statement, JavaScript will "return" to execute the code after the invoking statement. Functions often compute a return value. The return value is "returned" back to the "caller": Example Calculate the product of two numbers, and return the result: var x = myFunction(4, 3); // Function is called, return value will end up in x function myFunction(a, b) { return a * b; // Function returns the product of a and b } The result in x will be: 12

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. 2 < 12 true 2 < "12" true 2 < "John" false 2 > "John" false 2 == "John" false "2" < "12" false "2" > "12" true "2" == "12" false

Access the Full Array

With JavaScript, the full array can be accessed by referring to the array name: Example var cars = ["Saab", "Volvo", "BMW"]; document.getElementById("demo").innerHTML = cars;

The escape character (\) can

also be used to insert other special characters in a string. These are commonly used special characters that can be inserted in a text with the backslash sign: Code Outputs \' single quote \" double quote \\ backslash

JavaScript functions

are defined with the function keyword. You can use a function declaration or a function expression. Function Declarations Earlier in this tutorial, you learned that functions are declared with the following syntax: function functionName(parameters) { code to be executed } Declared functions are not executed immediately. They are "saved for later use", and will be executed later, when they are invoked (called upon). Example function myFunction(a, b) { return a * b; } Try it Yourself »

The concat() Method

concat() joins two or more strings: Example var text1 = "Hello"; var text2 = "World"; text3 = text1.concat(" ", text2);


Ensembles d'études connexes

Chapter 11 Committed Romantic Relationships

View Set

Early childhood science study guide ( BY: MONICA HERNANDEZ)

View Set

Ryan - Basic Principles of Accounting

View Set

Första deklinationen Grupp F - sjukliga förändringar och tillstånd

View Set

AWS Cloud Practitioner Exam - Coursera Questions

View Set

Corals and Symbiotic Relationships

View Set

Basic Nursing Ch 4: "Legal Principles in Nursing"

View Set

N3381 - Psychiatric Mental Health Exam 2

View Set