[Go to site: main page, start]

0% found this document useful (0 votes)
2 views13 pages

Java Script Part 1

JavaScript is a lightweight, interpreted programming language essential for creating interactive web pages, running both client-side in browsers and server-side with Node.js. It includes key concepts such as variables, data types, operators, control statements, functions, arrays, and objects, along with methods for type conversion and event handling. The document serves as a comprehensive guide to understanding the fundamentals of JavaScript programming.

Uploaded by

nawobeb932
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
2 views13 pages

Java Script Part 1

JavaScript is a lightweight, interpreted programming language essential for creating interactive web pages, running both client-side in browsers and server-side with Node.js. It includes key concepts such as variables, data types, operators, control statements, functions, arrays, and objects, along with methods for type conversion and event handling. The document serves as a comprehensive guide to understanding the fundamentals of JavaScript programming.

Uploaded by

nawobeb932
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
JAVASCRIPT HANDWRITTEN NOTES Part 4 1. INTRODUCTION TO JAVASCRIPT © What is JavaScript ? > JavaScript is a lightweight, interpreted programming language used to make web pages interactive and dynamic. It is one of the core technologies of the web along with HTML and CSS. * Why JavaScript ? > It allows us to add behavior to web pages. It can update and change both HTML and CSS * Where does JavaScript run ? > In the Browser (Client-side) > On the Server using Node. js (Server-side) * Role of JavaScript in Web Development HTML css JavaScript fogether they Structure [>| Style and |——>| Behavior and idles eBlade of the page Design Interactivity OM oeee 2. HOW JAVASCRIPT WORKS ? User action JavaScript bon Changes. are (Click, Type, |—>] Code |] gta [>] visible on Scroll, ete.) Executes a the page Note : DOM (Document Object Model) is a representation of the HTML structure that JavaScript can access and manipulate. 3. YOUR FIRST JAVASCRIPT CODE © Example : Output in Console : Helle, JavaSeript | —> You can check the output by opening browser console 4. VARIABLES IN JAVASCRIPT Variables are used to store data values + Tn JavaScript, we can declare variables using var, let and const Example ver a = 10; var let const let b = 20; const ¢ = 305 + Function scoped | + Block scoped + Block scoped + Can be re-declared | + Cannot be + Cannot be a= 15; I allowed Can be updated | revdelared re-declared Tess Fr clsoed + Hoisted with | + Can be updated | + Cannot be updated = 35; // not allowed undefined. + Heised but in |» Must be initialised Temporal. Dead at the time of EL ze Zone (TDZ) declaration SE oleae instead of var 2. DATA TYPES IN JAVASCRIPT Data types are basically used to define the type of value a variable can hold Symbol (ESC) Data. Types Primitive (7) Non-Primitive / Reference : =a + Object «© Number oh Ore Spe + Undefined + Null BigInt (£52020) TYPEOF OPERATOR Example let name = “Aman”; I) String let age = 22; 11 Namber let Student = trues 11 Boolean let x; H Undefined let y = null; 11 Null let id = Symbol(‘id’); UL Symbol let big = 1234567890123456789012345678901234567840n; // BigInt let obj = {name "Aman"}; Uf Object let arr = (1, 2, 3]5 I Brrag function greet() MI Function typeof operator is used to find the type of a variable. Example console log (typeof “Aman”) console-log (typeof 22); console. log (typeof true); console-log (typeof null) ; console log (typeof Lt, 2, 3] console-log (typeof functionl 5H ang H rarber 7 boolean console log (typeof undefined); /f undefined H object console log (typeof frame: "Aman"}); // object 5M object YD; M1 function Note : ' | + typeof null returns “object” (this i a | known bug. in JavaScript) | 4 Arrays and Objects both return object" ' 4. OPERATORS IN JAVASCRIPT + Operators are used to perform operations on variables and values Types of Operators Type Description Arithmetic Used for mathematical, operations Assignment Used to assign values Comparison. Used to compare two values ae Logical Used to combine multiple conditions eeu Unary Used with a single operand Y= Ternary Shorthand if. else condition ? expel + expr2 Arithmetic Operators : | Example = + Addition | Wt a = 10, b=3 =__Siblrecfien’ | console..log(a +b) ; 33 + Multiplication | console. log(a ~ 6); Nt [maa | console-log(a * b); 1 30 % Modulus (remainder) 1 console. log(a / b); Hf 3.333. ++ Trerement ' yt ~~ Decrement t Wa t Wr Comparsion Operators : 1 Example ce fell 5 ! jis I= Not equal to sn - p | console H) false (type different) > Greater than { | console W true eee corel Whee Greater then or equal to ' . iets fees ae te Strict equal (value ond type) |“ | console. log(5 <= 4); se Strict nob equal (value and type) | Pe AY Hi $e Logical Operators : , Example : | Ternary Operator : 4B — Logical AND |} console-log(true && false); // false | condition 7 expri : expr? I] Logical OR | [Link](trus II false); // true | Example egies NOT! Gs econese Lara) ee) een Se let result = age >= 18 ? “Adult” : “Minor”; console. log (result); — // Adult 5. CONTROL STATEMENTS + These statements are used 42 control the flow of execution 2) if statement J (condition) { Ms code } 4) switch statement switch (variable) { case valued: MW code break; ease value2: MH code break; default: HW code b) if-else statement @) if-else if-else ladder if (condition) { F (conditions) { We code if true fh cxha. Poe } else if (condition?) { is MW code H cade if, false ae i W code } e) Loops saree Flow for Coin; lon rena amt) 3 ae False + while loop es Tohile Ceondition’) Mi Execute Code 3 + do. .while loop i eG Next Statement }e—J W eode } while Ceonsditign); 6. FUNCTIONS IN JAVASCRIPT + A function is a block of code designed to perform a particular task. + Function Declaration = Function Expression. © Arrow Function. faa palGaryT ‘console log ( “Hello, "+ name); } greet ("Amen"); // Function Call const greet» function console log ("Hell h greet ("Aman”); const greet = (name) => { console. log (Hello, "+ name); hb greet (“Aman”); Note : Functions help in code reusability and keep our code organized. 7. COMMENTS IN JAVASCRIPT I) This is a single line comment , This is a multi-line comment, ey Example conslelog(10); //- prints. 10 console: tog(20); /* prints 20 on two line comment */ console log(30); // prints 30 | 8. ARRAYS IN JAVASCRIPT + Array is a special type of object used to store multiple values in a single variable, Common. Array Methads + Index of on array starts from 0 + push) > adds element ak the ond Example * pop) > removes last element let fruits = [“Apple”, “Banana”, “Mango” ); © shift() removes first. element oO 1 2 # unshift() > adds element at the beginning index —> | Apple. Banana | Mango + Length > returns mumber of elements + indexOf() > returns index of element Accessing Elements Example + fruits[0] > Apple let feuits = ["Apple”, "Bonana”, "Mango"]; + fruits[1] > Banana fruits push (“Orange”) ; HH. Uhpple”, “Banana”, “Mango”, “Orange” ] + fruits(2] > Mango fruits. pop) a a consle. tog (fruts(4)); UW Banana 4. OBJECTS IN JAVASCRIPT + Object is a collection of key-value. pairs + Tk is used to store related data and more complex entities Example Lat person = { Aecessing Object Properties name: “Aman”, age: 22, city: “Dalni* + personage") > 22 + [Link] > Aman i + [Link] > Delhi 40. _TYPE_CONVERSION + TevaScript automatically converts one type into another Example cancle lg (person name) conde log ptr Za5e°1); lek person + { name: “Aman”, age: 22, city: "Delhi" }; W dman 22 # Tivo types : Implicit Conversion and Explicit Conversion Implicit Conversion (Automatic) + undefined +1 NoN (Not a Number) +2 =» "52" (string) to. 2 Ss 3 Coumber Y a stu tt > 2 (number) t sft > 4 (number) i valle {=> 1 —“‘Grambar) ! Explicit Comerson (Manual) String to Number : Number ("123") Number to Sting : String (123) Boson to String : String (true) Shing be Nanker + pareTab(“45") > 123 tas erate 45 porsefloak ("45,67") > 45.67 Example + lt a + "10"; 1 let b+ 20; console-Log (typeef a); Uy string —\—conacle. Log (typesf. String (b))5 M1 shing console. lag (typeof Number(a)); // number console tog (typeof (a+ b)); Using ("1020") 44. STRING METHODS + Strings ore used to represent and manipulate text Common String Methods Example Method Length. Returns length of the string tollpperCase() | Converts string to uppercase tolowerCase() | Converts string to lowercase trim() Removes uhitespace from both ends sice(start, end) | Extracts part of a string replace(old, new) | Replaces a value in string includes(value) | Checks if string contains value let mag = “Hello JavaScript”; console log (meg. Length) ; 46 console log ([Link]());,//) HELLO. JAVASCRIPT console og [Link]()); // hello javascript console: log (msg-trim()) j MH “Helle TavaSerigt console. log ([Link](6,10)); // Java. console. log ([Link]( "JavaScript", “J5")); // Hello JS concole log (msg. includes( Java"); // true 412. TEMPLATE + Template literals LITERALS. allow embedded expressions and multi-line strings Example ae rs i wis let age = 2: Hello, Aman ! eda i let meg = Use bocktick (*) instead Hello, ${name} ! giana ese single or double quotes You are $foge} years old console «log (msg) ; 43. CONDITIONAL (TERNARY) OPERATOR + Short hand if...else statement Use $£} to embed variables or expressions Example let age = 18; condition ? expression-if-true : expression if flee “Minor”; lek result = (age >= 48) ? “Adult” 44. EVENTS IN JAVASCRIPT + Events are actions or occurrences that happen in. the + TovaSeript can be used to handle these events Common Events console log (result); // Adult lick mouseover | [ mouseout eydoun, Occurs when | | Occurs when | | Ocers when | | Occurs when an elenent | | mouse printer | | mouse pointer| | a key is is licked. | | moves over. | | moves out presse, browser. Example (click event) document gAElenenBIA oa") edaGventistena(“ehick”, function() { aoe alert (“Button Clicked !"); Gear wn! | yy a form ie i snbmittel. | HTML + Click Me eee eee hahaa 15. DOM (DOCUMENT OBJECT MODEL) + DOM represents the structure of an HTML document as a. tree. + TovaScript can access ond update the content, structure and style of the page using the DOM Example: Accessing DOM Elements : Document + document getElementByld() > by id { + document. getElementsByClassName() > by class uu + document. getElementsByTagNamel) > by tag = + document .querySelector() > by ess. selector = cor + document .querySelectorAll() > all matching | Example: poe Ht ° Hello DOM¢/ka> My Page |

