/ Published in: JavaScript
Basic information on JavaScript from CodeAcademy.com's JavaScript track
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
// logging to the console console.log("Studio Ghibli"); // asks user for a yes/no confirmation confirm("I love Studio Ghibli."); // prompts the user for an answer prompt("What is the name of your favorite animation studio?"); // substring function usage to print Ghibli "Studio Ghibli".substring(7, "Studio Ghibli".length); // function syntax at CodeAcademy.com var greeting = function (name) { console.log("Great to see you," + " " + name); }; // the function below returns a random number between 0 and 1 var randomNumber = Math.random(); // checking the type of the received parameter var cube = function (x) { if (typeof(x) != 'number') return 0; return x * x * x; } /* Code snippet showing how to wrap long lines of text and the hits method of Arrays, used to insert a new item in it. */ var text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. \ Duis in rutrum lorem.Akihiko Vestibulum ante ipsum primis in faucibus \ orci luctus et ultrices posuere cubilia Curae;. "; var myName = "Akihiko"; var hits = []; // could also be var hits = new Array(); for (var i = 0; i < text.length; i++) { if (text[i] === "A") { for (var j = i; j < i + myName.length; j++) { hits.push(text[j]); } } } if (hits.length === 0) console.log("Your name wasn't found!"); else console.log(hits); // do / while construction loopCondition = false; do { console.log("I'm gonna stop looping 'cause my condition is " + String(loopCondition) + "!"); } while (loopCondition === true); // creating a random true/false variable var youWon = Math.floor(Math.random() * 2); // returns 0 or 1, that evaluates to true/false // beware of this behaviour of JavaScript console.log(isNaN('42')); // prints false /* simple example on using switch and logical operators */ var message = "Totoro has just appeared in front of you. \ Choose a present to give him (UMBRELLA, NUTS, OCARINA)"; var action = prompt(message).toUpperCase(); switch (action) { case "UMBRELLA": var umbrellaMsg = "Are you waiting for your father? (YES/NO)"; var umbrellaAct = prompt(umbrellaMsg).toUpperCase(); if (umbrellaAct === "YES") { console.log("Totoro waits together until Neko Bus comes."); } else { console.log("Totoro goes away."); } break; case "NUTS": var nutsMsg1 = "Have you planted some of it before? (YES/NO)"; var nutsAct1 = prompt(nutsMsg1).toUpperCase(); var nutsMsg2 = "Are you used to sleep early? (YES/NO)"; var nutsAct2 = prompt(nutsMsg2).toUpperCase(); if (nutsAct1 === "YES" && nutsAct2 === "YES") { console.log("Totoro comes to help you make these nuts into a huge tree."); } else { console.log("Totoro won't come."); } break; case "OCARINA": var ocarinaMsg1 = "Can you play it? (YES/NO)"; var ocarinaAct1 = prompt(ocarinaMsg1).toUpperCase(); var ocarinaMsg2 = "Are you afraid of high height? (YES/NO)"; var ocarinaAct2 = prompt(ocarinaMsg2).toUpperCase(); if (ocarinaAct1 === "NO" || ocarinaAct2 === "YES") { console.log("Totoro won't do anything."); } else { console.log("Totoro will take you to the top of a huge tree to play together."); } break; default: var invalidMsg = "Are you sure? (YES/NO)"; var invalidAct = prompt(invalidMsg).toUpperCase(); if (invalidAct === "YES") { console.log("OK."); } else { console.log("OK too."); } break; } /* examples on creating new objects using two different notation */ // object literal notation var emptyObj = {}; // or var myObj = { type: 'fancy', disposition: 'sunny' }; //object constructor var myObj = new Object(); myObj["type"] == "fancy"; myObj["disposition"] = "sunny"; // or myObj.type == "fancy"; myObj.disposition = "sunny"; // one more simple example on objects. It is important to take a look at how to iterate over object properties var friends = {}; friends.bill = { firstName: "Bill", lastName: "Gates", number: "(206) 555-5555", address: ['One Microsoft Way','Redmond','WA','98052'] }; friends.steve = { firstName: "Steve", lastName: "Jobs", number: "(408) 555-5555", address: ['1 Infinite Loop','Cupertino','CA','95014'] }; var list = function(obj) { for(var prop in obj) { console.log(prop); } }; var search = function(name) { for(var prop in friends) { if(friends[prop].firstName === name) { console.log(friends[prop]); return friends[prop]; } } }; list(friends); search("Steve"); // example on how to declare object methods var preferences = new Object(); preferences.favoriteMovie = "Princess Mononoke"; preferences.setFavoriteMovie = function(newMovie) { preferences.favoriteMovie = newMovie; }; preferences.setfavoriteMovie("Spirited Away"); // the example above is very limited because setFavoriteMovie can only change the property of the preferences object // we can use the "this" keyword to create a generic implementation of the method var setFavoriteMovie = function(newMovie) { // declaring it even before creating the object this.favoriteMovie = newMovie; }; var preferences = new Object(); preferences.favoriteMovie = "Princess Mononoke"; preferences.setFavoriteMovie = setFavoriteMovie; preferences.setfavoriteMovie("Spirited Away"); // in the last example we could also define setFavoriteMovie as an preferences exclusive method: preferences.setFavoriteMovie = function(newMovie) { this.favoriteMovie = newMovie; }; // defining a JavaScript class function GhibliMovie(name, releaseYear) { this.name = name; this.releaseYear = releaseYear; this.director = "Hayao Miyazaki"; this.getMovieDetails = getMovieDetails(); } function getMovieDetails() { return "Movie Name: " + this.name + " (" + this.releaseYear + ")\nDirectedy by: " + this.director; } var whisper = new GhibliMovie("Whisper of the Heart", 1996); whisper.director = "Yoshifumi Kondou"; alert(whisper.getMovieDetails()); // the same class with its method defined internally to avoid name conflicts // the code to use the class remains the same function GhibliMovie(name, releaseYear) { this.name = name; this.releaseYear = releaseYear; this.director = "Hayao Miyazaki"; this.getMovieDetails = function() { return "Movie Name: " + this.name + " (" + this.releaseYear + ")\nDirectedy by: " + this.director; } } // in the above example, the method getMovieDetails is recreated everytime a new object is created // to avoid that, we can add the method to the prototype of the constructor function // the code to use the class remains the same function GhibliMovie(name, releaseYear) { this.name = name; this.releaseYear = releaseYear; this.director = "Hayao Miyazaki"; } GhibliMovie.prototype.getMovieDetails = function() { return "Movie Name: " + this.name + " (" + this.releaseYear + ")\nDirectedy by: " + this.director; } // we can use a completely different syntax: object literals var whisper = { name: "Whisper of the Heart", releaseYear: 1996, getMovieDetails: function() { return "Movie Name: " + this.name + " (" + this.releaseYear + ")\nDirectedy by: " + this.director; } } whisper.director = "Yoshifumi Kondou"; alert(whisper.getMovieDetails()); // an instance such as whisper above is called singleton // we can use a function to define the same singleton var whisper = new function() { this.name = "Whisper of the Heart", this.releaseYear = 1996, this.getMovieDetails = function() { return "Movie Name: " + this.name + " (" + this.releaseYear + ")\nDirectedy by: " + this.director; } } whisper.director = "Yoshifumi Kondou"; alert(whisper.getMovieDetails());
URL: http://www.codecademy.com