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

Javascript Notes Nutshell

Uploaded by

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

Javascript Notes Nutshell

Uploaded by

Pushpak Rai
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 30
Why you should Learn JavaScript? Te Com ncn eg Like most languages, you don't need to setup anything. You can run your code without any Environment. Easy to Learn A very beginner friendly language in which you don't need to learn deal with complexities. Versatile Programming Language From front-end to back-end, JavaScript can be used for almost anything. There's nothing you can't do with Bo Big Community Support Doesn't matter what error you face while learning. Just google it, and you'll see tons of solution. Let, Const, Var Let The let statement declares a block-scoped local variable, optionally initializing it to a value. var The var statement declares a function-scoped or globally- scoped variable, optionally initializing it to a value. const Constants are block-scoped, much like variable is declared using the let keyword. The value of a constant can't be changed through reassignment, and it can't be redeclared. Cheatsheet. @ Lae aoa ela BYE) [ose a tere) os) Cel ilatele) [=| ae as Operations Definition In JavaScript, an operator is a special symbol used to perform operations on operands (values and variables). 24 oF tS + is an operator that performs addition, and 2 and 3 are operands. JavaScript Operator Types + Assignment Operators. + Arithmetic Operators. + Comparison Operators. + Logical Operators. + Bitwise Operators. + String Operators. + Other Operators. Data Types Data types can be confusing sometimes. Let's make it clear because its super important. Definition Ces aa ean ema TBC + 5 is an integer data. + "Hello" is a string data represents textual data Ree ate an integer ora floating-point number an integer with arbitrary er irela] ere Pa Amon Col es true or false foTolel Coho Bilarels variable is not initialized mat denotes a null value Cre E Rd es ont MT Cy and immutable key-value pairs of besa kaa Mes eter eet etc Strings Blo Wolrell leita las | Javascript string is a primitive data type that is used to work with texts. For example, Sa eid Creating Javascript String. Satlarels are created by surrounding them with quotes. Here's how we do it: Single quotes: ‘Hello’ Double quotes: "Hello" Backticks: Hello” B Single & Double quotes are practically the same. Use Either of them. = We use backticks when we need to include variables or expression in a string. Events JavaScript Events The change in the state of an object is known as an Event. This process of reacting over the events is called Event Handling. Thus, JS handles the HTML events via Event Handlers. onclick — The event occurs when the user clicks on an element. oncontextmenu — User right-clicks on an element to open a context menu. ondbiclick — The user double-clicks on an element. onmousedown — User presses a mouse button over an element. onmouseenter — The pointer moves onto an element. onmouseleave — Pointer moves out of an element. onmousemove — The pointer is moving while it is over an element. AV a Rey Ug Event Handler There are two ways you can handle an Ova » Event Listeners. » Event Handlers. Event Handlers » To use event handlers, use one of the EventHandler properties of an object. + Here’s an example of using one onmouseover. e oes Coane srr Cat amc Tae) Pel One Serer ert m Terao) } + onmouseover - triggers when the mouse pointer is moved onto the button. Event Listener + An event listener is something you assign to an object. + As the name suggests, the event listener listens for events and gets triggered when an event occurs. Caney Creer ra Ca en Ta) eee areca ee Ona Um eta i?) mouseover". () => + mouseover - Hovering on the button triggers a "mouseover" event, then it runs the block of code. Functions JavaScript Functions JavaScript provides functions similar to most of the scripting and programming languages. In JavaScript, a function allows you to define a block of code, give it aname and then execute it as many times as you want. Example Pe eo et Pa@n tC oath) i SO Objects JavaScript Objects Javascript object is a non-primitive data-type that allows you to store multiple collections of data. ears ys etre Uta ert) Here, student is an object that stores values such as strings and numbers. JavaScript Object Declaration const object_name = key1: value, VP MMT Yd Here, an object object_name is defined. Each member of an object is a key: value pair separated by commas and enclosed in curly braces {}. Arrays JavaScript Arrays. An array is an object that can store multiple elements. For example, a seed Geer aC eo Array Example. const myList = [ ]; const numberarray = [ 2, 4, 6, 8]; const stringArray = [ 'eat', ‘work', 'sleep']; const newData = ['work', ‘exercise’, 1, true]; eats what is getter - we use getter to access the properties. In this case, we have firstName & lastName, but what if we want to access full name. Here's how we will do it. (oleae 3 1 ee e-19) ec ab ea lastName = 'Khan', fullname () { ce raed eee aes RS Oelbace a i i in fullName(), we're using a template literal. Output - Cr) CeCe eum LO setter Pine la i 1 Cl ad we use setter to change (mutate) the property. coo aera pest ames Pea a et em ee a i Seem Cetra are ty Sree eee Cet nett to} oe clus hues auc iets kitty Eacktelteiciahslaj rod eee arg) Peet See a AK el Tok mai em a ela Mieke RMI} for loop For Loop Loops are used to repeat a block of code. Example If you want to show something 1000 times, you can use a loop. Syntax Eaten eke estou cer Seah eed for eee condition; updateExpression) { milano ha eee ens een eu Mer Tec) ea Re Lae et ea ee aR Red cl sco when the condition is true. Example - const n = 5; eae ar ar ero ie | ee Ces ae Rr e cee for...in Syntax ae com CMU Sao el i In each iteration of the loop, a key is assigned to the key variable. The loop continues for all object properties. Once you get keys, you can easi Teta tig corresponding values. Example - Output - name => Monica class =>7 age => 12 SCR a@n (yee cc oca Ts) Code Explanation - In the above program, the for..in loop is used to iterate over the student object and print all its properties. |- The object key is assigned to the variable key. 2- student[key] is used to access the value of key. while loop While Loop The while loop loops through a block of code as long as a specified condition is true. Syntax PCR TtStL3) } Example - the code in the loop will run, over and over again, as long as a variable (1) is less than 10: e CeCe eee Tae do while loop Do while statement creates a loop that executes a specified statement until the test condition evaluates to false. syntax aD Cle paper ceaa (sha Cp) atom Tao d > The body of loop is executed. >> If the condition is true, the body of the loop inside the do statement is executed again. >> The condition is evaluated again. >> If the condition evaluates to true, the body inside do is executed again. >> The process continues until the condition evaluates to false. Then the loop stops. Com CN Mea CRM toe MU ko NY CCC u unm te mutlses Redes is executed at least once. Type Conversion Break Statement Type conversion is the process of converting data of one type to another. Example - Converting String data to Number. it Conversion - automatic type conversion it Conversion - manual type conversion Mua lick con) In certain situations, JavaScript automatically converts one data type to another (to the right type). Example Cx) ranretied ete eae ey console. Log( result) porte eae a aT) console. log( result) || Explicit Conversion The type conversion that you do manually is known as explicit type conversion. Example eae result = Number('324'); console. log( result); Pear Tae Caren) Cote Certo oascoind pron eae retest console. log(result); Ponte enero console. log(result); Callbacks A function is a block of code that performs a certain task when called. esr ae Coreen! Pa In above program, a string value is passed as an argument to the greet() function. In JavaScript, you can also pass a function as an argument to a function. This function that is passed as an argument inside of another function is called a callback function. function greet(name, caliback) { console.log(‘Hi' + ' * + name); callback() i este con! PeOCN Cr areca Ts Cuny i Pea ee Promises Promises is a good way to handle asynchronous operations. It is used to find out if the asynchronous operation is successfully completed or not. States - A promise may have one of three states. >> Pending. peel cro >> Rejected. A promise start with pending state means the process is not complete. If the operation is successful, the process ends in a fulfilled state. If error occurs, the process ends in a rejected state. Create a promise - ae let promise = new Promise( function(resolve, reject){ » Example ao const count = true} Steer ast Merete ao et acorn ee enG eet a tea en reject(*There is no count value") i CeCe Creare Output eee Promise {: ‘There is a count value."} In the above program, a Promise object is created VES To) that takes two functions: resolve() and el resolve() is used if the process is successful and reject! when an error occurs in the promise. The promise is resolved if the value of count is true. Async,Await “async and await make promises easier to write" async makes a function return a Promise. await makes a function wait for a Promise. e Poe as Cree acto >> name - name of the function >> parameters - parameters that are passed to the function Example felt oltig ( async function. peeek Cera eett The await keyword is used inside the async function to wait for the asynchronous operation. Example Ce ee oer mesa Spo REE TEIEE DS wait for promise to (oregano ky eon ey ee een Porrent mica) calling function Note: You can use await only inside of async functions. Closures Before you understand closure, quickly understand these two concepts. >» Nested Function >» Returning a function Nested Function a function can also contain another function. er Returning a function you can also return a function within a function. function greet(nane) function displayName() ECR Tarr + nae) ere eer Serre Tre) Timers Tatanl testi 3 The setTimeout() method executes a block of code after the specified time. The method executes the code only once. The commonly used syntax of JavaScript setTimeout is: setTimeout( function, milliseconds); a function the time after containing which the function a block of code is executed Example xe function greet() { UCR eek GRC Sak i asec eer Ere ek QR Ca oe eR ea In the above program, the setTimeout() method calls the greet() function after 3000 milliseconds (3 second). Prototyping JavaScript Prototype In JavaScript, every function and object has a property named prototype by default. Example function Person () { aed EeEy =< i const person = new Person(); ee Cece Ss We are trying to access the prototype property of a Person constructor function. Since the prototype property has no value at the moment, it shows an empty object { ... }. Prototype Inheritance A prototype con be used to add properties and methods to a constructor function. Example ase ee es a ee this.age = 23 ea ee Rae eae CO se ec 1s7 Co c ee Oe Case Soa console. Log( person1.gender ) Coe Cece Generators In JavaScript, generators provide a new way to Pol ann eed keh Cueto Using a generator, »2 you can stop the execution of a function from anywhere inside the function >> and continue executing code from a halted position function* generator_function() { 5 const generator_obj = generator_function(); Note: The generator function is denoted by *. You can either use function* generatorFunc() {...} or function *generatorFunc(){...} to create them. Using yield to Pause Execution You can pause the execution of a generator function without executing the whole function body. Use ‘yield’ keyword. Cas Cecaae net COCR Gree CCR aC Ce OUCH console. log("2 OCLs Cee eae Cai } Cer eee cea Reem Cece cians IK >? Generate object named "generator" is created. >> When "generator.next()" Is called, the code up to the yield is executed. When "yield" is encountered. When yield is encountered, the program returns the value and pauses the generator function. Note: You need to assign generator objects to a variable before you use it. Unicode Bott) ae tL) The Unicode Standard provides a unique number for every character, no matter the platform, device, application, or language. UTF-8 is o popular Unicode encoding which has 8-bit code units. How to insert Unicode »» Unicode in JavaScript source code. »» Unicode in JavaScript strings. bcolaalel 1, Unicode in JavaScript source code, The identifiers and string literals can be expressed in Unicode via a Unicode escape sequence. Example - The letter 0 is denoted as ‘\uO06F’ in Unicode. Hence, HOSS UTENTCIieg Sei ice, POC eo Coney Ce taa7)) Eva Unicode in JavaScript strings. Unicode can also be represented in a JavaScript string Wien MUL OP Oe noha var str = '\uD83D\uDC04'; console. log(str) a Inheritance Inheritance enables you to define a class that takes all the functionality from a parent class and allows you to add more. Inheritance is a useful feature that allows code reusability. Example | In the above example, the Student class inherits all the methods and properties of the Person class. Hence, the Student class will now have SAA OEE OSE the name property and the greet() method. Then, we accessed the greet() method of Student class by creating a student object. rose) RegEx Regular Expression (RegEx) A Regular Expression (RegEx) is an object that describes a sequence of characters used for defining a search folelac-tay 1a, 58! The above code defines a RegEx pattern. The pattern is: any five letter string starting with o and ending with s. atl UVC 1 fe Tei abs No nate coin) alias Match abyss Match Alias No match An abacus No match Create a RegEx Two ways to create RegEx in JS. 1, Using a regular expression literal. The regular expression consists of a pattern enclosed between slashes /. Corrects meme ead 2. Using the RegExp() constructor function You can also create a regular expression by calling the erelan lO heoeitterel mi inven Ces ean oar Tap) @gulraizcodes | @codewithharshad Thank you for your humble support. Its a free e-book for you so you start your journey as a JS Developer. Every topic is as short as possible. I'm sure not each and every topic is covered but these were the most important topics. We'll be making a detailed version of JavaScript e-book where we will cover every JS Topic. Thank you, once again. ~ By Harshad & Gulraiz.

You might also like