0% found this document useful (0 votes)
22 views22 pages

Js Cheatsheet

js notes

Uploaded by

21052473
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)
22 views22 pages

Js Cheatsheet

js notes

Uploaded by

21052473
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
You are on page 1/ 22
— Oy = JavaScript CheatSheetIn this Cheatsheet, we will cover the basics of JavaScript. We will provide examples to help you understand how JavaScript work and how to use them in your own web development projects. Whether you are a beginner or an experienced developer, this PDF can serve as a useful reference guide. ss} JavaScript JavaScript is a programming language that is widely used in web development. It is a client-side scripting language, which means that it is executed on the client side (in a web browser) rather than on the server side. JavaScript is used to create interactive web pages and is an essential component of modern web development. It is a high-level, dynamically typed language that is interpreted, which means that it is not compiled into machine code before it is run. JavaScript is used to add functionality to websites, such as handling user events (such as clicks and form submissions), animating page elements, and making asynchronous requests to servers. It is a versatile language that can be used for a wide range of applications, from simple scripts that add simple interactivity to websites to complex single-page applications. On page script: Include external JS file: Delay - 1 second timeout: setTimeout(function 0 { }, 1000); Functions: function addNumbers(a, b) { return a +b;; } x= addNumbers(1, 2); Edit DOM element: document.getElementById("elementID").innerHTML = "Hello World)”; Output: console.log(a); document.write(a); alert(a); confirm("?"); prompt("Age // write to the browser console. // write to the HTML. // output in an alert box. // yes/no dialog, returns true/false depending on user click. // input dialog box. (Initial Value = 0).Values: false, true // Boolean 4, 3.14, 0b10011, OxF6, NaN // Number "CodeHelp", ‘Love’ // String undefined, Infinity, null // Special Basic Operators: a=b+c-d; // Addition, Subtraction. a=b*(c/d); // Multiplication, Division. x=10%4; // Modulo, 10 / 4 Remainder = 2. a++; b--; // Postfix Increment and Decrement. Bitwise Operators: & AND 5&1 (010160001) 1 I OR 5|1 (0101}0001) 5 - NoT -5 (-0101) 10 4 XOR Sa (01010001) 4 Right Shift S>>1 (0101 >> 1) 2 >>> Zero Fill Right Shift 5 >>>1 (0101 >>> 1) 2 @ (01) (1010) (100) (1010) (10) (10)Objects: var student = { firstName: "Koushik", lastName: "Sadhu", age: 20, height: 175, fullName: functionO { // object name // list of properties and values // object function return this.firstName +"" + this.lastName; b student.age = 19; student[age]++; name = student.fullNameQ; // setting value // incrementing value // call object function | Strings: var a = "Codehelp"; var b = 'I don\'t \n know’; var len = a.length; a.indexof("h"); a.lastIndexOf("e"); aslice(, 6); a.replace("help","love"); a.toUpperCase(); a.toLowerCase(); a.concat("”, str2); a.charAt(4); abe.split(” "); //\n new line. // string length. // find substring, -1 if doesn't contain, // \ast occurrence. // cut out "ehe", negative values count from behind. // find and replace, takes regular expressions. // convert to upper case. // convert to lower case. // Codehelp +" + str2. // character at index 4: // splitting a string on space, and stores in an array.Numbers and Math: var pi = 3.14; pi.toFixed(0); pi.toFixed(2); pi.toPrecision(2) pi.valueofo; Number‘true); Number(new DateQ) parselnt("3 months”); parseFloat("3.5 days"); Number.MAX_VALUE Number.MIN_VALUE Number.NEGATIVE_INFINITY Number.POSITIVE_INFINITY var pi = Math.PI; Math.round(4.5); Math.pow(2,8); Math.sqrt(49); Math.abs(-3.14); Math.ceil(.14); Math.floor(3.99); Math.sin(); Math.cos(Math.PI); Math.min(O, 3, -2, 2); Math.max(0, 3, -2, 2); Math.log(1); Math.exp(1); Math.randomQ); Math.floor(Math.random( * 5) + 1; // returns 3 // returns 3.14, working with money // returns 3.1 // returns number // converts to number // number of milliseconds since, 1970 // returns the first number 3 // returns 3.5 // largest possible JS number // smallest possible JS number // Minus Infinity // Infinity // 3.141592653589793 WS // 256 - 2 to the power of 8 //7- square root // 3.14 - absolute, positive value // 4~rounded up //3- rounded down //0-sine // OTHERS: tan, atan, asin, acos, // -2 the lowest value //3 the highest value 7/0 natural logarithm // 2.7182pow(E,X) // random number between 0 and 1 // random integer, from 1 to 5Array: var flowers = ["Rose", var flowers = new Array ("Rose", "Sunflower", "Lotu: alert(flowers[1]); dogs[0] = "Hibiscus", for (vari console.log(flowers[i]); ", "Sunflower", "Lotus", “Lily”]; 0; i = 10) && (age Click here « Mouse Events: o onclick © oncontextmenu o ondbiclick © onmousedown © onmouseenter © onmouseleave © onmousemove © onmouseover © onmouseout © onmouseup* Keyboard Events: ° ° onkeydown onkeypress onkeyup ° Frame Events: onabort onbeforeunload onerror onhashchange onload onpageshow onpagehide onresize, onscroll onunload « Form Events: ° ° onblur onchange onfocus onfocusin onfocusout oninput oninvalid onreset onsearch onselect onsubmit* Drag Events: ° ° ° ° ondrag ondragend ondragenter ondragleave ondragover ondragstart ondrop * Clipboard Events: ° ° ‘oncopy oncut onpaste * Media Events: ° onabort oncanplay oncanplaythrough ondurationchange onended onerror onloadeddata onloadedmetadata onloadstart onpause onplay onplaying onprogress onratechange onseeked onseeking onstalled onsuspend© ontimeupdate © onvolumechange © onwaiting ¢ Animation Events: o Animationend o Animationiteration © Animationstart ‘cellaneous Events: © transitioned ° onmessage © onmousewheel © ononline © onoffline © onpopstate © onshow © onstorage © ontoggle © onwheel © ontouchcancel © ontouchmove Errors: try { undefinedFunctionO; } catch¢err) { console.log(err.message); // try block of code // block to handle errorsThrow error: throw "My error message"; // throws a text Input validation: const input = document.getElementById(‘num"); _// get input element try { const x = input.value; // get input value if (x ==") throw "empty"; // error cases if (isNaN@x)) throw “not a number”; x = Number(x); if (% > 20) throw "too hig} } catch (err) { // if there's an error console.log(“Input is ${err}"); // output error console.error(ert); // write the error in console } finally { console.log("Done" // executed regardless of the try catch block Error Names: * RangeError: A number is "out of range”. « ReferenceError: An illegal reference has occurred. ¢ SyntaxError: A syntax error has occurred. * TypeError: A type error has occurred. © URIError: An encodeURI( error has occurred.ISON: JavaScript Object Notation let str = '{"names"’ '{("first”"Koushik","lastN":"Sadhu" },' + “¢first’s"Pranay”,"lastl ‘¢"first’:"Shuvam’,"last":'Chodhury" }]¥; upta” },) + obj = JSON.parse(str); console.log(obj.namesf1].first); // Send: let myObj = { "name"?"Nidi let myJSON = JSON.stringify(myObj); window.location = “demo,html?x=${myJSON}*; // Storing and retrieving: let myObj = { "name":"Nidhi”, "age":20, “city"." Kolkata” }; let myJSON = JSON.stringify(myObj); localStorage.setItem("testJSON”, myJSON); let text = localstorage.getItem("testJSON"); let obj = JSON.parse(text); document.write(obj.name); "age":20, "city"”"Kolkata” }; // create JSON object // create object // stringify // sending to php // storing data // retrieving datafunction sum(a, b) { return new Promise((resolve, reject) => { setTimeout(@ => { // send the response after 1 second if (typeof a “number” || typeof b ! "number"){ — // testing input types return reject(new TypeError("Inputs must be numbers")); + resolve(a + b); }, 1000); Ds + let myPromise = sum(10, 5); myPromise.then((result) => { console.log("10 + 5:", result); return sum(null, “foo"); // Invalid data and return another promise Dy} sthen(Q => { // Won't be called because of the error » scatch((err) => { console.error(ert); // => Inputs must be numbers Ds

You might also like