Previous: JavaScript Intro and JavaScript Functions.
Use the Console to practice some useful JavaScript methods and built-in functions. Learn to differentiate between them. When are there parentheses? What goes inside them?
.lengthvarname.length;var words = "Hello, World!";words.length;var list = ["red", "white", "blue"];list.length;
.substring()varname.substring(3);varname.substring(3, 5);varname and continues either to the end of varname or to the second index supplied. Note that the first character in a string has an index of 0 (just like the first item in an array).
var wise = "Eat more fruit today.";wise.substring(4);wise.substring(9, 14);
.toString()varname.toString();var social = 321894567;var newSocial = social.toString();console.log(social + " and " + newSocial);social === newSocial;
parseInt()parseInt(varname, 10);varname is a string containing a number or numbers, an integer is returned. (10 means "base 10." Other bases may be used.)
If varname cannot be converted, the result will be NaN (which means "not a number"). parseInt("Hello", 10);varname is a string containing a number with decimal places, use parseFloat() to return a float. Otherwise, everything after the decimal will be lost.
Try this:var age = prompt("What is your age? ");var newAge = age + 10;alert("In 10 years you will be " + newAge + " years old.");newAge = parseInt(age, 10) + 10;alert("In 10 years you will be " + newAge + " years old.");
isNaN()isNaN(varname);var earth = "round";var circle = 360;isNaN(earth);isNaN(circle);
Math.random()var num = Math.random();var randy = Math.floor(Math.random() * 6) + 1;.floor vs. .round. When generating random numbers for gameplay, .floor provides a more uniform distribution than .round.)
var number = Math.floor(Math.random() * 100) + 1;var guess = prompt("Type a number between 1 and 100. ")guess = parseInt(guess, 10);if (guess < number) { confirm("Your guess is too low.
Try again?") };if (guess > number) { confirm("Your guess is too high.
Try again?") };
Math.floor()Math.floor(41.9999); // returns 41var num = 4.9;var newNum = Math.floor(num);console.log(num + " becomes " + newNum);
Math.round()Math.round(41.9999); // returns 42Math.round(41.4999); // returns 41var nums = 4.9;var newNums = Math.round(nums);console.log(nums + " becomes " + newNums);
Published under an MIT License. Copyright © 2015 Mindy McAdams. Fork on GitHub.