Open navigation menu
Close suggestions
Search
Search
en
Change Language
Upload
Sign in
Sign in
Download free for days
0 ratings
0% found this document useful (0 votes)
5 views
Js Cheatsheet
js notes
Uploaded by
21052473
AI-enhanced title
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
Download now
Download
Save js cheatsheet For Later
Download
Save
Save js cheatsheet For Later
0%
0% found this document useful, undefined
0%
, undefined
Embed
Share
Print
Report
0 ratings
0% found this document useful (0 votes)
5 views
Js Cheatsheet
js notes
Uploaded by
21052473
AI-enhanced title
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
Download now
Download
Save js cheatsheet For Later
Carousel Previous
Carousel Next
Save
Save js cheatsheet For Later
0%
0% found this document useful, undefined
0%
, undefined
Embed
Share
Print
Report
Download now
Download
You are on page 1
/ 22
Search
Fullscreen
— 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 <« Left shift Sccl (0101 << 1) 10 > 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 < flowers.length; i++) { // Array Declaration ly”); //Alternate method. // access value at index. // change the first item to “Hibiscus”. // Accessing array element using loop. Array Methods: flowers.toStringQ); flowersjoin(” _ "); flowers.pop0; flowers.push("Tulip"); flowers [flowers.length] = "Tulip"; flowers.shift0; flowers.unshift(Tulip"); delete.flowers[0]; flowers.splice(2, 0, "ABC", "DEF"); var f = flowers.concat(a,b); flowers.slice(1,4); flowers.sortQ); flowers.reverse(); x.sort(function(a, b){return a - b}); x-sort(function(a, b){return b - a}); // convert the array to string. // join between two array element. // remove last element. // add new element to the end. // the same as push. // remove first element. 7/ add new element to the beginning. // change element to undefined. // add elements. // join two arrays (a followed by b). // elements from [1] to [4-1]. // sort string alphabetically. // sort string in descending order. // numeric sort. // numeric descending sort. x.sort(function(a, b){return 0.5 - Math.random()});__// random order sorting.Regular Expressions: var a = strsearch(/CheatSheet/i); Modifiers: Patterns: *\ *\d *\s *\b ° one . n* ° n? a -$ © WOOK ° aly © Ge) ° [xyz] *° [0-9] © [xyz] e\s perform case-insensitive matching. perform a global match. perform multiline matching. Escape character find a digit find a whitespace character find match at beginning or end of a word contains at least one n contains zero or more occurrences of n contains zero or one occurrences of n Start of string End of string find the Unicode character Any single character xory Group section In range (x, y or z) any of the digits between the brackets Not in range White space° a? . at ° at? a © a+? © a{2} © af2,} * a{,10} * {1,6} + a{4,6}? * [punct:] * [:space:] © [blank] If-Else Statements: if (age >= 10) && (age < 20)) { status = "Permitted.”; } else { status = "Not Permitted.”; Zero or one of a Zero or more of a Zero or more, ungreedy One or more of a One or more, ungreedy Exactly 2 of a 2 or more of a Up to 10 of a lto6ofa 4tobofa Any punctuation symbol Any space character Space or tab // \ogical condition // executed if condition is true // else block is optional // executed if condition is falseswitch (day) { case 1: text = "Monday"; break; case 2: text = "Tuesday"; break; case 3: text = "Wednesday"; break; case 4: text = "Thursday"; break; case 5: text = "Friday"; break; case 6: text = "Saturday"; break; case 7: text = "Sunday"; break; default: text = "Please enter valid day number.”; // Input is current day in numeric. // if (day == 1) // if (day == 2) /1 if (day == 3) /1 if (day == 4) // if (day == 5) /1 if (day == 6) // if (day == 7) // else...While Loop:Do While Loop: Break Statement: Continue Statement:Dates: var d = new Dated; a=d.getDayQ; getDateQ; getDay(); getFullYear(; getHours(; getMilliseconds(); getMinutes(Q; getMonthQ; getSeconds(); getTimeQ; dsetDate(d.getDate() + 7); setDateQ; setFullYear(; setHours(); setMilliseconds(; setMinutes0; setMonth(); setSeconds(); setTimeg; // getting the weekday // day as a number (1-31) // weekday as a number (0-6) // four digit year (yyy) // hour (0-23) // milliseconds (0-999) // minutes (0-59) // month (0-11) // seconds (0-59) // milliseconds since 1970 // adds a week to a date // day as a number (1-31) // year (optionally month and day) // hour (0-23) // milliseconds (0-999) // minutes (0-59) // month (0-11) // seconds (0-59) // milliseconds since 1970)Global Functions: eval(); String(44); (44)t0StringQ; Number("44”); decodeURI(enc); encodeURI(uri); decodeURIComponent(enc); encodeURIComponent(uri); // executes a string as if it was scriptcode // return string from number // return string from number // return number from string // decode URI, Result: "page.asp" // encode URI. Result: "page.asp" // decode a URI component // encode a URI component parseFloat; // returns floating point number of string parseInto; // parses a string and returns an integer isFiniteQ; //is variable a finite, legal number isNaNo; // is variable an illegal number Events:
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
The Subtle Art of Not Giving a F*ck: A Counterintuitive Approach to Living a Good Life
From Everand
The Subtle Art of Not Giving a F*ck: A Counterintuitive Approach to Living a Good Life
Mark Manson
4/5 (6125)
Principles: Life and Work
From Everand
Principles: Life and Work
Ray Dalio
4/5 (627)
The Gifts of Imperfection: Let Go of Who You Think You're Supposed to Be and Embrace Who You Are
From Everand
The Gifts of Imperfection: Let Go of Who You Think You're Supposed to Be and Embrace Who You Are
Brené Brown
4/5 (1148)
Never Split the Difference: Negotiating As If Your Life Depended On It
From Everand
Never Split the Difference: Negotiating As If Your Life Depended On It
Chris Voss
4.5/5 (932)
The Glass Castle: A Memoir
From Everand
The Glass Castle: A Memoir
Jeannette Walls
4/5 (8214)
Grit: The Power of Passion and Perseverance
From Everand
Grit: The Power of Passion and Perseverance
Angela Duckworth
4/5 (631)
Sing, Unburied, Sing: A Novel
From Everand
Sing, Unburied, Sing: A Novel
Jesmyn Ward
4/5 (1253)
The Perks of Being a Wallflower
From Everand
The Perks of Being a Wallflower
Stephen Chbosky
4/5 (8365)
Shoe Dog: A Memoir by the Creator of Nike
From Everand
Shoe Dog: A Memoir by the Creator of Nike
Phil Knight
4.5/5 (860)
Her Body and Other Parties: Stories
From Everand
Her Body and Other Parties: Stories
Carmen Maria Machado
4/5 (877)
Hidden Figures: The American Dream and the Untold Story of the Black Women Mathematicians Who Helped Win the Space Race
From Everand
Hidden Figures: The American Dream and the Untold Story of the Black Women Mathematicians Who Helped Win the Space Race
Margot Lee Shetterly
4/5 (954)
The Hard Thing About Hard Things: Building a Business When There Are No Easy Answers
From Everand
The Hard Thing About Hard Things: Building a Business When There Are No Easy Answers
Ben Horowitz
4.5/5 (361)
Steve Jobs
From Everand
Steve Jobs
Walter Isaacson
4/5 (2922)
Elon Musk: Tesla, SpaceX, and the Quest for a Fantastic Future
From Everand
Elon Musk: Tesla, SpaceX, and the Quest for a Fantastic Future
Ashlee Vance
4.5/5 (484)
The Emperor of All Maladies: A Biography of Cancer
From Everand
The Emperor of All Maladies: A Biography of Cancer
Siddhartha Mukherjee
4.5/5 (277)
Brooklyn: A Novel
From Everand
Brooklyn: A Novel
Colm Toibin
3.5/5 (2061)
A Man Called Ove: A Novel
From Everand
A Man Called Ove: A Novel
Fredrik Backman
4.5/5 (4972)
Angela's Ashes: A Memoir
From Everand
Angela's Ashes: A Memoir
Frank McCourt
4.5/5 (444)
The Art of Racing in the Rain: A Novel
From Everand
The Art of Racing in the Rain: A Novel
Garth Stein
4/5 (4281)
The Yellow House: A Memoir (2019 National Book Award Winner)
From Everand
The Yellow House: A Memoir (2019 National Book Award Winner)
Sarah M. Broom
4/5 (100)
The Little Book of Hygge: Danish Secrets to Happy Living
From Everand
The Little Book of Hygge: Danish Secrets to Happy Living
Meik Wiking
3.5/5 (447)
The World Is Flat 3.0: A Brief History of the Twenty-first Century
From Everand
The World Is Flat 3.0: A Brief History of the Twenty-first Century
Thomas L. Friedman
3.5/5 (2283)
Bad Feminist: Essays
From Everand
Bad Feminist: Essays
Roxane Gay
4/5 (1068)
Yes Please
From Everand
Yes Please
Amy Poehler
4/5 (1987)
Devil in the Grove: Thurgood Marshall, the Groveland Boys, and the Dawn of a New America
From Everand
Devil in the Grove: Thurgood Marshall, the Groveland Boys, and the Dawn of a New America
Gilbert King
4.5/5 (278)
The Outsider: A Novel
From Everand
The Outsider: A Novel
Stephen King
4/5 (1993)
The Woman in Cabin 10
From Everand
The Woman in Cabin 10
Ruth Ware
3.5/5 (2619)
A Tree Grows in Brooklyn
From Everand
A Tree Grows in Brooklyn
Betty Smith
4.5/5 (1936)
The Sympathizer: A Novel (Pulitzer Prize for Fiction)
From Everand
The Sympathizer: A Novel (Pulitzer Prize for Fiction)
Viet Thanh Nguyen
4.5/5 (125)
A Heartbreaking Work Of Staggering Genius: A Memoir Based on a True Story
From Everand
A Heartbreaking Work Of Staggering Genius: A Memoir Based on a True Story
Dave Eggers
3.5/5 (692)
Team of Rivals: The Political Genius of Abraham Lincoln
From Everand
Team of Rivals: The Political Genius of Abraham Lincoln
Doris Kearns Goodwin
4.5/5 (1912)
Wolf Hall: A Novel
From Everand
Wolf Hall: A Novel
Hilary Mantel
4/5 (4074)
On Fire: The (Burning) Case for a Green New Deal
From Everand
On Fire: The (Burning) Case for a Green New Deal
Naomi Klein
4/5 (75)
Fear: Trump in the White House
From Everand
Fear: Trump in the White House
Bob Woodward
3.5/5 (830)
Rise of ISIS: A Threat We Can't Ignore
From Everand
Rise of ISIS: A Threat We Can't Ignore
Jay Sekulow
3.5/5 (143)
Manhattan Beach: A Novel
From Everand
Manhattan Beach: A Novel
Jennifer Egan
3.5/5 (901)
John Adams
From Everand
John Adams
David McCullough
4.5/5 (2530)
The Light Between Oceans: A Novel
From Everand
The Light Between Oceans: A Novel
M L Stedman
4.5/5 (790)
The Unwinding: An Inner History of the New America
From Everand
The Unwinding: An Inner History of the New America
George Packer
4/5 (45)
Little Women
From Everand
Little Women
Louisa May Alcott
4/5 (105)
The Constant Gardener: A Novel
From Everand
The Constant Gardener: A Novel
John le Carré
3.5/5 (109)
Related titles
Click to expand Related Titles
Carousel Previous
Carousel Next
The Subtle Art of Not Giving a F*ck: A Counterintuitive Approach to Living a Good Life
From Everand
The Subtle Art of Not Giving a F*ck: A Counterintuitive Approach to Living a Good Life
Principles: Life and Work
From Everand
Principles: Life and Work
The Gifts of Imperfection: Let Go of Who You Think You're Supposed to Be and Embrace Who You Are
From Everand
The Gifts of Imperfection: Let Go of Who You Think You're Supposed to Be and Embrace Who You Are
Never Split the Difference: Negotiating As If Your Life Depended On It
From Everand
Never Split the Difference: Negotiating As If Your Life Depended On It
The Glass Castle: A Memoir
From Everand
The Glass Castle: A Memoir
Grit: The Power of Passion and Perseverance
From Everand
Grit: The Power of Passion and Perseverance
Sing, Unburied, Sing: A Novel
From Everand
Sing, Unburied, Sing: A Novel
The Perks of Being a Wallflower
From Everand
The Perks of Being a Wallflower
Shoe Dog: A Memoir by the Creator of Nike
From Everand
Shoe Dog: A Memoir by the Creator of Nike
Her Body and Other Parties: Stories
From Everand
Her Body and Other Parties: Stories
Hidden Figures: The American Dream and the Untold Story of the Black Women Mathematicians Who Helped Win the Space Race
From Everand
Hidden Figures: The American Dream and the Untold Story of the Black Women Mathematicians Who Helped Win the Space Race
The Hard Thing About Hard Things: Building a Business When There Are No Easy Answers
From Everand
The Hard Thing About Hard Things: Building a Business When There Are No Easy Answers
Steve Jobs
From Everand
Steve Jobs
Elon Musk: Tesla, SpaceX, and the Quest for a Fantastic Future
From Everand
Elon Musk: Tesla, SpaceX, and the Quest for a Fantastic Future
The Emperor of All Maladies: A Biography of Cancer
From Everand
The Emperor of All Maladies: A Biography of Cancer
Brooklyn: A Novel
From Everand
Brooklyn: A Novel
A Man Called Ove: A Novel
From Everand
A Man Called Ove: A Novel
Angela's Ashes: A Memoir
From Everand
Angela's Ashes: A Memoir
The Art of Racing in the Rain: A Novel
From Everand
The Art of Racing in the Rain: A Novel
The Yellow House: A Memoir (2019 National Book Award Winner)
From Everand
The Yellow House: A Memoir (2019 National Book Award Winner)
The Little Book of Hygge: Danish Secrets to Happy Living
From Everand
The Little Book of Hygge: Danish Secrets to Happy Living
The World Is Flat 3.0: A Brief History of the Twenty-first Century
From Everand
The World Is Flat 3.0: A Brief History of the Twenty-first Century
Bad Feminist: Essays
From Everand
Bad Feminist: Essays
Yes Please
From Everand
Yes Please
Devil in the Grove: Thurgood Marshall, the Groveland Boys, and the Dawn of a New America
From Everand
Devil in the Grove: Thurgood Marshall, the Groveland Boys, and the Dawn of a New America
The Outsider: A Novel
From Everand
The Outsider: A Novel
The Woman in Cabin 10
From Everand
The Woman in Cabin 10
A Tree Grows in Brooklyn
From Everand
A Tree Grows in Brooklyn
The Sympathizer: A Novel (Pulitzer Prize for Fiction)
From Everand
The Sympathizer: A Novel (Pulitzer Prize for Fiction)
A Heartbreaking Work Of Staggering Genius: A Memoir Based on a True Story
From Everand
A Heartbreaking Work Of Staggering Genius: A Memoir Based on a True Story
Team of Rivals: The Political Genius of Abraham Lincoln
From Everand
Team of Rivals: The Political Genius of Abraham Lincoln
Wolf Hall: A Novel
From Everand
Wolf Hall: A Novel
On Fire: The (Burning) Case for a Green New Deal
From Everand
On Fire: The (Burning) Case for a Green New Deal
Fear: Trump in the White House
From Everand
Fear: Trump in the White House
Rise of ISIS: A Threat We Can't Ignore
From Everand
Rise of ISIS: A Threat We Can't Ignore
Manhattan Beach: A Novel
From Everand
Manhattan Beach: A Novel
John Adams
From Everand
John Adams
The Light Between Oceans: A Novel
From Everand
The Light Between Oceans: A Novel
The Unwinding: An Inner History of the New America
From Everand
The Unwinding: An Inner History of the New America
Little Women
From Everand
Little Women
The Constant Gardener: A Novel
From Everand
The Constant Gardener: A Novel