Web Development Guides and Tutorials

  • facebook
  • twitter
  • github

Javascript Basics 2 & 3

9th Sep 2015 12:37:23 Front End, Javascript by Kerry Owston

Javascript Basics 2 & 3

I have continued with learning about the basics of javascript by learning about handeling numbers and handeling if statements. I have built on my knowledge of javascript and learnt some new concepts. These are the new concepts have learnt.

Conditional statements

This is an example of a javascript conditional statemtent:

//Am i ready to learn OOP Javascript yet?
alert("find out if you're ready for javaScript OOP");

//course name and if completed
var basics1 = prompt("have you completed javascript basics yet?");
var basics2 = prompt("have you completed javascript loops arrays and objects yet?");

//tests to determin what is next for me
if(basics1.toUpperCase() === "YES" && basics2.toUpperCase() === "YES"){
 alert("you are ready to start learning javascript OOP");
} else if (basics1.toUpperCase() === "YES" && basics2.toUpperCase() === "NO"){
 alert("you're nearly there but there are still some basics to cover first");
} else if (basics1.toUpperCase() === "NO" && basics2.toUpperCase() === "NO"){
 alert("Get to know the all basics first before moving on to oop");
} else {
 alert("error in response");
}

Console Log

JavaScript code can be written in directly into the console

clear anything already in the log out of the way with the clear() funtion inside the console.

I’m not far more comfortable in the console.

Working with numbers

Javascript has a math object with many math methods 

It is possible to round a number, or set a number to always roundup or always round down to the next whole integer, going against principles of math.

Here are some examples:

// unlike other js the Math starts of with a capital letter
var num = 3.644545454

alert(Math.round(num));
alert(Math.floor(num));
alert(Math.ceil(num));

There are many more examples of the math object, another is the generation of a random number:

A random number will produce by default a number between 0 and 1 not including 1 a number with 16 decimal places like 0.6924692997708917.

Make this a whole number by passing the result of Math.random to Math.floor() or Math.ceil() multiply this number by another number (eg 7) to create a random number between 0 and 7. Add 1 so that number is between 1 and 10 by setting it to Math.floor() this will insure the number is rounded down to 10 and elimintes the chance of it being a 0.

//Create a random number
Math.random();

//Create a whole Random number
Math.floor(Math.random());

//Create a random number between one and 10 not including zero
Math.floor(Math.random() * 10) + 1;