0% found this document useful (0 votes)
5 views

JS Unit1

java script unit 1

Uploaded by

vivekkarche18
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
5 views

JS Unit1

java script unit 1

Uploaded by

vivekkarche18
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 30
Introduction to Java Scripts Introduction ~ First Look at Javaseript, ‘Adding JavaScript to XHTML Documents- The : 3 : .
Examplect Linked rts x ig B tier spranicsharsremt is value sa URL-path to the itisin ss tn ee os aaa technologies. So in this: function alertMsg() Scanned with CamScanner ‘Scanned with CamScanner ‘Scanned with CamScanner ‘Scanned with CamScanner . > JavaScript is everywhere, and-for the seventh year in a row ft ranks as the most used progr ‘with 67.8% of developers using it in 2019, Its rise to the most popular programming language in the > ‘synonymous with the rise of the Internet itself ; eee It was created out of necessity and is used today studing some o s ar ly to create 95.2% (1.52 billion) ‘of websites, incl > ‘world’s largest such as Facebook and YouTube, Without it, we wouldn't have popular and wseful mel i > > > > , Google Maps and eBay. So without further ado, let's take a look at what JavaScript is, the language, JavaScript Origins how and why it was created, and what's next for - } Netscape Navigator 9 2 Veto 2.02 peer ; ‘Cams 9 198t-1975 Nenzage Communit Comet, Alissa Be swannaiiteinn gant teh aes Tan raterohavar nee E ; NETSCAPE , j sas Yr ateatUepedySe deren lpr © aes dueateroae oe Mop Bes , BagRSA Seema totfan Dossier : 7 ses : barn se sen mets ca cf rk Sovarhe isonet ee ec mas tea J aR ay Z i indie Sans y ; © The early to mid-1990s was an important time for the internet. Key players like Netscape and Microsoft were in the midst of browser wars, with Netscape’s Navigator and Microsoft’ Internet Explorer going head to head. } © In September 1995, a Netscape programmer named Brandan Bich developed a new scripting language in just ; 10 days. It was originally named Mocha, but quickly became known as LiveScript and, later, JavaScript. ; 1.4 JavaScript Core Features w : 1.4.1 Overview : What is JavaScript? ae «JavaScript is a dynamic computer programming language. It Is lightweight and most commonly used a ‘web pages whose implementations allow client-side script to interact with the user and create dynamic ted programming ap i ante Scanned with CamScanner Inteodction lying JavaScript language, JavaScript is lightweight, interpreted programming language, Designed for building network oriented applications © Complementary and integrated with ava ‘Complementary and integrated with HTML, © Open and cross-platform, Client-side JavaScript ° SAGAE sae evaScriptis the most common form af the language, The crip shouldbe pat of or referenced inthe jocumentin order for the code to be interpreted by the browser. ‘This means that a web page may not be static HTML, but may contain programs that interact with the user, control the browser, and dynamically create HTML content. ‘The client-side javaScript mechanism provides many advantages over traditional server-side CGI scripts. For ‘example, you can use JavaScript to check whether a user has entered a valid email address ina form field. ‘The aes ‘code is executed when the user submits the form, and only ifall the entries are valid will they be sent to the web server. + JavaScript can be used to capture user-initiated events such as button clicks, link navigations, and other actions that are explicitly or implicitly triggered by the user. Advantages of JavaScript : Advantages of using JavaScript are: ‘+ Less interaction with the server : You can validate user Input before sending the page to the server. This saves server traffic, which means fewer loads on your server, + Instant feedback for visitors : They don’thave to wait for a page reload to see if they forgot to enter something. + Increased interactivity : You can create interfaces that respond when the user hovers over them with the ‘mouse or activates them with the keyboard. + Richer Interface ; Using JavaScript, you can include items such as drag-and-drop components and sliders to provide a rich interface to your site visitors. JavaScript limitations : ‘We cannot treat favaScript asa full-fledged programming language It lacks the following important features: «Client-side JavaScript does not allow Mes tobe read oF written. This has been retained for security reasons. «JavaScript cannot be used for network applications because such suppart is not avalabe. + JavaSeripchas no multithreading or multiprocessor capabilities, 1.4.1(A) JavaScript Development Tools of Javascripts that it does not require expensive development tools. You can start Gne of the main advantages i dont na eee - ith a simple text editor like Notepad, Because its an interpreted language Scanned with CamScanner Macromedia Dreamweaver MX : Mactomedia Dreamweaver MX is a ‘very popular | caltor among professional web application developers. It provides several SomPonents, integrates well with databases, and conforms to new standards Macromedia Homesites : Homesites is Macroms ‘used to efficiently manage personal websites. ° 1.4.2 Basic Definition JavaScript (8) 1s a scripting language primarily used on the web, It is used to Commonly found embedded in HTML code. JavaScript is an interpreted language, JavaScript renders web pages in an interactive and dynamic way. This allows Special effects, receive variable text, validat enhance HTML pages and is So It Is not necessary to compile it. Pages to respond to events, display © data, create cookies, detect the user's browser, etc. 14.3 Language Characteristics ) JavaScript is a simple language designed to be interpreted at runtime Ith s a vaguely C-shaped syntax (except for pointer arithmetic); a straightforward clas: sless object model, said tobe inspired by a ltle-known programming 4 language called self; automatic waste collection; and ‘weak, dynamle writing. As such, JavaScript has no built-in 1/0 | mechanisms. In the browser, poor communicatio "capabilities with the host environment are offered through a set of Predefined methods and properties that map to native code inside the browser, but unlike what ‘can be seen in many other programming languages, these interfaces are fairly limited and purpose-built. JavaScript is a client-side fechnology, basically tis used for client-side authentication, but Ithas many features which ae listed helow JavaScript is an object-based scripting language, ~ JavaScript gives the user better control over the browser. ) * Identifies the user's browser and operating systetn, + Itisa scripting language and not Java. + JavaSctipt is an interpreter-based scripting language, * _ JavaScriptis case sensitive. ‘+ It isan object-oriented language because it provides predefined objects + Every command in JavaScript must end with a semicolon (). A significant part of JavaScript is the ability to generate new functions within scripts. Declare a function in JavaScript using the function keyword. JavaScript Is one of the most popular languages that contaln many features when it comes to development is among the top programming languages according to Gib and we Beta wo the features of JavaScript to understand whatiit is capable of er ? 3 p * — Most of the JavaScript control syntax is the'same as the C control syntax. ; ) Scanned with CamScanner 2. Light Weight Scripting Language JavaScript is a lightweight scripting language because its made for data handling at the browser only. Since itis ‘Rota general-purpose language it has a limited set of libraries, Also as It (s only meant for client-side execution and that too for web applications, hence the lightweight nature of JavaScript is a great feature. 2. Dynamic Typing ‘ ‘ JavaScript supports dynamic typing which means types.of the variable are defined based on the stored value. For example, if you declare a variable x then you can store either a string or a Number type value oF ail array or ah object. This is known as dynamaic typing. + To understand this, in languages like Java, we explicitly mention that « particular variable will store 2 certain type of data, whereas in JavaScript we do not have to provide, the data type while declaring 2 variable. In JavaScript, we just have to use var or let keyword hefore the variable name to declare a variable ‘without worrying about its type. 3. Object-Oriented Programming Support Starting from ES6, the concept of class and OOPs has been more refined. Also, in JavaScript. two important principles with OOP in JavaScript are Object Creation patterns (Encapsulation) and Code Reuse patterns (Inheritance). Although JavaScript developers rarely use this feature but it's for everyone to explore. 4. Functional Style This implies that JavaScript uses a functional approach, even objects are created from the constructor functions and each constructor function represents a unique object-type. Also, functions in JavaScript.can be used as - objects and can be passed to other functions too. i 5. Platform Independent ‘This implies that JavaScript is platform-independent or we can say it is portable; which simply means that you can simply write the script once and run it anywhere and anytime, In general, you can write your JavaSeript applications and run them on any platform or any browser without affecting the output of the Script 6. Prototype-based Language JavaScript Is a prototype-based scripting Language. This means JavaScript uses prototypes instead of classes or inheritance, In languages like Java, we create a class and then we create objects for those classes. But in JavaScript, wedefine object prototype and then more objects can be created using this object prototype. Interpreted Language Scanned with CamScanner ‘Scanned with CamScanner ‘Scanned with CamScanner ‘Scanned with CamScanner var obji = (‘cat 'playfui' Java Introduction to Java Seripts i j © dd Vone’, Wo ‘ehree, four, Objects are not compared by value. This means that even if two objects have the same properties and values, ‘hey are not strictly equal. Same goes for arrays. Even if they have the same elements that are n the same order, they are not strictly equal var obj2= {cat’:'playfal}, | Obl sss0bj2; //false | ek vararra=[1,2,3,4,5};, | vararr2=[1,2,3,4,5]: } arrl = arr2; //false | var obj3 = (‘car'{ purple’) Var obj4 = 0bj3; obj3 === obj; //true Ja aa «An array Is an ordered set of values'grouped under a single identifier. There are many ways to create an =~ Non primitive values can also be referred to as reference types because they are being compared by reference Instead of value. Two objects are only strictly equal if they refer to the same underlying object You can check if two objects are the same by doing a deep equals comparison to go through each of the properties to determine if two objects have the exact same properties. Unlike primitive types such as numbers and strings, composite types are composed of heterogeneous data as a single unit. A composite type can contain not only strings, numbers, Booleans, undefined values, and null values, but even other composite types. JavaScrpt supports three composite types: bjects, arrays, and functions, {Script non-primitive (Composite types) data type The non-primitive data types are as follows : i Datatype | Description Object "| Represents instance through Which we can access members | Array —_| Represents group of similar values RegExp _| Represents regular expression i ‘We will have great discussion on eachdata type! & + f 4 6 ; € e © Se € © € é € ¢€ ¢ € ¢ » é € ¢ ‘ array, but the easiest is to define it as a standard parentheses, ‘+ Another way to syntactically define arrays that recognize their inheritance as objects Is to use the new Keyword to invoke the constructor of an Array object, as shown her This defines myArray as an array with no specific length ‘+ We could easily predetermine the length ofan array by passing ita single numeric value. For example, ‘var myArray = new Array(4); 4 ¢ aes ‘defines an array of length 4 7 tale ot We can even populate fel using explicit constructor-style syntax as shown here: var myArray = new Array(1,5,"Thomas’, trie); + Regardless of how they are defined, array elements are accessed in the same way. To refer to a specific part ofan array, we need to énter the index value in square brackets. var myArray = new Array(1,5,"Thomas”, true); “var x= myArray[2]; vary = myArray[0]; * The value of x would be the string “Thomas” and y would be set to the number 1. This is because fiekds in JavaScript are indexed from 0. The following script shows both the definition of the field and the assignment using the index value. var myArray = new Array(4); myArray[0] myArray[1] = 5: myArray(2]= "Thomas"; myArray[3] = true; «s+ Asstated briefly, arrays are actially objects and have a number of properties and methods that can be used ; ‘to manipulate them. These functions will be discussed in detail in Chapter 3. But first, let's take a brief look at objects in JavaScript. Objects ) + Objects can hold any type of data and are the primary mechanism by which useful asks are performed. The browser provides a large number of objects that you can use. For example, you can interact with the user y using a Window objector edit the content of a web page using a Document object. : , +The data contained in an object are considered properties of the object. Properties are accessed wing the dot operator, which s simply a dot followed by the property name. The syntax ie ae object.nameproperty.name . scierrenre teat ws he maid reper of the Document Java Seript (SPU) 1-18 Introduction to Java Scripts * You'll notice that when using objects, the identifier length needed to access a particular property can be uite long, For example, writing documentwrite can be tedious, as can accessing even more deeply nested sub-objects, By using with keyword, we can avoid referring to the full path to an object's property or method: - * In addition to using built-in objects such as Document or Window, you can create your own objects using the new keyword, The use of new was briefly demonstrated in the field examples in the previous section. You-can also destroy a property or element in an array using the delete keyword. For example, here we define an array element and then quickly destroy it. var myArray= new Array(4); = myArray[0}="Thomas' delete myarray(0}; * At its core, JavaScript is an object-oriented language, and everything is derived from various objects provided by the language or browser. For example, JavaScript provides objects corresponding to primitive data types such as String, Number, and Boolean, which have methods for working with the respective data ‘pes. + There are also more complex data-related objects such as Array, Math; and Date, as well as browser- ‘oriented objects such as Navigator and History and the powerful Document object. + There is even a generic object that we can use to bulld our own objects 1.6 _ Flow Control Statements + Im this article, we will earn about conditional statement (Le. if-else statement) in JavaScript along with understanding tts implementation through examples. A conditional statement performs some action for a specific condition. Ifthe condition is met, the specific action block will be executed-otherwise, the next action block that meets that specific condition will be executed. Decision making in programming is similar to decision making in real life. In programming we also face some situations where we want a certain block of code to be executed when some condition is met. A programming language uses control statements to control the flow of program execution based on certain conditions. These are used to allow the flow of execution to advance and branch based on program state changes. Conditional JavaScript statements : 1 if 2. ielse 3. nested-ifelse 4. else ifladder ‘We will understand each conditional statement, its syntax, flowchart and examples. To understand the switch ‘case, read the article Switch Case in JavaScript, Let's start with ifstatement. : if statement : The if statement is the simplest decision making statement. It is used to decide whether a certain. statement or block of statements will be executed or not ie. if a certain condition is met then the block of statement will be executed otherwise not. Racing ere a Scanned with CamScanner MEEED 9 9 2 2 oa a a 2 a 2 2 hae 9 vy) Here the condition will be either true of false after evaluation. If statement accepts Boolean valuey ifthe va {s true, it executes the block of statements below it. If we don't provide the cain hee anh ‘f(condition), then the if statement will default to the statement immediately within its block, For example, = 11 Here ifthe condition is true, if block wil consider only statement1 to be inside its block. Flow chart : tne Halse = Body of it; 3 ——— Siatement just below.it. y Fig. 1.6.1 > — Example: This example describes the if-statement in JavaScript. J/ JavaScript program to illustrate If statement vari=10; if(> 15) { document. write("10 is less than 15"); // This statement will be executed } ‘//as ifconsiders one statement by default | Body ott] pe Siatemen joa below if Fig. 1.6.2 > Example: This example describes the if-else statement inJavaserpt. 2 Output: Hello Admin welcome to GeeksforGeeks : i si Return Statement : + There are some situations where we want to retin some values from a function after performing some operations, In such cases, we can use the return statement in JavaScript + “This is an optional statement and usually the last statement in a JavaScript function. Take é look at our first example with a function named caleAddttion. Tis function calculates two numbers and then returns the result ‘The most basic syntax for using the return statement is: return value; iin 3 pa: ‘The return statement begins with the keyword return separated by the value which we want to return We can use an expression also instead of directly returning the value, cereale a der for a computer program to do any useful work, it must be able to communicate with he ouside work a known as input/output or a + mo Scanned with CamScanner ‘Scanned with CamScanner Java Script (SPPU) bath Introduction to Java Scripts ‘ype "numeric™. Although the message wil stil be a ext string, defaultValue must be a numeric constant rather ‘than a text constant. Numeric input command : age= parseFloat(prompt("Enter your age’O)); 6 . Prompts the user to enter their age by displaying an on-screen numeric keypad prompting "Enter next to the input field. ‘i ei . * The number entered by the user will be stored in the age variable. Ifthe user does not enter a number, the age will be assigned a default value of zero. 1.10 _Regular Expressions A regular expression is a sequence of characters that forms a search pattern, The search pattern can be used for text search and text replacement operations. A regular expression can be a single character or a more complex Pattern. Regular expressions can be used to perform all types of search and replace text operations. Syntax : Jpattern/modifiers; Example: var pat = /GeeksforGeeks /i; 2 » i Explanation : /GeeksforGeeks/i is a regular expression. GeeksforGeeks is a pattern (to be used in a search). isa modifier (modifies the search to be Case-lnsensitive). 1.10.1 Regular Expression Modifiers Modifiers can be used to perform multiline searches : Examples : Expressions a Description, [abc] Find any of the character inside the brackets, 0-9) ' Find any of the digits between the brackets 0 to 9 . (ly) Find any of the alternatives between x or y separated with | Regular Expression Patterns : Metacharacters are characters with a special meaning: 3 Examples : Description Jeera Used to fn a whitespace character. 2 Scanned with CamScanner ‘Scanned with CamScanner

You might also like