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

Full Transcript

What is JavaScript? JavaScript is a very powerful client-side scripting language. JavaScript is used mainly for enhancing the interaction of a user with the webpage. In other words, you can make your webpage more lively and interactive, with the help of JavaScript. JavaScript is also b...

What is JavaScript? JavaScript is a very powerful client-side scripting language. JavaScript is used mainly for enhancing the interaction of a user with the webpage. In other words, you can make your webpage more lively and interactive, with the help of JavaScript. JavaScript is also being used widely in game development and Mobile application development. What you can do with JavaScript? You can modify the content of a web page by adding or removing elements. You can change the style and position of the elements on a web page. You can monitor events like mouse click, hover, etc. and react to it. You can perform and control transitions and animations. You can create alert pop-ups to display info or warning messages to the user. You can perform operations based on user inputs and display the results. You can validate user inputs before submitting it to the server. Why is JavaScript considered a loosely-typed language JavaScript is a loosely typed language, meaning you don’t have to specify what type of information will be stored in a variable in advance. JavaScript automatically types a variable based on what kind of information you assign to it (e.g., that '' or " " to indicate string values). Many other languages, like Java, require you to declare a variable’s type, such as int, float, boolean, or String. Even though the type system in JavaScript allows for a lot of freedom, it lacks the ability of a highly typed system to shout at you whenever you try to add an int to an object, saving you from being forced to spend hours debugging a type error. Why is JavaScript considered a loosely-typed language The typing of JavaScript is ad hoc. A function does not need to accept an integer as a parameter, nor do you need to state clearly that a string is a string. JavaScript now has a lot of versatility. Despite the numerous methods in JavaScript to convert data between different types, there are two that are most frequently done − Values are converted to Strings Values are converted to Numbers Adding JavaScript to Your Web Pages There are typically three ways to add JavaScript to a web page: 1. Embedding the JavaScript code between a pair of and tag. 2. Creating an external JavaScript file with the.js extension and then load it within the page through the src attribute of the tag. 3. Placing the JavaScript code directly inside an HTML tag using the specialtag attributes such as onclick, onmouseover, onkeypress, onload, etc. Adding JavaScript to Your Web Pages : 1 Embedding JavaScript var greet = "Hello World!"; document.write(greet); // Prints: Hello World! Adding JavaScript to Your Web Pages : 2 You can also place your JavaScript code into a separate file with.js extension, and then call that file in your document through the src attribute of the tag, like this: Example: Adding JavaScript to Your Web Pages : 2.js File // A function to display amessage function sayHello() { alert("Hello World!"); } // Call function on click of the button document.getElementById("myBtn").onclick = sayHello; HTML File: Click Me Difference between Client-side and Server-side scripting Client-side scripting languages such as JavaScript, VBScript, etc. are interpreted and executed by the web browser. Server-side scripting languages such as PHP, ASP, Java, Python, Ruby, etc. runs on the web server and the output sent back to the web browser in HTML format. You can use JavaScript to check if the user has entered invalid data in form fields and show notifications for input errors. Response from a server-side script is slower as compared to a client-side script, because server-side scripts are processed on the remote computer not on the user's local computer. Understanding the JavaScripts syntax: The syntax of JavaScript is the set of rules that define a correctly structured JavaScript program. A JavaScript consists of JavaScript statements that are placed within the HTML tags in a web page, or within the external JavaScript file having.js extension. Example: var x = 5; var y = 10; var sum = x + y; document.write(sum); // Prints variable value Case sensitivity in JavaScript JavaScript is case-sensitive. This means that variables, language keywords, function names, and other identifiers must always be typed with a consistent capitalization of letters. Example: var myVar = "Hello World!"; console.log(myVar); console.log(MyVar); console.log(myvar); JavaScript Variables You can create a variable with the var keyword The assignment operator (=) is used to assign value to a variable var varName = value; Example: var name = "Peter Parker"; var age = 21; var isMarried = false; JavaScript Variables In JavaScript, variables can also be declared without having any initial values assigned to them. This is useful for variables which are supposed to hold values like user inputs. Example: // Declaring Variable var userName; // Assigning value userName = “James"; JavaScript Hoisting Hoisting is JavaScript's default behavior of moving declarations to the top. JavaScript Declarations are Hoisted In JavaScript, a variable can be declared after it has been used. In other words; a variable can be used before it has been declared Hoisting is JavaScript's default behavior of moving all declarations to the top of the current scope (to the top of the current script or the current function). JavaScript Hoisting Example 1 x = 5; // Assign 5 to x elem = document.getElementById("demo"); // Find an element elem.innerHTML = x; // Display x in the element var x; // Declare x Example 2 var x; // Declare x x = 5; // Assign 5 to x elem = document.getElementById("demo"); // Find an element elem.innerHTML = x; // Display x in the element Naming Conventions for JavaScript Variables These are the following rules for naming a JavaScript variable: A variable name must start with a letter, underscore (_), or dollar sign ($). A variable name cannot start with a number. A variable name can only contain alpha-numeric characters (A-z, 0-9)and underscores. A variable name cannot contain spaces. A variable name cannot be a JavaScript keyword or a JavaScript reservedword. JavaScript generating Output In JavaScript there are several different ways of generating output including writing output to the browser window or browser console, displaying output in dialog boxes, writing output into an HTML element, etc. Writing into an HTML element, using innerHTML. Writing into the HTML output using document.write(). Writing into an alert box, using window.alert(). Writing into the browser console, using console.log(). JavaScript generating Output 1. Using innerHTML To access an HTML element, JavaScript can use the document.getElementById(id) method. The id attribute defines the HTML element. The innerHTML property defines the HTML content: Example: document.getElementById("demo").innerHTML = 5 + 6; JavaScript generating Output 2. Using document.write( ): You can use the document.write() method to write the content to the current document only while that document is being parsed. Example: // Printing a simple text message document.write("Hello World!"); // Prints: Hello World! // Printing a variable value var x = 10; var y = 20; var sum = x + y; document.write(sum); // Prints: 30 JavaScript generating Output 3. Using alert ( ): You can also use alert dialog boxes to display the message or output data to the user. An alert dialog box is created using the alert( ) method. Example: // Displaying a simple text message alert("Hello World!"); // Outputs: Hello World! // Displaying a variable value var x = 10; var y = 20; var sum = x + y; alert(sum); // Outputs: 30 JavaScript generating Output 3. Using console.log() For debugging purposes, you can call the console.log() method in the browser to display data. Example: // Printing a simple text message console.log("Hello World!"); // Prints: Hello World! // Printing a variable value var x = 10; var y = 20; var sum = x + y; console.log(sum); // Prints: 30 Data Types in JavaScript Data types basically specify what kind of data can be stored and manipulated within a program. 1. String 2. Number 3. Boolean 4. Array 5. Undefined 6. Null 7. Object 8. Function Data Types in JavaScript 1. String: - The string data type is used to represent textual data (i.e. sequences of characters). - Strings are created using single or double quotes surrounding one or more characters Example: var a = 'Hi there!'; // using single quotes var b = "Hi there!"; // using double quotes Data Types in JavaScript 1. String: Example: var a = "Let's have a cup of coffee."; // single quote inside double quotes var b = 'He said "Hello" and left.'; // double quotes inside single quotes var c = 'We\'ll never give up.'; // escaping single quote with backslash Data Types in JavaScript 2. Number: The number data type is used to represent positive or negative numbers with or without decimal place, or numbers written using exponential notation. Example: var a = 25; // integer var b = 80.5; // floating-point number var c = 4.25e+6; // exponential notation, same as 4.25e6 or 4250000 var d = 4.25e-6; // exponential notation, same as 0.00000425 Data Types in JavaScript 3. Boolean: The Boolean data type can hold only two values: true or false. It is typically used to store values like yes (true) or no (false), on (true) or off (false) Example: var isReading = true; // yes, I'm reading var isSleeping = false; // no, I'm not sleeping OR var a = 2, b = 5, c = 10; alert(b > a) // Output: true alert(b > c) // Output: false Data Types in JavaScript 4. Undefined: The undefined data type can only have one value-the special value undefined. If a variable has been declared, but has not been assigned a value, has the value undefined. Example: var a; var b = "Hello World!" alert(a) // Output: undefined alert(b) // Output: Hello World! Data Types in JavaScript 5. NULL: A null value means that there is no value. It is not equivalent to an empty string ("") or 0, it is simply nothing. A variable can be explicitly emptied of its current contents by assigningit the null value. Example: var a = null; alert(a); // Output: null var b = "Hello World!" alert(b); // Output: Hello World! b = null; alert(b) // Output: null Data Types in JavaScript 6. Object: The object is a complex data type that allows you to store collections of data. An object contains properties, defined as a key-value pair. Example: var emptyObject = {}; var person = {"name": "ABC", "surname": "XYZ", "age": "36"}; // For better reading var car = { "modal": "BMW X3", "color": "white", "doors": 5 } Data Types in JavaScript 7. Array: The array index starts from 0, so that the first array element is arr not arr. The simplest way to create an array is by specifying the array elements as a comma-separated list enclosed by square brackets Example: var colors = ["Red", "Yellow", "Green", "Orange"]; var cities = ["London", "Paris", "New York"]; alert(colors); // Output: Red alert(cities); // Output: New York Data Types in JavaScript 8. Function: The function is callable object that executes a block of code. Since functions are objects, so it is possible to assign them to variables Example: var greeting = function() { return "Hello World!"; } // Check the type of greeting variable alert(typeof greeting) // Output: function alert(greeting()); // Output: Hello World! Operators in JavaScript var x = 10; var y = 4; alert(x + y); // Outputs: 14 alert(x - y); // Outputs: 6 alert(x * y); // Outputs: 40 alert(x / y); // Outputs: 2.5 alert(x % y); // Outputs: 2 JavaScript Assignment operators JavaScript Assignment operators var x; // Declaring Variable x = 10; alert(x); // Outputs: 10 x = 20; x += 30; alert(x); // Outputs: 50 x = 50; x -= 20; alert(x); // Outputs: 30 x = 5; x *= 25; alert(x); // Outputs: 125 x = 50; x /= 10; alert(x); // Outputs: 5 x = 100; x %= 15; alert(x); // Outputs: 10 JavaScript String operators var str1 = "Hello"; var str2 = " World!"; alert(str1 + str2); // Outputs: Hello World! str1 += str2; alert(str1); // Outputs: Hello World! JavaScript Increment & Decrement operators JavaScript Logical operators JavaScript Comparison operators JavaScript async and defer attribute When the browser loads HTML and comes across a... tag, it can’t continue building the DOM. It must execute the script right now. The same happens for external scripts : the browser must wait for the script to download, execute the downloaded script, and only then can it process the rest of the page. That leads to two important issues: Scripts can’t see DOM elements below them, so they can’t add handlers etc. If there’s a bulky script at the top of the page, it “blocks the page”. Users can’t see the page content till it downloads and runs: JavaScript async and defer attribute defer The defer attribute tells the browser not to wait for the script. Instead, the browser will continue to process the HTML, build DOM. The script loads “in the background”, and then runs when the DOM is fully built. Here’s the same example as above, but with defer:...content before script......content after script... Scripts with defer never block the page. Scripts with defer always execute when the DOM is ready (but before DOMContentLoaded event). JavaScript async and defer attribute async The async attribute is somewhat like defer. It also makes the script non-blocking. But it has important differences in the behavior. The async attribute means that a script is completely independent: The browser doesn’t block on async scripts (like defer). Other scripts don’t wait for async scripts, and async scripts don’t wait for them. DOMContentLoaded and async scripts don’t wait for each other: DOMContentLoaded may happen both before an async script (if an async script finishes loading after the page is complete) …or after an async script (if an async script is short or was in HTTP-cache) JavaScript async and defer attribute async Example:...content before scripts... document.addEventListener('DOMContentLoaded', () => alert("DOM ready!"));...content after scripts... JavaScript Functions A function is a group of statements that perform specific tasks and can be kept and maintained separately from main program. Functions reduces the repetition of code within a program — Function allows you to extract commonly used block of code into a single component. Functions makes the code much easier to maintain — Since a function created once can be used many times, so any changes made inside a function automatically implemented at all the places without touching the several files. Functions makes it easier to eliminate the errors — When the program is subdivided into functions, if any error occur you know exactly what function causing the error and where to find it. Therefore, fixing errors becomes much easier. JavaScript Functions Defining and Calling a Function The declaration of a function start with the function keyword, followed by the name of the function you want to create, followed by parentheses i.e. () and finally place your function's code between curly brackets {}. function functionName( ) { // Code to be executed } Once a function is defined it can be called (invoked) from anywhere in the document, by typing its name followed by a set of parentheses. JavaScript Functions Adding Parameters to Functions You can specify parameters when you define your function to accept input values at run time. The parameters work like placeholder variables within a function; they're replaced at run time by the values (known as argument) provided to the function at the time of invocation. function functionName(parameter1, parameter2, parameter3) { // Code to be executed } However for each parameter you specify, a corresponding argument needs to be passed to the function when it is called, otherwise its value becomes undefined. JavaScript Functions JavaScript Return Value You can also create JS functions that return values. Inside the function, you need to use the keyword "return" followed by the value to be returned. function functionname(arg1, arg2) { lines of code to be executed return val1; } JavaScript Functions Working with Function Expressions Once function expression has been stored in a variable, the variable can be used as a function. // Function Declaration function getSum(num1, num2) { var total = num1 + num2; return total; } // Function Expression var getSum = function(num1, num2) { var total = num1 + num2; return total; }; JavaScript Functions Method Description apply() It is used to call a function contains this value and a single array of arguments. bind() It is used to create a new function. call() It is used to call a function contains this value and an argument list. toString() It returns the result in a form of a string. JavaScript Functions JavaScript Function apply() method Used to call a function contains this value and an argument contains elements of an array. Unlike call( ) method, it contains the single array of arguments. Syntax function.apply(thisArg, [array]) Parameter thisArg - It is optional. The this value is given for the call to a function. array - It is optional. It is an array-like object. Return Value It returns the result of the calling function along provided this value and arguments. JavaScript Functions JavaScript Function bind() method Used to create a new function. When a function is called, it has its own this keyword set to the provided value, with a given sequence of arguments. Syntax function.bind(thisArg [, arg1[, arg2[,...]]] Parameter thisArg - The this value passed to the target function. arg1,arg2,....,argn - It represents the arguments for the function. Return Value It returns the replica of the given function along provided this value and initial arguments. JavaScript Functions JavaScript Function call() method Used to call a function contains this value and an argument provided individually. Unlike apply() method, it accepts the argument list. Syntax function.call(thisArg, arg1,arg2,....,argn) Parameter thisArg - It is optional. The this value is given for the call to function. arg1,arg2,...,argn - It is optional. It represents the arguments for the function. Return Value It returns the result of the calling function along provided this value and arguments. JavaScript Functions JavaScript Function toString() method The JavaScript Function toString() method returns a string. Syntax function.toString() Return Value It returns a string. JavaScript Functions Working with Functions: Reverse a String With Built-In Functions The split( ) method splits a String object into an array of string by separating the string into sub strings. The reverse( ) method reverses an array in place. The first array element becomes the last and the last becomes the first. The join( ) method joins all elements of an array into a string. JavaScript String Interpolation String interpolation in JavaScript is a process in which an expression is inserted or placed in the string. To insert or embed this expression into the string a template literal is used. By using string interpolation in JavaScript, values like variables and mathematical expressions and calculations can also be added. Syntax The syntax of the string interpolation in JavaScript is as follows. `string where interpolation should be done enclosed in backticks: expression’ JavaScript String Interpolation const name="Abdul Rawoof" const company = "Tutorials Point" let salary = 18000 let increment = 2000 let mail = '[email protected]’ console.log(`Employee name is ${name} and the company is ${company} Salary of ${name} after increment is ${increment}:${salary+increment} Contact details of ${name} is ${mail}`) The console command has to be written for 3 times in the traditional way but when the backticks are used and the placeholders are used it is written in only one console. This decreases the code complexity and also the dynamic inputs can be used. JavaScript Anonymous Function It is a function that does not have any name associated with it. Normally we use the function keyword before the function name to define a function in JavaScript, however, in anonymous functions in JavaScript, we use only the function keyword without the function name. An anonymous function is not accessible after its initial creation, it can only be accessed by a variable it is stored in as a function as a value. An anonymous function can also have multiple arguments, but only one expression. JavaScript Anonymous Function function using the normal declaration: function() { // Function Body } We may also declare an anonymous function using the arrow function technique which is shown below: ( () => { // Function Body... } )(); Example: var greet = function () { console.log("Welcome to GeeksforGeeks!"); }; greet(); JavaScript Anonymous Function Example: We define an anonymous function that prints a message to the console. var greet = function () { console.log("Welcome to JavaScript!"); }; greet(); Below we pass arguments to the anonymous function. var greet = function (platform) { console.log("Welcome to ", platform); }; greet(“JavaScript!"); JavaScript Loops Loops are useful when you have to execute the same lines of code repeatedly, for a specific number of times or as long as a specific condition is true There are mainly four types of loops in JavaScript. 1. for loop 2. For - in a loop 3. while loop 4. do…while loop JavaScript Loops 1. for loop The for loop repeats a block of code as long as a certain condition is met. It is typically used to execute a block of code for certain number of times. Its syntax is: for(initialization; condition; increment) { // Code to be executed } JavaScript Loops 1. for loop The parameters of the for loop statement have following meanings: initialization — it is used to initialize the counter variables, and evaluated once unconditionally before the first execution of the body of the loop. condition — it is evaluated at the beginning of each iteration. If it evaluates to true, the loop statements execute. If it evaluates to false, the execution of the loop ends. increment — it updates the loop counter with a new value each time the loop runs. JavaScript Loops 2. for – in loop The for-in loop is a special type of a loop that iterates over the propertiesof an object, or the elements of an array. The generic syntax of the for-in loop is: for(variable in object) { // Code to be executed } The loop counter i.e. variable in the for-in loop is a string, not a number. It contains the name of current property or the index of the current array element. JavaScript Loops 3. While loop This is the simplest looping statement provided by JavaScript. The while loop loops through a block of code as long as the specified condition evaluates to true. As soon as the condition fails, the loop is stopped. The generic syntax of the while loop is: while(condition) { // Code to be executed } JavaScript Loops 4. Do - While loop The do-while loop is a variant of the while loop, which evaluates the condition at the end of each loop iteration. With a do-while loop the block of code executed once, and then the condition is evaluated, if the condition is true, the statement is repeated as long as the specified condition evaluated to is true. The generic syntax of the do-while loop is: do { // Code to be executed } while(condition); JavaScript Conditional Statements Conditional statements are used to decide the flow of execution based on different conditions. If a condition is true, you can perform one action and if the conditionis false, you can perform another action. The if statement The if...else statement The if...else if....else statement The switch...case statement JavaScript Conditional Statements The if statement The if statement is used to execute a block of code only if the specified condition evaluates to true. This is the simplest JavaScript's conditional statements and can be written like: if(condition) { // Code to be executed } JavaScript Conditional Statements The if statement Example: var now = new Date(); var dayOfWeek = now.getDay(); // Sunday - Saturday : 0 - 6 if(dayOfWeek == 5) { alert("Have a nice weekend!"); } JavaScript Conditional Statements The if...else statement The if...else statement allows you to execute one block of code if the specified condition is evaluates to true and another block of code if it is evaluates to false. It can be written, like this: if(condition) { // Code to be executed if condition is true } else { // Code to be executed if condition is false } JavaScript Conditional Statements The if...else statement Example: var now = new Date(); var dayOfWeek = now.getDay(); // Sunday - Saturday : 0 - 6 if(dayOfWeek == 5) { alert("Have a nice weekend!"); } else { alert("Have a nice day!"); } JavaScript Conditional Statements The if...else if....else statement The if...else if...else a special statement that is used to combine multiple if...else statements. if(condition1) { // Code to be executed if condition1 is true } else if(condition2) { // Code to be executed if the condition1 is false and condition2 is true } else { // Code to be executed if both condition1 and condition2 are false } JavaScript Conditional Statements The if...else if....else statement Example: var now = new Date(); var dayOfWeek = now.getDay(); // Sunday - Saturday : 0 - 6 if(dayOfWeek == 5) { alert("Have a nice weekend!"); } else if(dayOfWeek == 0) { alert("Have a nice Sunday!"); } Else { alert("Have a nice day!"); } JavaScript Conditional Statements The switch...case statement The switch...case statement tests a variable or expression against a series of values until it finds a match, and then executes the block of code corresponding to that match. It's syntax is: switch(x) { case value1: // Code to be executed if x === value1 break; case value2: // Code to be executed if x === value2 break;... default: // Code to be executed if x is different from all values } JavaScript Conditional Statements The switch...case statement Example: var d = new Date(); switch(d.getDay()) { case 0: alert("Today is Sunday."); break; case 1: alert("Today is Monday."); break;..... default: alert("No information available for that day."); break; } JavaScript block Statements A block statement groups zero or more statements. In languages other than JavaScript, it is known as a compound statement. Syntax { //List of statements } Variables with a block get scoped to the containing function. Block statement never introduce scope and using var to declare variables don’t have block scope. JavaScript block Statements var a = 20; { var b = 40; } Now, when you will print the value of a, it will print 40, not 20. This is because variable declared with a var within the block has the same scope like var before the block. var a = 20; { var a = 40; } // this prints 40 document.write(a); JavaScript break Statements You have already seen the break statement used in an earlier chapter of this tutorial. It was used to "jump out" of a switch() statement. The break statement can also be used to jump out of a loop: Example for (let i = 0; i < 10; i++) { if (i === 3) { break; } text += "The number is " + i + ""; } In the example above, the break statement ends the loop ("breaks" the loop) when the loop counter (i) is 3. JavaScript Objects Many times, variables or arrays are not sufficient to simulate real-life situations. JavaScript allows you to create objects that act like real life objects. You can create properties and methods to your objects to make programming easier. If your object is a student, it will have properties like first name, last name, id etc and methods like calculateRank, changeAddress etc. JavaScript Objects Creating Objects: An object can be created with curly brackets {} with an optional list of properties. A property is a "key: value" pair, where the key (or property name) is always a string, and value (or property value) can be any data type, like strings, numbers, Booleans or complex data type like arrays, functions, and other objects. var objName = new Object(); objName.property1 = value1; objName.property2 = value2; objName.method1 = function() { line of code } OR var objName= {property1:value1, property2:value2, method1: function() { lines of code} }; JavaScript Objects Access Object Properties and Methods You can access properties of an object like this: objectname.propertyname; You can access methods of an object like this: objectname.methodname(); JavaScript Objects Access Object Properties and Methods To access or get the value of a property, you can use the dot (.), or square bracket ([ ]) notation. var book = { "name": “C Programming", "author": “Kanetkar", "year": 2000 }; // Dot notation document.write(book.author); // Prints: Kanetkar // Bracket notation document.write(book["year"]); // Prints: 2000 JavaScript Objects Looping Through Object's Properties You can iterate through the key-value pairs of an object using the for...in loop. This loop is specially optimized for iterating over object's properties. Example: var person = { name: "Peter", age: 28, gender: "Male" }; // Iterating over object properties for(var i in person) { document.write(person[i] + ""); // Prints: name, age and gender } JavaScript Objects Setting Object's Properties var person = { name: "Peter", age: 28, gender: "Male" }; // Setting a new property person.country = "United States"; document.write(person.country); // Prints: United States person["email"] = "[email protected]"; document.write(person.email); // Prints: [email protected] // Updating existing property person.age = 30; document.write(person.age); // Prints: 30 person["name"] = "Peter Parker"; document.write(person.name); // Prints: Peter Parker JavaScript Objects Deleting Object's Properties The delete operator can be used to completely remove properties from an object. Deleting is the only way to actually remove a property from an object. Setting the property to undefined or null only changes the value of the property. It does not remove property from the object. var person = { name: "Peter", age: 28, gender: "Male", displayName: function() { alert(this.name); } }; // Deleting property delete person.age; alert(person.age); // Outputs: undefined JavaScript Objects Calling Object's Methods You can access an object's method the same way as you would access properties—using the dot notation or using the square bracketnotation. var person = { name: "Peter", age: 28, gender: "Male", displayName: function() { alert(this.name); } }; person.displayName( ); // Outputs: Peter person["displayName"]( ); // Outputs: Peter JavaScript Properties: Properties are the values associated with a JavaScript object. A JavaScript object is a collection of unorderedproperties. Properties can usually be changed, added, and deleted, but some are read only. Accessing JavaScript Properties The syntax for accessing the property of an object is: objectName.property // person.age or objectName["property"] // person["age"] or objectName[expression] // x = "age"; person[x] Deleting Properties The delete keyword deletes a property from an object: Example var person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"}; delete person.age; // or delete person["age"]; The delete keyword deletes both the value of the property and the property itself. After deletion, the property cannot be used before it is added back again. The delete operator is designed to be used on object properties. It has no effecton variables or functions. The delete operator should not be used on predefined JavaScript object properties. It can crash your application. JavaScript Date Object The JavaScript date object can be used to get year, month and day. You can display a timer on the webpage by the help of JavaScript date object. You can use different Date constructors to create date object. It provides methods to get and set day, month, year, hour, minute and seconds. Constructor You can use 4 variant of Date constructor to create date object. Date() Date(milliseconds) Date(dateString) Date(year, month, day, hours, minutes, seconds, milliseconds) JavaScript Date Object JavaScript Date Object JavaScript Date Object Current Time: var today=new Date(); var h=today.getHours(); var m=today.getMinutes(); var s=today.getSeconds(); document.getElementById('txt').innerHTML=h+":"+m+":"+s; JavaScript Callbacks A callback function can be defined as a function passed into another function as a parameter. Callbacks are mainly used to handle the asynchronous operations such as the registering event listeners, fetching or inserting some data into/from the file, and many more. If we want to execute a function right after the return of some other function, then callbacks can be used. JavaScript Callbacks Using a callback, you could call the calculator function (myCalculator) with a callback (myCallback), and let the calculator function run the callback after the calculation is finished: function myDisplayer(some) { document.getElementById("demo").innerHTML = some; } function myCalculator(num1, num2, myCallback) { let sum = num1 + num2; myCallback(sum); } myCalculator(5, 5, myDisplayer); JSON JSON: JavaScript Object Notation. JSON is a syntax for storing and exchanging data. JSON is text, written with JavaScript object notation. Exchanging Data When exchanging data between a browser and a server, the data can only be text. JSON is text, and we can convert any JavaScript object into JSON, and send JSON to the server. We can also convert any JSON received from the server into JavaScript objects. This way we can work with the data as JavaScript objects, with no complicated parsing and translations. Why use JSON? Since the JSON format is text only, it can easily be sent to and from a server, and used as a data format by any programming language. JavaScript has a built in function to convert a string, written in JSON format, into native JavaScript objects: JSON.parse( ) So, if you receive data from a server, in JSON format, you can use it like any other JavaScript object. JSON Objects JSON objects are written inside curly braces. Just like in JavaScript, objects can contain multiple name/value pairs: {"firstName":"Arati", "lastName":"Dev"} JSON Arrays JSON arrays are written inside square brackets. Just like in JavaScript, an array can contain objects: "employees": [ {"firstName":"Mangesh", "lastName":"Bhat"}, {"firstName":"Anamika", "lastName":"Patil"}, ] The object "employees" is an array. It contains three objects. Each object is a record of a person (with a first name and a last name) Converting a JSON Text to a JavaScript Object A common use of JSON is to read data from a web server, and display the data in a web page. First, create a JavaScript string containing JSON syntax: var text = '{ "employees" : [' + '{ " firstName":"Mangesh", "lastName":"Bhat " },' + '{ " firstName":"Anamika", "lastName":"Patil " },' + '{ "firstName":"James" , "lastName":"Jones" } ]}'; Then, use the JavaScript built-in function JSON.parse( ) to convert the string into a JavaScript object: var obj = JSON.parse(text); Finally, use the new JavaScript object in your page. Converting a JSON Text to a JavaScript Object var text = '{"employees":[' + '{ " firstName":"Mangesh", "lastName":"Bhat " },' + '{ " firstName":"Anamika", "lastName":"Patil " },' + '{ "firstName":"James" , "lastName":"Jones" } ]}'; obj = JSON.parse(text); document.getElementById("demo").innerHTML = obj.employees.firstName + " " + obj.employees.lastName; JSON.parse ( ) Parsing JSON Data in JavaScript When receiving data from a web server, the data is always a string. Parse the data with JSON.parse(), and the data becomes a JavaScript object. Example - Parsing JSON Imagine we received this text from a web server:. '{ "name":"John", "age":30, "city":"New York"}' Use the JavaScript function JSON.parse() to convert text into a JavaScript object: var obj = JSON.parse('{ "name":"John", "age":30, "city":"NewYork"}'); JSON Parsing JSON Data in JavaScript var txt = '{"name":"John", "age":30, "city":"NewYork"}‘ var obj = JSON.parse(txt); document.getElementById("demo").innerHTML = obj.name + ", " + obj.age; Parsing Functions Functions are not allowed in JSON. If you need to include a function, write it as a string. You can convert it back into a function later. Example: var text = '{ "name":"John", "age":"function ( ) {return 30;}", "city":"NewYork"}'; var obj = JSON.parse(text); obj.age = eval("(" + obj.age + ")"); document.getElementById("demo").innerHTML = obj.name + ", " + obj.age( ); Parsing Functions In JSON, functions are not allowed as object values. The JSON.stringify() function will remove any functions from a JavaScript object, both the key and the value: Example var obj = { name: "John", age: function ( ) {return 30;}, city: "NewYork"}; var myJSON = JSON.stringify(obj); document.getElementById("demo").innerHTML = myJSON; Parsing Functions This can be omitted if you convert your functions into strings before running the JSON.stringify() function. Example var obj = { name: "John", age: function () {return 30;}, city: "New York"}; obj.age = obj.age.toString( ); var myJSON = JSON.stringify(obj); document.getElementById("demo").innerHTML = myJSON; JSON.stringify( ) Parsing JSON Data in JavaScript When sending data to a web server, the data has to be a string. Convert a JavaScript object into a string with JSON.stringify(). Imagine we have this object in JavaScript: var obj = { name: "John", age: 30, city: "New York"}; Use the JavaScript function JSON.stringify() to convert it into a string. var myJSON = JSON.stringify(obj); JSON.stringify( ) Parsing JSON Data in JavaScript myJSON is now a string, and ready to be sent to a server: var obj = { name: "John", age: 30, city: "New York"}; var myJSON = JSON.stringify(obj); document.getElementById("demo").innerHTML = myJSON; JSON Sending Data If you have data stored in a JavaScript object, you can convert the object into JSON, and send it to a server: Example var myObj = {name: "John", age: 31, city: "New York"}; var myJSON = JSON.stringify(myObj); window.location = "demo_json.php?x=" + myJSON; JSON Receiving Data If you receive data in JSON format, you can convert it into a JavaScript object: Example var myJSON = '{"name":"John", "age":31, "city":"New York"}'; var myObj = JSON.parse(myJSON); document.getElementById("demo").innerHTML = myObj.name; JSON Storing Data When storing data, the data has to be a certain format, and regardless of where you choose to store it, text is always one of the legal formats. JSON makes it possible to store JavaScript objects as text. Example Storing data in local storage // Storing data: myObj = {name: "John", age: 31, city: "New York"}; myJSON = JSON.stringify(myObj); localStorage.setItem("testJSON", myJSON); // Retrieving data: text = localStorage.getItem("testJSON"); obj = JSON.parse(text); document.getElementById("demo").innerHTML = obj.name; JSON Values In JSON, values must be one of the following data types: - a string - a number - an object (JSON object) - an array - a boolean - Null In JavaScript values can be all of the above, plus any other valid JavaScript expression, including: - a function - a date - undefined JSON vs XML Both JSON and XML can be used to receive data from a web server. The following JSON and XML examples both define an employees object, with an array of 3 employees: JSON Example {"employees": [ { "firstName":"BB", "lastName":"DD" }, { "firstName":"Aa", "lastName":"SS" }, { "firstName":"CC", "lastName":"JJ" } ] } JSON vs XML XML Example BB DD Aa SS CC JJ JSON vs XML XML is much more difficult to parse than JSON. JSON is parsed into a ready-to-use JavaScript object. Both JSON and XML are "self describing" (human readable) Both JSON and XML are hierarchical (values within values) Both JSON and XML can be parsed and used by lots of programming languages Both JSON and XML can be fetched with an XMLHttpRequest

Use Quizgecko on...
Browser
Browser