Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...

Full Transcript

CS202 - Fundamentals of Front End Development Front-end development, also known as client-side development is the practice of producing HTML, CSS and JavaScript for a website or web application so that a user can see and interact with them directly. Front End Languages “Front end languages” lives...

CS202 - Fundamentals of Front End Development Front-end development, also known as client-side development is the practice of producing HTML, CSS and JavaScript for a website or web application so that a user can see and interact with them directly. Front End Languages “Front end languages” lives in your browser.  HTML  CSS  JavaScript Front End Development Front end web development is NOT design. The front end developer stands between the designer on one end and the back end developer on the other. As a Front end developer you have to:  Make sure the content is presented as desire.  All user interactions are handled. 02- URL: Uniform Resource Locator URL stands for Uniform Resource Locator. It is the global address of documents and other resources on the World Wide Web. A URL is one type of Uniform Resource Identifier (URI). Uniform Resource Identifier (URI) Is the generic term for all types of names and addresses that refer to objects on the World Wide Web. The term "Web address" is a synonym for a URL that uses the HTTP or HTTPS protocol. Here are few examples:  http://mydomain.com  http://mydomain.com/myresource.html  https://mydomain.com/resource2.html  ftp://mydomain.com/resource3.html  Parts of a URL http://mydomain.com/myresource.html The first part of the URL is called a protocol identifier and it indicates what protocol to use. http://mydomain.com/myresource.html The second part is called a resource location name and it specifies the IP address or the domain name where the resource is located. http://mydomain.com/myresource.html The third part is optional; it’s the resource name, typically a file name on server. Dynamic URL A dynamic URL is the address of a dynamic Web page. Dynamic URLs often contain the characters like: ?, &, %, +, =, $, cgi-bin http://mydomain.com/myres.php?fname=Asim There is a fourth optional part for dynamic URL. It contain the parameters sent to the dynamic page, in key=value pair. ?fname=Asim&job=Software%20Engineer URL Encoding URLs can only be sent over the Internet using the ASCII character-set. Since URLs often contain characters outside the ASCII set, the URL has to be converted into a valid ASCII format. URL encoding replaces unsafe ASCII characters with a "%" followed by two hexadecimal digits. URLs cannot contain spaces. URL encoding normally replaces a space with a plus (+) sign or with %20. 03- HTTP Basics HTTP HTTP stands for Hypertext Transfer Protocol. It’s an application level protocol, works as a request- response protocol between a client and server over web. HTTP is the foundation of data communication for the World Wide Web. Hypertext is structured text that uses logical links (hyperlinks) between nodes containing text. HTTP Requests Two commonly used methods for a request-response between a client and server are: GET and POST  GET - Requests data from a specified resource, has limited length and can cached by client.  POST - Submits data to be processed to a specified resource, has no data limit and never cached. HTTPS Hypertext Transfer Protocol Secure. Or HTTP over SSL It’s a secure version of HTTP. All the communications between client and server are encrypted and authenticated. 04- Web Server, Services and Agents Web Server A Web server is a program that uses HTTP (Hypertext Transfer Protocol) to serve the files that form Web pages to users, in response to their requests, by HTTP clients. Dedicated computers and appliances may be referred to Web servers as well. Application Server An application server is a software framework that provides both facilities to create web applications and a server environment to run them. It acts as a set of components accessible to the developer through an API defined by the platform itself. Web Services Web services are client and server applications that communicate over the World Wide Web (WWW) using HyperText Transfer Protocol (HTTP). Typically Web Service resides on a Web Server and use XML to communicate messages. Web Agents / User Agents These are the Software applications that are used by users to communicate to a Web server to retrieve resources or receive data. Web Browser is a typical example of Web/User Agent application. 05- Domain, Hosting, FTP Domain A domain name is a unique name for your web site.  Google.com  Microsoft.com  TechnologyWisdom.com  Facebook.com It is that part of the Uniform Resource Locator (URL) that tells a domain name server using the domain name system (DNS), where to forward a request for a Web page. The domain name is mapped to an IP address (which represents a physical point on the Internet). See here some example of Domain Name.  www.google.com.pk  facebook.com  validate.ecp.gov Parts of Domain Name www.google.com.pk facebook.com validate.ecp.gov TLD: Top Level Domain www.google.com.pk facebook.com validate.ecp.gov Second Level Domain Must be unique on the Internet and registered with one of the ICANN-accredited registrars for specific TLD. www.google.com.pk facebook.com validate.ecp.gov Third Level Domain – Sub Domain Hosting An Internet hosting service is a service that runs Internet servers, allowing organizations and individuals to serve content on the Internet. FTP The File Transfer Protocol (FTP) is a standard network protocol used to transfer computer files from one host to another host over a TCP-based network, such as the Internet. FTP is simple and secure File is split into small data packets. Client sends a packet to destination after opening an authenticated connection. FTP server check the packet, if data is correct, it send request for next packet, till the file is completely received. FTP Client FTP Client is typically software that allows us to communicate with a server to transfer files using FTP protocol. HTML: Hyper Text Markup Language Introduction HTML stands for Hyper Text Markup Language. It is the standard markup language used to create web pages. Along with CSS, and JavaScript, HTML is a cornerstone technology used to create web pages, as well as to create user interfaces for mobile and web applications. Web browsers can read HTML files and render them into visible or audible web pages. HTML Basics HTML Documents All HTML documents must start with a type declaration: See the following example: Lorem ipsum Dummy Text. The HTML document itself begins with and ends with. The visible part of the HTML document is between and. HTML Headings HTML headings are defined with the to tags. HTML Paragraphs HTML paragraphs are defined with the tag: My Paragraph. AnotherParagraph. HTML Images HTML images are defined with the tag. The source file (src), alternative text (alt), and size (width and height) are provided as attributes: 08- Elements and Attributes HTML Elements HTML elements are written with a start tag, with an end tag, with the content in between: content The HTML element is everything from the start tag to the end tag: Dummy Text Nested HTML Elements HTML elements can be nested (elements can contain elements). All HTML documents consist of nested HTML elements. This example contains 4 HTML elements: The element defines the whole document. It has a start tag and an end tag. The element content is another HTML element (the element). My Heading My paragraph. The element defines the document body. It has a start tag and an end tag. The element content is two other HTML elements ( and ). Dummy Text Lorem ipsum dolor The element defines a heading. It has a start tag and an end tag. The element content is: My Heading. My Heading The element defines a paragraph. It has a start tag and an end tag. The element content is: My paragraph. My paragraph. Don't Forget the End Tag Some HTML elements will display correctly, even if you forget the end tag: My paragraph Empty HTML Elements HTML elements with no content are called empty elements. is an empty element without a closing tag (the tag defines a line break). Empty elements can be "closed" in the opening tag like this:. HTML5 does not require empty elements to be closed. But if you want stricter validation, or you need to make your document readable by XML parsers, you should close all HTML elements. Use Lowercase Tags HTML tags are not case sensitive: means the same as. The HTML5 standard does not require lowercase tags, but W3C recommends lowercase in HTML4, and demands lowercase for stricter document types. HTML Attributes  HTML elements can have attributes  Attributes provide additional information about an element  Attributes are always specified in the start tag  Attributes come in name/value pairs like: name="value" The lang Attribute The document language can be declared in the tag. The language is declared in the lang attribute. Declaring a language is important for accessibility applications (screen readers) and search engines: My Heading My paragraph. The title Attribute HTML paragraphs are defined with the tag. In this example, the element has a title attribute. The value of the attribute is “paragraph": W3Schools is a web developer's site. It provides tutorials and references covering many aspects of web programming,including HTML, CSS, JavaScript, XML, SQL, PHP etc. The href Attribute HTML links are defined with the tag. The link address is specified in the href attribute: Example This is a link Size Attributes HTML images are defined with the tag. The filename of the source (src), and the size of the image (width and height) are all provided as attributes: Example Always Use Lowercase Attributes  The HTML5 standard does not require lower case attribute names.  W3C recommends lowercase in HTML4, and demands lowercase for stricter document types like XHTML. Always Quote Attribute Values The HTML5 standard does not require quotes around attribute values. The href attribute, demonstrated above, can be written as: Single or Double Quotes? Double style quotes are the most common in HTML, but single style can also be used. In some situations, when the attribute value itself contains double quotes, it is necessary to use single quotes: Comments in HTML are not displayed by the browser, but they can help document your HTML. With comments you can place notifications and reminders in your HTML. Try these examples and see the differences: Comments are also great for debugging HTML, because you can comment out HTML lines of code, one at a time, to search for errors: Conditional Comments You might stumble upon conditional comments in HTML: Software Program Tags HTML comments tags can also be generated by various HTML software programs. For example tags wrapped inside HTML comments by FrontPage and Expression Web. As a rule, let these tags stay, to help support the software that created them. 14- HTML Links HTML Links-Hyperlinks HTML links are hyperlinks. A hyperlink is a text or an image you can click on, and jump to another document. HTML Links – Syntax In HTML, links are defined with the Visit Google! HTML Links - Image as Link In HTML, it is common to use images as links. As in the following example: HTML Links - The id Attribute The id attribute can be used to create bookmarks inside HTML documents. Bookmarks are not displayed in any special way. They are invisible to the reader. Add an id attribute to any element: Useful Tips Section Then create a link to the element (tips): View Tips Create a link to the element (tips) from another page: The alt Attribute  The alt attribute specifies an alternate text for the image, if it cannot be displayed.  The value of the alt attribute should describe the image in words. HTML Screen Readers  Screen readers are software programs that can read what is displayed on a screen.  Used on the web, screen readers can "reproduce" HTML as text-to-speech, sound icons, or braille output.  Screen readers are used by people who are blind, visually impaired, or learning disabled. Image Size - Width and Height  You can use the style attribute to specify the width and height of an image.  The values are specified in pixels (use px after the value) Last name: 10 { text = "Input not valid“; } else { text = "Input OK"; } document.getElementById("demo").innerHTML = text;} 53- JavaScript Syntax JavaScript Programs: A computer program is a list of "instructions" to be "executed" by the computer. In a programming language, these program instructions are called statements, and we have already discussed that, JavaScript is a programming language. Script statements are separated by semicolon. See some examples below: var x = 5; var y = 6; var z = x + y; JavaScript Statements JavaScript statements are composed of Values, Operators, Expressions, Keywords, and Comments. JavaScript Values The JavaScript syntax defines two types of values:  Fixed values  Variable values. Whereas, fixed values are called literals. Variable values are called variables. JavaScript Literals The most important rules for writing fixed values are: Numbers are written with or without decimals such as:  10.50  1001 Strings are text, written within double or single quotes:  "John Doe"  'John Doe' Expressions can also represent fixed values:  5+6  5 * 10 JavaScript Variables In a programming language, variables are used to store data values.  JavaScript uses the var keyword to define variables.  An equal sign is used to assign values to variables. Check out some examples given below: In the example which is given below, x is defined as a variable. Then, x is assigned (given) the value 8:  var x;  x = 8; JavaScript Operators JavaScript uses an assignment operator (=) to assign values to variables:  var x = 5;  var y = 6; JavaScript uses arithmetic operators ( + - * / ) to compute values: (5 + 6) * 10 var x = (5 + 6) * 10; JavaScript Keywords JavaScript keywords are used to identify actions to be performed. The var keyword tells the browser to create a new variable:  var x = 5 + 6;  var y = x * 10; JavaScript Comments Not all JavaScript statements are "executed". Code after double slashes // or between is treated as a comment. Comments are ignored, and will not be executed:  var x = 5; // will be executed  // var x = 6; will NOT be executed JavaScript is Case Sensitive All JavaScript identifiers are case sensitive. The variables lastName and lastname, are two different variables.  lastName = "Doe";  lastname = "Peterson"; JavaScript and Camel Case Historically, programmers have used three ways of joining multiple words into one variable name: Hyphens:  first-name  last-name  master-card Underscore:  first_name  master_card Camel Case:  FirstName  MasterCard In programming languages, especially in JavaScript, camel case often starts with a lowercase letter: firstName, masterCard JavaScript Character Set JavaScript uses the Unicode character set. Unicode covers (almost) all the characters, punctuations, and symbols in the world. 54- JavaScript Statements In programming language, a statement tells the browser what to do. The statements are executed, one by one, in the same order as they are written. Most JavaScript programs contain many JavaScript statements. Here is a JavaScript Statement: document.getElementById("demo").innerHTML = “Hi, Everyone."; Explanation: This statement tells the browser to write "Hello Everyone." inside an HTML element with id="demo". Let’s discuss some general elements in JavaScript statements Semicolons (;) Semicolons in JavaScript separate JavaScript statements. Add a semicolon at the end of each executable statement. Let evaluate the role of semicolons in JS through the example given below: a = 5; b = 6; c = a + b; When separated by semicolons, multiple statements on one line are allowed: a = 5; b = 6; c = a + b; JavaScript White Space JavaScript ignores multiple spaces. You can add white space to your script to make it more readable. 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."; 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. 55- JavaScript Comments JavaScript comments can be used to explain JavaScript code, and to make it more readable. Furthermore, you can also use the JS comments to prevent execution, when testing alternative code.  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).  Multi-line Comments: Multi-line comments start with. Any text between will be ignored by JavaScript. 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. 56a- JavaScript Variables & Operators JavaScript Variables: JavaScript variables are containers for storing data values. In the example, given below, x, y, and z, are variables: var x = 5; var y = 6; var z = x + y; From the example above, you can expect: - x stores the value 5 - y stores the value 6 - z stores the value 11 JavaScript Identifiers All JavaScript variables must be identified with unique names and these unique names are called identifiers. Identifiers can be short names (like x and y), or more descriptive names (age, sum, totalVolume). The general rules for constructing names for variables (unique identifiers) are:  Names can contain letters, digits, underscores, and dollar signs.  Names must begin with a letter  Names can also begin with $ and _  Names are case sensitive (y and Y are different variables)  Reserved words (like JavaScript keywords) cannot be used as names The Assignment Operator In JavaScript, the equal sign (=) is an "assignment" operator, not an "equal to" operator. This is different from algebra. 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 quotes around a number, it will be treated as a text string. var pi = 3.14; var person = "John Doe"; var answer = 'Yes I am!'; var anum = '3.14'; Declaring (Creating) JavaScript Variables Creating a variable in JavaScript is called "declaring" a variable. You declare a JavaScript variable with the var keyword: var carName; After the declaration, the variable is empty (it has no value). To assign a value to the variable, use the equal sign: carName = "Volvo"; See the example: var carName = "Volvo"; document.getElementById("demo").innerHTML = carName; 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; 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: var carName; Note: If you re-declare a JavaScript variable, it will not lose its value. 56b- JavaScript Variables & Operators JavaScript Operators As with algebra, you can do arithmetic with JavaScript variables, using operators like = and + See these Examples: var x = 5 + 2 + 3; var x = 5; // assign the value 5 to x var y = 2; // assign the value 2 to y var z = x + y; // assign the value 7 to z (x + y) JavaScript String Operators In JavaScript, the + operator can also be used to add (concatenate) strings. See the example below: txt1 = "John"; txt2 = "Doe"; txt3 = txt1 + " " + txt2; The += assignment operator can also be used to add (concatenate) strings: txt1 = "What a very "; txt1 += "nice day"; Adding Strings and Numbers Adding two numbers will return the sum, but adding a number and a string will return a string: x = 5 + 5; y = "5" + 5; z= "Hello" + 5; Output 57- JavaScript Functions What is JavaScript Function? A JavaScript function is a block of code designed to perform a particular task. The function is executed when "something" invokes it (calls it). 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). function name (parameter1, parameter2, parameter3) { code to be executed } Explanation: Function parameters are the names listed in the function definition. Function arguments are the real values received by the function when it is invoked. Function Invocation The code inside the JS 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 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. Why Functions? (Importance of 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. See the example below: function toCelsius(fahrenheit) { return (5/9) * (fahrenheit-32); } document.getElementById("demo").innerHTML = toCelsius(32); The () Operator Invokes the Function Using the example above, toCelsius refers to the function object, and toCelcius() refers to the function result. Accessing a function without () will return the function definition: function toCelsius(fahrenheit) { return (5/9) * (fahrenheit-32); } document.getElementById("demo").innerHTML = toCelsius; Functions Used as Variables In JavaScript, you can use functions the same way as you use variables. See the example below: You can use: var text = "The temperature is " + toCelsius(32) + " Centigrade"; Instead of: var x = toCelsius(32); var text = "The temperature is " + x + " Centigrade"; 58- JavaScript Objects Object properties can be primitive values, other objects, and functions. An object method is an object property containing a function definition. JavaScript objects are containers for named values, called properties and methods. 59- JavaScript Scope Scope is the set of variables, objects, and functions you have access to. In JavaScript, objects and functions are also variables. JavaScript has function scope: The scope changes inside functions. 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. Local variables are created when a function starts, and deleted when the function is completed. See the example below: // code here cannot use variable userName function myFunction() { var userName = “Tariq"; // code here can use variable userName } 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. The global scope is the complete JavaScript environment. Automatically Global If you assign a value to a variable that has not been declared, it will automatically become a GLOBAL variable. The Lifetime of JavaScript Variables: The lifetime of a JavaScript variable starts when it is declared.  Local variables are deleted when the function is completed.  Global variables are deleted when you close the page.  Function arguments (parameters) work as local variables inside functions.  In HTML, the global scope is the window object: All global variables belong to the window object. 60- JavaScript Events JavaScript's interaction with HTML is handled through events that occur when the user or the browser manipulates a page. HTML Events An HTML event can be something the browser does, or something a user does.  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. See the example below: With single quotes: With double quotes: In the following example, an onclick attribute (with code), is added to a button element: The time is? Output in Browser: Here, the JavaScript code changes the content of the element with id="demo". In the next example, the code changes the content of its own element (using this.innerHTML): The time is? Output in Browser: Furthermore, you can search online for HTML events with practical demonstration 60- JavaScript Strings A JavaScript string simply stores a series of characters like "Mike Slough". A string can be any text inside quotes. You can use single or double quotes. For example: var carname = "Volvo XC60"; (with double quotes) var carname = 'Volvo XC60'; (with double quotes) Furthermore, you can use quotes inside a string, as long as they don't match the quotes surrounding the string. See this example: var answer = "It's alright"; var answer = "He is called 'Johnny'"; var answer = 'He is called "Johnny"'; String Length The length of a string is found in the built in property length. See the example below: var txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; var sln = txt.length; 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." Explanation 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. Checkout the example below: var x = 'It\'s alright'; var y = "We are the so-called \"Vikings\" from the north.“ The escape character (\) can also be used to insert other special characters in a string. 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. For further clarification, see the examples below: Example document.getElementById("demo").innerHTML = “hi,how are you?."; You can also break up a code line within a text string with a single backslash: Example document.getElementById "demo".innerHTML = “hi \ How are you?"; The safest (but a little slower) way to break a long string is to use string addition: Example document.getElementById "demo".innerHTML = “Hi," + “How are you?”; Example You cannot break up a code line with a backslash: document.getElementById("demo").innerHTML = \ " Hi, How are you?"; Strings Can be Objects Normally, JavaScript strings are primitive values, created from literals: var firstName = “Mike" But, strings can also be defined as objects with the keyword new. Check out an example below: var x = “Mike"; var y = new String “Mike" ; // typeof x will return string // typeof y will return object When using the == equality operator, equal strings looks equal: var x = “Mike"; var y = new String “Mike" ; // (x == y) is true because x and y have equal values When using the === equality operator, equal strings are not equal, because the === operator expects equality in both type and value. var x = “Mike"; var y = new String “Mike" ; String Properties and Methods Primitive values, like “Mike Slough", 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. 62- JavaScript Numbers JavaScript numbers can be written with, or without decimals. See in example below: var x = 34.00; // A number with decimals var y = 34; // A number without decimals Furthermore, extra large or extra small numbers can be written with scientific (exponent) notation: var x = 123e5; // 12300000 var y = 123e-5; // 0.00123 JavaScript Numbers are Always 64-bit Floating Point 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: Value (aka Fraction/Mantissa) Exponent Sign 52 bits (0 - 51) 11 bits (52 - 62) 1 bit (63) Precision Integers (numbers without a period or exponent notation) are considered accurate up to 15 digits. See the example below: var x = 999999999999999; // x will be 999999999999999 var y = 9999999999999999; // y will be 10000000000000000 The maximum number of decimals is 17, but floating point arithmetic is not always 100% accurate: var x = 0.2 + 0.1; // x will be 0.30000000000000004 To solve the problem, it helps to multiply and divide: var x = (0.2 * 10 + 0.1 * 10) / 10; // x will be 0.3 Hexadecimal JavaScript interprets numeric constants as hexadecimal if they are preceded by 0x. var x = 0xFF; // x will be 255 Infinity Infinity (or -Infinity) is the value JavaScript will return if you calculate a number outside the largest possible number. See the example below: var myNumber = 2; while (myNumber != Infinity) { // Execute until Infinity myNumber = myNumber * myNumber; } Division by 0 (zero) also generates Infinity: var x = 2 / 0; // x will be Infinity var y = -2 / 0; // y will be –Infinity Infinity is a number: typeOf Infinity returns number. typeof Infinity; // returns "number" NaN - Not a Number NaN is a JavaScript reserved word indicating that a value is not a number. Trying to do arithmetic with a non-numeric string will result in NaN (Not a Number): You can use the global JavaScript function isNaN() to find out if a value is a number. var x = 100 / "Apple"; isNaN(x); // returns true because x is Not a Number 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)  When using the == equality operator, equal numbers looks equal: var x = 500; var y = new Number(500); // (x == y) is true because x and y have equal values  When using the === equality operator, equal numbers are not equal, because the === operator expects equality in both type and value. var x = 500; var y = new Number(500); // (x === y) is false because x and y have different types  Objects cannot be compared: var x = new Number(500); var y = new Number(500); // (x == y) is false because objects cannot be compared Number Properties and Methods 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. 63- JavaScript Number Methods Number Methods JavaScript number methods are methods that can be used on numbers. In JavaScript, all number methods return a new value. They do not change the original variable. In the table below, you can see some number methods with their appropriate description: Method Description toString() Returns a number as a string toExponential() Returns a string, with a number rounded and written using exponential notation. toFixed() Returns a string, with a number rounded and written with a specified number of decimals. toPrecision() Returns a string, with a number written with a specified length valueOf() Returns a number as a number Converting Variables to Numbers There are 3 JavaScript functions that can be used to convert variables to numbers:  Number()  parseInt()  parseFloat() These methods are not number methods, but global JavaScript methods. Let’s illustrate them briefly: Number() Number(), can be used to convert JavaScript variables to numbers. See some examples below: 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 parseInt() parseInt() parses a string and returns a whole number. Spaces are allowed. Only the first number is returned. If the number cannot be converted, NaN (Not a 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 parseFloat() parseFloat() parses a string and returns a number. Spaces are allowed. Only the first number is returned. If the number cannot be converted, NaN (Not a Number) is returned. 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 64- JavaScript Math To understand the JavaScript Math, we have to evaluate some basic mathematical objects in programming. The Math Object The Math object allows you to perform mathematical tasks. It includes several mathematical methods. Check out the example below: Math.random(); // returns a random number 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); // returns -8 You can find below some meth objects:  Math.random() Math.random() returns a random number between 0 and 1 Math.random();  Math.round() Math.round() rounds a number to the nearest integer: Math.round(4.7); // returns 5 Math.round(4.4); // returns 4  Math.ceil() Math.ceil() rounds a number up to the nearest integer: Math.ceil(4.4); // returns 5  Math.floor() Math.floor() rounds a number down to the nearest integer: Math.floor(4.7); // returns 4 Math Constants JavaScript provides 8 mathematical constants that can be accessed with the Math object: 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 Furthermore, you can check online several Math Object Methods 65- JavaScript Date In JavaScript, The Date object lets you work with dates (years, months, days, hours, minutes, seconds, and milliseconds). Let’s discuss how to deal with date object in JavaScript: JavaScript Date Formats: A JavaScript date can be written as a string: Wed Apr 15 2015 23:17:51 GMT-0700 (Pacific Daylight Time) Or as a number: 1429165071958 Dates written as numbers, specifies the number of milliseconds since January 1, 1970, 00:00:00. Displaying Dates we use a script to display dates inside a element with id="demo": document.getElementById("demo").innerHTML = Date(); Creating Date Objects The Date object lets us work with dates. A date consists of a year, a month, a day, an hour, a minute, a second, and milliseconds. Date objects are created with the new Date() constructor. There are following ways of initiating a date: new Date() new Date(milliseconds) new Date(dateString) // var d = new Date("October 13, 2014 11:13:00"); new Date(year, month, day, hours, minutes, seconds, milliseconds)  Using new Date(number), creates a new date object as zero time plus the number. Zero time is 01 January 1970 00:00:00 UTC. The number is specified in milliseconds: var d = new Date(86400000); document.getElementById("demo").innerHTML = d;  Using new Date(7 numbers), creates a new date object with the specified date and time: The 7 numbers specify the year, month, day, hour, minute, second, and millisecond, in that order: var d = new Date(99,5,24,11,33,30,0); document.getElementById("demo").innerHTML = d;  Variants of the example above let us omit any of the last 4 parameters: var d = new Date(99,5,24); document.getElementById("demo").innerHTML = d; Date Methods When a Date object is created, a number of methods allow you to operate on it. Date methods allow you to get and set the year, month, day, hour, minute, second, and millisecond of objects, using either local time or UTC (universal, or GMT) time. When you display a date object in HTML, it is automatically converted to a string, with the toString() method. d = new Date(); document.getElementById("demo").innerHTML = d.toString();  The toUTCString() method converts a date to a UTC string (a date display standard). var d = new Date(); document.getElementById("demo").innerHTML = d.toUTCString();  The toDateString() method converts a date to a more readable format: var d = new Date(); document.getElementById("demo").innerHTML = d.toDateString(); Date Formats There are generally three types of valid JavaScript date formats:  ISO Dates  Long Dates  Short Dates Let’s discuss each format in detail below: ISO Date Format: The ISO 8601 syntax (YYYY-MM-DD) is the newest (and preferred) JavaScript date format.  var d = new Date("2015-03-25"); // YYYY-MM-DD  var d = new Date("2015-03"); // YYYY-MM  var d = new Date("2015"); // YYYY var d = new Date("2015-03-25T12:00:00"); The T in the date string, between the date and time, indicates UTC time Long Date Format: Long dates are most often written with a "MMM DD YYYY" syntax.  var d = new Date("Mar 25 2015");  year, month, and day can be in any order:  var d = new Date("25 Mar 2015") And, month can be written in full (January), or abbreviated (Jan). Commas are ignored. Names are case insensitive Short Date Format: Short dates are most often written with an "MM/DD/YYYY" syntax. Either "/" or "-" can be used as a separator.  var d = new Date("03/25/2015");  var d = new Date("03-25-2015"); JavaScript will also accept "YYYY/MM/DD" Month is written before day in all Short date and ISO date formats. Date Get Methods Get methods are used for getting a part of a date. In the following table, you can see some methods with description: Method Description getDate() Get the day as a number (1-31) getDay() Get the weekday as a number (0-6) getFullYear() Get the four digit year (yyyy) getHours() Get the hour (0-23) getMilliseconds() Get the milliseconds (0-999) getMinutes() Get the minutes (0-59) JavaScript Date Set Methods Set methods are used for setting a part of a date. In the following table, some date set methods are given: 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) Date Get/Set Methods Let’s use Set and Get methods to add some days to a date object. See the example below: Let’s add 4 days to current date. var d = new Date(); d.setDate( d.getDate() + 4 ); document.getElementById("demo").innerHTML = d; String to Date If you have a valid date string, you can use the Date.parse() method to convert it to milliseconds. Date.parse() returns the number of milliseconds between the date and January 1, 1970. See a script below: var msec = Date.parse("March 21, 2012"); var d = new Date(msec); document.getElementById("demo").innerHTML = d; Date Comparison Date objects can easily be compared using standard comparison operators. See a detailed example below: var today, anotherday, result; today = new Date(); anotherday = new Date("03/25/2016"); if (anotherday > today) { result = "Today is before March 25, 2016.“; } else { result = "Today is after March 25, 2016.“; } 67- JavaScript Arrays 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 = "Toyota";  var car2 = "Honda";  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 Arrays In JavaScript, arrays are used to store multiple values in a single variable. In the example below, we will use a script to display arrays inside a element with id="demo": var cars = ["Toyota", "Honda", "BMW"]; document.getElementById("demo").innerHTML = cars; Creating an Array using an array literal is the easiest way to create a JavaScript Array. Syntax: var array-name = [item1, item2,...]; See an example here: var cars = ["Toyota", "Honda", "BMW"]; Using the JavaScript Keyword new: The following example also creates an Array, and assigns values to it: var cars = new Array("Toyota", "Honda", "BMW"); 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; This statement modifies the first element in cars: cars = “Audi"; Access the Elements of an Array 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 = Date.now;  myArray = myFunction;  myArray = myCars; 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: var person = [“Adil", “Saeed", 46]; Arrays use numbers to access its "elements". In this example, person returns John. Object: var person = {firstName:“Adil", lastName:“Saeed", age:46}; Objects use names to access its "members". In this example, person.firstName returns Adil. Array Properties and Methods The real strength of JavaScript arrays are the built-in array properties and methods:  var x = cars.length;  var y = cars.sort; The length Property The length property of an array returns the length of an array (the number of array elements). var fruits = ["Banana", "Orange", "Apple", "Mango"]; fruits.length; // returns 4 Adding Array Elements The easiest way to add a new element to an array is to use the length property: var fruits = ["Banana", "Orange", "Apple", "Mango"]; fruits[fruits.length] = "Lemon"; // adds a new element (Lemon) to fruits Adding elements with high indexes can create undefined "holes" in an array. Looping Array Elements The best way to loop through an array, is using a "for" loop: var index; var fruits = ["Banana", "Orange", "Apple", "Mango"]; for (index = 0; index < fruits.length; index++) { text += fruits[index]; } 68- JavaScript 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 use numbered indexes. See the example below: var person = []; person = "Adil"; person = "Anwar"; person = 46; var x = person.length; // person.length will return 3 var y = person; // person will return "Adil" What is the Difference between Arrays and Objects? In JavaScript:  Arrays use numbered indexes.  Objects use named indexes. 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. Avoid new Array() There is no need to use the JavaScript's built-in array constructor new Array(). Use [] instead. var points = new Array(); // Bad var points = []; // Good These two different statements both create a new array containing 6 numbers: var points = new Array(40, 100, 1, 5, 25, 10) // Bad var points = [40, 100, 1, 5, 25, 10]; // Good The new keyword complicates your code and produces nasty side effects. How to Recognize an Array? How do I know if a variable is an array? The problem is that the JavaScript operator typeof returns "object" var fruits = ["Banana", "Orange", "Apple", "Mango"]; typeof fruits; // typeof returns object The typeof operator returns object because a JavaScript array is an object. To solve this problem you can create isArray() function: function isArray(myArray) { return myArray.constructor.toString().indexOf("Array") > -1; } 69- Array Methods The strength of JavaScript arrays lies in the array methods. Let’s discuss JavaScript array methods in details: Converting Arrays to Strings In JavaScript, all objects have the valueOf() and toString() methods. The valueOf() method is the default behavior for an array. It returns an array as a string. See an example here: var fruits = ["Banana", "Orange", "Apple", "Mango"]; document.getElementById("demo").innerHTML = fruits.valueOf(); Output The valueOf() method returns an array as a comma separated string. Banana,Orange,Apple,Mango Popping and Pushing When you work with arrays, it is easy to remove elements and add new elements. Popping items out of an array, or pushing items into an array: Popping The pop() method removes the last element from an array: var fruits = ["Banana", "Orange", "Apple", "Mango"]; fruits.pop(); // Removes the last element ("Mango") from fruits Pushing The push() method adds a new element to an array (at the end): var fruits = ["Banana", "Orange", "Apple", "Mango"]; fruits.push("Kiwi"); // Adds a new element ("Kiwi") to fruits Shifting Elements Shifting is equivalent to popping, working on the first element instead of the last. The shift() method removes the first element of an array, and "shifts" all other elements one place up. See an example here: var fruits = ["Banana", "Orange", "Apple", "Mango"]; fruits.shift(); // Removes the first element "Banana" from fruits Changing Elements Array elements are accessed using their index number. Lets discuss with detailed example: var fruits = ["Banana", "Orange", "Apple", "Mango"]; fruits = "Kiwi"; // Changes the first element of fruits to "Kiwi“ // ["Kiwi", "Orange", "Apple", "Mango"] fruits[fruits.length] = "Kiwi"; // Appends "Kiwi" to fruit // ["Banana", "Orange", "Apple", "Mango", "Kiwi" ] Deleting Elements Since JavaScript arrays are objects, elements can be deleted by using the JavaScript operator delete. var fruits = ["Banana", "Orange", "Apple", "Mango"]; delete fruits; // Changes the first element in fruits to undefined // [undefined, "Orange", "Apple", "Mango"] Splicing an Array The splice() method can be used to add new items to an array. See this example: var fruits = ["Banana", "Orange", "Apple", "Mango"]; fruits.splice(2, 1, "Lemon", "Kiwi"); // ["Banana", "Orange", "Lemon", "Kiwi", "Mango"]  The first parameter (2) defines the position where new elements should be added.  The second parameter (1) defines how many elements should be removed.  The rest of the parameters ("Lemon" , "Kiwi") define the new elements to be added. Sorting an Array The sort() method sorts an array alphabetically. var fruits = ["Banana", "Orange", "Apple", "Mango"]; fruits.sort(); // Sorts the elements of fruits // ["Apple", "Banana", "Mango", "Orange"] Reversing an Array The reverse() method reverses the elements in an array. You can use it to sort an array in descending order too. var fruits = ["Banana", "Orange", "Apple", "Mango"]; fruits.sort(); // Sorts the elements of fruits // ["Apple", "Banana", "Mango", "Orange"] fruits.reverse(); // Reverses the order of the elements // ["Orange", "Mango", "Banana", "Apple"] 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. The Compare Function var points = [40, 100, 1, 5, 25, 10]; points.sort(function(a, b){return a-b}); 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. function(a, b){return a-b} When comparing 40 and 100, the sort() method calls the compare function(40,100). The function calculates 40-100, and returns -60 (a negative value). The sort function will sort 40 as a value lower than 100. Joining Arrays The concat() method creates a new array by concatenating two arrays. Here is an example with more details: var myGirls = ["Aisha", "Meryam"]; var myBoys = ["Bilal", "Umer" , "Ali"]; var myChildren = myGirls.concat(myBoys); // Concatenates (joins) myGirls and myBoys arrays Slicing an Array The slice() method slices out a piece of an array into a new array. var fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"]; var citrus = fruits.slice(1, 3); // ["Orange", "Lemon"] var citrus = fruits.slice(2); // ["Lemon", "Apple", "Mango"] 71- JavaScript Comparisons Comparison Operators Comparison operators are used in logical statements to determine equality or difference between variables or values. Major comparison operators are given in the table below: For x = 5 Operator Description Comparing Returns == equal to x == 8 false x == 5 true === equal value and equal type x === "5" false x === 5 true != not equal x != 8 true !== not equal value or not equal x !== "5" true type x !== 5 false > greater than x>8 false < less than x= greater than or equal to x >= 8 false

Use Quizgecko on...
Browser
Browser