Javascript cheatsheet
Javascript function example
var isEven = function(number) { if(number%2===0) return true; else return false; }; console.log(isEven(9));
Javascript for loop example
for (var counter = 1; counter < 11; counter++) { console.log(counter); }
Javascript while loop example
var loop = function(){ var i=0; while(i<3){ console.log("I'm looping!"); i++; } }; loop();
Javascript switch example
var answer = prompt("Enter a letter here!"); switch(answer) { case 'a': console.log("a"); break; case 'b': console.log("b"); break; default: console.log("not a, not b, some other letter"); break; }
Javascript array example
var languages=["php","java","python","javascript","c++"]; for(var i=0; i<languages.length; i++) { console.log(languages[i]); }
Javascript object examples
var BMW = { cost:"too much", speed:220, country:"Germany" } var Ford = new Object(); Ford.cost = "OK"; Ford.speed = "210"; Ford.country = "USA";
Javascript object with function in it
var bob = new Object(); bob.age = 30; bob.setAge = function (newAge){ bob.age = newAge; }; bob.getYearOfBirth = function () { return 2013 - bob.age; }; console.log(bob.getYearOfBirth());
Javascript class object example
function StudentReport() { var grade1 = 4; var grade2 = 2; var grade3 = 1; this.getGPA = function() { return (grade1 + grade2 + grade3) / 3; }; } var myStudentReport = new StudentReport(); for(var x in myStudentReport) { if(typeof myStudentReport[x] !== "function") { console.log("Muahaha! " + myStudentReport[x]); } } console.log("Your overall GPA is " + myStudentReport.getGPA());
Javascript Cash Register example
function StaffMember(name,discountPercent){ this.name = name; this.discountPercent = discountPercent; } var sally = new StaffMember("Sally",5); var bob = new StaffMember("Bob",10); // Create yourself again as 'me' with a staff discount of 20% var me = new StaffMember("Peng",20); var cashRegister = { total:0, lastTransactionAmount: 0, add: function(itemCost){ this.total += (itemCost || 0); this.lastTransactionAmount = itemCost; }, scan: function(item,quantity){ switch (item){ case "eggs": this.add(0.98 * quantity); break; case "milk": this.add(1.23 * quantity); break; case "magazine": this.add(4.99 * quantity); break; case "chocolate": this.add(0.45 * quantity); break; } return true; }, voidLastTransaction : function(){ this.total -= this.lastTransactionAmount; this.lastTransactionAmount = 0; }, // Create a new method applyStaffDiscount here applyStaffDiscount: function(employee){ this.total = this.total * (1-employee.discountPercent/100); } }; cashRegister.scan('eggs',1); cashRegister.scan('milk',1); cashRegister.scan('magazine',3); // Apply your staff discount by passing the 'me' object // to applyStaffDiscount cashRegister.applyStaffDiscount(me); // Show the total bill console.log('Your bill is '+cashRegister.total.toFixed(2));
Search within Codexpedia
Custom Search
Search the entire web
Custom Search
Related Posts