Welcomes /p> Hello This iso let ht = document. getElementByld (“title”); reste 16. EVENT HANDLING + Events are actions that eccur in the browser + We can respond to events using event listeners Uk p = document. getElementsByClassName( “text” (01; ht innerText = "Hello. JavaScript”; peimerText = “Welcome to JS"; Common Events Example (click event) Event. Description 123, 45.67 im ea 3. Boolean > true, false { Boole true fe 1 let person = { 4. Undefind > lat a ' © Amen” \ etter! 5. Null “ila = aly ' ; . ' ges 22 6. Symbl > lak # = Symbol ("id"); fait 7 Bigint > Lat m= 900729825474090%n; | | antl dng typeof person); Majo 20. TYPEOF OPERATOR + typeof operator is used to find the data type of «value eae Value typeof Value Rett | | Value typeof Vale Rent les [type “Halo? vag | | [mt ‘perf mal wake” Gc ad) 123 Uypeof 423 Sramber” | | [ Symbet(id") | typeaf SynbtC“at") | “ayntel” ms gee “tear | | [A000 ‘ypeef 4000 Fhgut™ wedafnd [typeof endafied[ “enefnd™ | | i} ‘aeentT object” 24, VARIABLES IN JAVASCRIPT ® Vrnln are snd to aoe data vlna, | 2: 000 Gd my) 1 2. at Goa sy) 13. cot Cotat) | + evaScript has 3 ways lo declare voriablas. | vor a * 10; ' \ ' webs; | ome 3; I function scoped. ! 1 ee wet | AP eh ig 22. VARIABLES + Variables are containers used to store data values + Rules for naming variables : Emer Valid Variables Tnvalid. Variables 4. Mast stark with a latter, $ or name name (darts with miner) 2, Cannot start with a number ame wcer-nama (contains -) 3. Con contain laters, numbers, $ and _ * ee 4. Care easitve (age and Age are differed) ti tes 5. Cannot be 0 JavaScript keyword. gel first. name (contains space) username @ralue (contains @) 23. ARITHMETIC OPERATORS. ee Example Operator Name Example | Result lb a= 10, b= 3; ¥ ‘Addition 343 8 [Link](a +b); i 13 console. log(a-b); M/F z te z 3 be si) e console. log(* b); 1/30 z HS plist | ac Ba [Link](a /b); — /f 3.333. Z Division to/2 | 5 console. log(a %b); — // 4 a Modulus tons | 4 atts ++ | neon [are | eet een ee = Decrement e-t console. log (b) ; wa 24. COMPARISON OPERATORS ————————_— Exony Operator Name Result io : a Equal to true abe Seti 7a T ett ee nse (amr) erifitne Shik ual bo fis consolelog(x ++ y)i Mf false Shick not equal true [Link](x I= y); if false > Greater than true [Link](x !== y); // true < Lass thas ie [Link](x > 3); i true ee eee trae Seeds (2g), a Sn 25. LOGICAL OPERATORS Operator [Name Deseription Example Ee Pee bs yb Wb a+5, be 3,84 && | AND (>3 be 3>1) eal ine Soe console. lag(a > b && b>); I true Rare tan fo el Il oR | Res ee (6>3 i13<1) conselerleg(a 3) ee GE ue 26. CONTROL FLOW STATEMENTS © Control flow statements are used to control the flow of execution based. on conditions Le | A. if Statement 2. if. selse 3. else if Ladder 4. switch Statement 5. ternary Operator | Ewesutes @ block Executes ona block | | Checks multiple Enecules a Hack Short hand if...lee | condition condition is true, | | conditions one by | | based on different used. for simple | [Lis ewe Aheraise another. | | one cases conditions Example Lyf 2. ifn 3. lee if Ladder 4 suite 5. lamary let x = 40; lx 235 lbs lab day = 2; lek age = 18; Jose Forse Gers) {| stehCdag) { Lab rend = (age >= 48) conte Leg("K is | contalaag(*K > 5°); | , comele ea @T 107: | case 4: cml eg Hn" ° “Adulk” oe mel Flee if (> 5) { break, ae # = irae E console-log ("GT 5°); | case 2: cone log ("Tie") s log "67 5°9, ge } onsale lag("X <= 5*);| } alee beak; onsale: lg (result); } conse lg ("<= 5°); | defi: const log(“Other"); } a 27. LOOPS IN JAVASCRIPT * Loops are used to execute a block of code multiple times © JavaScript has 3 types of loops Types 4. for Loop 2. while Loop Used when number of iterations is noun Exenstes the lock as long ‘ax the condition is true, Example for (lek b= 45 142 5; bre) cule eg(i)) 1 5 3 Example Wied; while (i <= 5) { console log(i); I to nee 28. FUNCTIONS IN JAVASCRIPT + Tk helps in reusability and. organiza 4. Fintion Declaration z conelag(Di IA te 5 F sfile (ie 5); |A function is a block of code designed to perform a. particular task. ion of code 2. Function. Expression 3. Arrow Function (ES6) fundion adda, bY relurn a+ bi } let sum = add(5, 3); cena leg(sum)s 8 Lab mallply = funciona, 6) { return a # bs % Lak recall = maltiply(4, 25 console lg(resall); If 8 console. lag (es) let divide = (a, b) => o/b; lat res = divide(10, 2); ns 4, Default Parameter 5. Rest Parameter (ES6) 6 Tnmiely Ted Flin. Exresion (LIFE) Fri. gri(name » “Gusk”) { conslaLog("Hell, * + name); greets Wf Halo, Guest gyeet("Aman”): 1 Hello, Aman Fastin esd Grant) { } reburn [Link]( (a, b) => 2+ b, 0) console Leg(sumAll(1, 2, 3,49); 19 Gustin’) € Os contla log (“TIFE exscated”); UI Rans immediatly Pee eee aaa | 29, FUNCTIONS IN JAVASCRIPT Pico farce sere pelle dechalo aede ebpat pore epecfc ta | + They help in code reusobility ond modularity Function Sy Example function funcionNeme (parameters) { function add (a, b) { II code to be executed lh ng, = 9 bs return. sum; return value; —// optional } ) lat remit = add(5, 3); console Leg (result); // 8 How ib. Works 1, Define the function using the function keyword. 2. Past ergunants when calling the function 3, Code inside the funchion executes 4 Tf return is used, the value is seat back Types of Functions 4. Function Declaration 2. Function Expression function (name) { return “Holle ” + name; 3. Arrow Funchion (ES6) ' ' function greet (name) { ' return “Hello "+ name; ! } i) const. great const greet = (name) => { rabarn “Holle!” * mania; h [Link] (greet (“Amen”); console log (greet ("Aman”)) ; console. Lg (greet (“Aman")); H Hallo Amon Hf Halle Anan 1 Hale Aman © Defined. uring. funtion por © Aaigud ta a vera © Shorter op © Can be called before decoration 1 I I I ' | ' | | | «Doce nat have ite oun this # Cannot be called before declaration Parameters vs Arguments + Parameters are variables Listed in the function definition + Arguments ore values passed when calling the function Return Statement © flere sede aed Gals teak fom Ue fat + Tf no alum i ated, funtion rebar undone, 1 t 1 Paranaars Cin dfn) | Argenta Go eal) | | | fonction oqnre(n) {| | [function pik € 1 | return n= 95 1 | conolelag (742°); function multiply es y) {| Ut reat = malliply(+, 895] | |} 1}} rebum x * 93 console log (rent); 1/ 20 | | | [Link] square (4)); | | | let vol + print); } | | 7 16 | | [Link] (val); 17 undefined I ! Default Parameters (ES6) Rest Parameters (ES6) funstion grect(name » “Guast") { finetion sumAlL(...name) { return “Hello, " + name; return [Link]((ace, val) => ace + val, 0); } } concla. log (greet ())5 1 Halo, Guash consle lag (sumAlL(4, 2, 3))5 n6 console -lg (greet (“Aman”); // Helle, Anan console og (sumAlL (4, 2, 3, 4, 5)); U7 45 30. FUNCTIONS IN JAVASCRIPT (CONT. ) + Functions can be created in different ways + Thay can have paramaters, return values ond con Other Ways te Create Functions 4. Function Expression 2. Arrow Function (ESS) be used multiple times 3. Arrow Function (Shorter) const add = fanction(a, 6) { relun a + bj } conasle. log (add (2, 3)); } NS return a + conaoe. log (ad(2, 3)); 11 5 1b) > { const add = a,b) > a+ b; console log (edd (2, 3)); // 5 4. Tmmediately Invoked Function Expression (IIFE) (fanction() { [Link]((“TIFE executed”); DOs Function with Default Parameter (ES6) Function with Rest Parameter (ES6) Guest") { function greet (name return “Hello,” y console. log (greet ()); H Hello, Guest [Link] (greet (“Aman")); /// Hello, Aman function sumAll(...nums) { return mums reduce((ace, val) => ace + val, 0); 5 [Link](sumAll(4, 2, 3)); M6 consslelog(aumAll(4, 2,3, 4, 5)); M1 15 Return Statement, + return is used to send a value back function square (n) { rebum © ny function show() { consst lag ("Hi") from the function ) } © If no tobrnts teed, finctin ans , Uab val = hou) undefined re ae eae shea Function Rules / Paints to Remember 4 Function names are cose sensitive Function can be pasted as « value Function can return onather function Anonyrous functions can be used or en Function nama should follow variable naming rule. Example : Function returning anather function function outer() { return function inner() { return “Hello from inner”; } const fo = outer(); [Link](fr()); // Hello from inner = 92 FOLLOW. « —> FOR <— ; FART ¢ c => COMMENT = x FOR PDF NOTES

You might also like