JavaScript - The Basics - CodeAcademy.com


/ Published in: JavaScript
Save to your folder(s)

Basic information on JavaScript from CodeAcademy.com's JavaScript track


Copy this code and paste it in your HTML
  1. // logging to the console
  2. console.log("Studio Ghibli");
  3.  
  4. // asks user for a yes/no confirmation
  5. confirm("I love Studio Ghibli.");
  6.  
  7. // prompts the user for an answer
  8. prompt("What is the name of your favorite animation studio?");
  9.  
  10. // substring function usage to print Ghibli
  11. "Studio Ghibli".substring(7, "Studio Ghibli".length);
  12.  
  13. // function syntax at CodeAcademy.com
  14. var greeting = function (name) {
  15. console.log("Great to see you," + " " + name);
  16. };
  17.  
  18. // the function below returns a random number between 0 and 1
  19. var randomNumber = Math.random();
  20.  
  21. // checking the type of the received parameter
  22. var cube = function (x) {
  23. if (typeof(x) != 'number') return 0;
  24. return x * x * x;
  25. }
  26.  
  27. /*
  28. Code snippet showing how to wrap long lines of text and the hits method of Arrays,
  29. used to insert a new item in it.
  30. */
  31. var text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. \
  32. Duis in rutrum lorem.Akihiko Vestibulum ante ipsum primis in faucibus \
  33. orci luctus et ultrices posuere cubilia Curae;. ";
  34.  
  35. var myName = "Akihiko";
  36. var hits = []; // could also be var hits = new Array();
  37.  
  38. for (var i = 0; i < text.length; i++) {
  39. if (text[i] === "A") {
  40. for (var j = i; j < i + myName.length; j++) {
  41. hits.push(text[j]);
  42. }
  43. }
  44. }
  45.  
  46. if (hits.length === 0)
  47. console.log("Your name wasn't found!");
  48. else
  49. console.log(hits);
  50.  
  51. // do / while construction
  52. loopCondition = false;
  53.  
  54. do {
  55. console.log("I'm gonna stop looping 'cause my condition is " + String(loopCondition) + "!");
  56. } while (loopCondition === true);
  57.  
  58. // creating a random true/false variable
  59. var youWon = Math.floor(Math.random() * 2); // returns 0 or 1, that evaluates to true/false
  60.  
  61. // beware of this behaviour of JavaScript
  62. console.log(isNaN('42')); // prints false
  63.  
  64. /* simple example on using switch and logical operators */
  65. var message = "Totoro has just appeared in front of you. \
  66. Choose a present to give him (UMBRELLA, NUTS, OCARINA)";
  67. var action = prompt(message).toUpperCase();
  68.  
  69. switch (action) {
  70. case "UMBRELLA":
  71. var umbrellaMsg = "Are you waiting for your father? (YES/NO)";
  72. var umbrellaAct = prompt(umbrellaMsg).toUpperCase();
  73. if (umbrellaAct === "YES") {
  74. console.log("Totoro waits together until Neko Bus comes.");
  75. } else {
  76. console.log("Totoro goes away.");
  77. }
  78. break;
  79.  
  80. case "NUTS":
  81. var nutsMsg1 = "Have you planted some of it before? (YES/NO)";
  82. var nutsAct1 = prompt(nutsMsg1).toUpperCase();
  83. var nutsMsg2 = "Are you used to sleep early? (YES/NO)";
  84. var nutsAct2 = prompt(nutsMsg2).toUpperCase();
  85. if (nutsAct1 === "YES" && nutsAct2 === "YES") {
  86. console.log("Totoro comes to help you make these nuts into a huge tree.");
  87. } else {
  88. console.log("Totoro won't come.");
  89. }
  90. break;
  91.  
  92. case "OCARINA":
  93. var ocarinaMsg1 = "Can you play it? (YES/NO)";
  94. var ocarinaAct1 = prompt(ocarinaMsg1).toUpperCase();
  95. var ocarinaMsg2 = "Are you afraid of high height? (YES/NO)";
  96. var ocarinaAct2 = prompt(ocarinaMsg2).toUpperCase();
  97. if (ocarinaAct1 === "NO" || ocarinaAct2 === "YES") {
  98. console.log("Totoro won't do anything.");
  99. } else {
  100. console.log("Totoro will take you to the top of a huge tree to play together.");
  101. }
  102. break;
  103.  
  104. default:
  105. var invalidMsg = "Are you sure? (YES/NO)";
  106. var invalidAct = prompt(invalidMsg).toUpperCase();
  107. if (invalidAct === "YES") {
  108. console.log("OK.");
  109. }
  110. else {
  111. console.log("OK too.");
  112. }
  113. break;
  114. }
  115.  
  116. /*
  117.   examples on creating new objects using two different notation
  118. */
  119.  
  120. // object literal notation
  121. var emptyObj = {};
  122. // or
  123. var myObj = {
  124. type: 'fancy',
  125. disposition: 'sunny'
  126. };
  127.  
  128. //object constructor
  129. var myObj = new Object();
  130. myObj["type"] == "fancy";
  131. myObj["disposition"] = "sunny";
  132. // or
  133. myObj.type == "fancy";
  134. myObj.disposition = "sunny";
  135.  
  136. // one more simple example on objects. It is important to take a look at how to iterate over object properties
  137. var friends = {};
  138. friends.bill = {
  139. firstName: "Bill",
  140. lastName: "Gates",
  141. number: "(206) 555-5555",
  142. address: ['One Microsoft Way','Redmond','WA','98052']
  143. };
  144. friends.steve = {
  145. firstName: "Steve",
  146. lastName: "Jobs",
  147. number: "(408) 555-5555",
  148. address: ['1 Infinite Loop','Cupertino','CA','95014']
  149. };
  150.  
  151. var list = function(obj) {
  152. for(var prop in obj) {
  153. console.log(prop);
  154. }
  155. };
  156.  
  157. var search = function(name) {
  158. for(var prop in friends) {
  159. if(friends[prop].firstName === name) {
  160. console.log(friends[prop]);
  161. return friends[prop];
  162. }
  163. }
  164. };
  165.  
  166. list(friends);
  167. search("Steve");
  168.  
  169. // example on how to declare object methods
  170. var preferences = new Object();
  171. preferences.favoriteMovie = "Princess Mononoke";
  172.  
  173. preferences.setFavoriteMovie = function(newMovie) {
  174. preferences.favoriteMovie = newMovie;
  175. };
  176.  
  177. preferences.setfavoriteMovie("Spirited Away");
  178.  
  179. // the example above is very limited because setFavoriteMovie can only change the property of the preferences object
  180. // we can use the "this" keyword to create a generic implementation of the method
  181. var setFavoriteMovie = function(newMovie) { // declaring it even before creating the object
  182. this.favoriteMovie = newMovie;
  183. };
  184.  
  185. var preferences = new Object();
  186. preferences.favoriteMovie = "Princess Mononoke";
  187. preferences.setFavoriteMovie = setFavoriteMovie;
  188. preferences.setfavoriteMovie("Spirited Away");
  189.  
  190. // in the last example we could also define setFavoriteMovie as an preferences exclusive method:
  191. preferences.setFavoriteMovie = function(newMovie) {
  192. this.favoriteMovie = newMovie;
  193. };
  194.  
  195. // defining a JavaScript class
  196. function GhibliMovie(name, releaseYear) {
  197. this.name = name;
  198. this.releaseYear = releaseYear;
  199. this.director = "Hayao Miyazaki";
  200. this.getMovieDetails = getMovieDetails();
  201. }
  202.  
  203. function getMovieDetails() {
  204. return "Movie Name: " + this.name + " (" + this.releaseYear + ")\nDirectedy by: " + this.director;
  205. }
  206.  
  207. var whisper = new GhibliMovie("Whisper of the Heart", 1996);
  208. whisper.director = "Yoshifumi Kondou";
  209. alert(whisper.getMovieDetails());
  210.  
  211.  
  212. // the same class with its method defined internally to avoid name conflicts
  213. // the code to use the class remains the same
  214. function GhibliMovie(name, releaseYear) {
  215. this.name = name;
  216. this.releaseYear = releaseYear;
  217. this.director = "Hayao Miyazaki";
  218. this.getMovieDetails = function() {
  219. return "Movie Name: " + this.name + " (" + this.releaseYear + ")\nDirectedy by: " + this.director;
  220. }
  221. }
  222.  
  223. // in the above example, the method getMovieDetails is recreated everytime a new object is created
  224. // to avoid that, we can add the method to the prototype of the constructor function
  225. // the code to use the class remains the same
  226. function GhibliMovie(name, releaseYear) {
  227. this.name = name;
  228. this.releaseYear = releaseYear;
  229. this.director = "Hayao Miyazaki";
  230. }
  231.  
  232. GhibliMovie.prototype.getMovieDetails = function() {
  233. return "Movie Name: " + this.name + " (" + this.releaseYear + ")\nDirectedy by: " + this.director;
  234. }
  235.  
  236. // we can use a completely different syntax: object literals
  237. var whisper = {
  238. name: "Whisper of the Heart",
  239. releaseYear: 1996,
  240. getMovieDetails: function() {
  241. return "Movie Name: " + this.name + " (" + this.releaseYear + ")\nDirectedy by: " + this.director;
  242. }
  243. }
  244.  
  245. whisper.director = "Yoshifumi Kondou";
  246. alert(whisper.getMovieDetails());
  247.  
  248. // an instance such as whisper above is called singleton
  249. // we can use a function to define the same singleton
  250. var whisper = new function() {
  251. this.name = "Whisper of the Heart",
  252. this.releaseYear = 1996,
  253. this.getMovieDetails = function() {
  254. return "Movie Name: " + this.name + " (" + this.releaseYear + ")\nDirectedy by: " + this.director;
  255. }
  256. }
  257.  
  258. whisper.director = "Yoshifumi Kondou";
  259. alert(whisper.getMovieDetails());

URL: http://www.codecademy.com

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.