Before, when a website need some functionality, it rely on web server which the web server then return the webpage with new data. So netscape came about the idea of wanting functionality not relying on web server. So they contacted "Bredan Eich" which he was able to create JS in just 10 days. It was first known as "Livescript" and they microsoft reverser engineer the program and name it "Jscript". This differences create confuses then the european standardize the language and name it "ECMASCRIPT"(European Computer Manufacturers Association Script).
There will be no functionality on a website without "JS" For example: We can search for "Javascript" in chrome browser then under content, click "javascript" to enable it or not. If not allowed, it'll make website not function just normal static website will be render without any functionality. It even make us have ad-free website.
Well, the script is same has assigning a role and functionality just as use in a play for an actor to do some specific task. In web development, the script is "Javascript" and the actor is the "HTML ELEMENT". E.g: one actor can be "h1" while the other can be "p" element.
Unhide h1
1second delay
Unhide p
"h1" change text to "Hello"
"p" change text to "World"
This result to:
h1 => Hello
p => World
In this case, we've simply instruct our element or players what should be done. This is way that the scripting language works.
Javascript is an interpreted language. Other interpreted languages includes: Python, Ruby e.t.c We also have compiled languages which involves: Java, C/C++, Swift.
Javascript is supported across major browsers. Although, other language can be compiled to javascript and execute on the browser.
We'll be using chrome as our script writer environment.
So on chrome new tab page => click "view" => developer => Javascript console.
alert("Hello");
This will simply pop up the "Hello" on screen. But there is downside in using chrome console for writing "js" it doesn't support continuous writing of code across multiple lines, as soon as we hit enter, it execute the code which we can only stop that by holding on shift button then hitting enter key when we want to add more code in another line.
alert("Hello"); hold Shift then Enter button
alert("Again!");
This will execute the "hello" first then when we click "ok" it execute the second code which is "Again!"
Another way is to click "sources" on chrome => ">>" => "snippets" => Then we create new snippets then we name our script with anything with "js" as the extension. Inside the file, we can write as many lines as we wish and it'll only run only when we click the play button.
alert("Hello");
alert("world!");
This differs from how console works, console is design to test a line of code but the snippet code is meant to execute the entire code when done writing them.
There are some proper keywords that javascript accept, we have to provide these proper keywords for it to function as we want. We can learn some of these keywords simply by visiting documented site like MDN DOCS . Here we can get acquainted with various valid "js" keyword and we can as well search for them. E.g we can search "alert" which will bring the details usage of it. By this, we'll be able to see the full version of the "alert" which is "window.alert".
alert("Hello");
As conventions implies, it is best to not keep any space between the code. So by convention, no space between the alert and the bracket till the semi-colon. Follow this link to learn more about art of writing uniform and universal code for readability. Neat code
alert("Hello");
The browser recognize the actual keyword which is the "alert" and which part of the line is to be display. The thing we add to make the browser know what to display is the quotation(""). So everything the quote enclosed get interpreted by the computer as a string so that it get filter out of the code and gets interpreted as text.
This a way to classify data to tell the computer how the program intends to use the data. In the case of the alert("Hello"); We simply want the "Hello" to be display in popup. A string is a text that's not meant to be interpreted as a code or just a string of character.
As a result of having different symbols from the alphabet we use to code then no special symbol is needed to tell the computer that we have a number. The number can simply be type.
This simply describe data that is either "True or False"
This is a keyword that let us know the kind of data type we are using.
typeof("Hello"); => "string"
typeof(332); => "number"
typeof(true); => "boolean"
Variables is highly important in programming, without it our data will be lost. Let's take for an example by using another "js" keyword which is "prompt".
prompt("What is your name?");
When the code is executed and our name is asked and it was provided, the name will be display in the console but we won't be able to retrieve it. Because it's not committed to the memory.
Variable store data and it can be use to retrieve any data stored. Example:
In the above code, "var" keyword which is shorten for "variable" is used to create our variable which we named "yourName". This is then committed to the memory and can be retrieve for use. In the chrome console, we can just type the "yourName" and it'll give us the value it contains which is "ola". "yourName" is like a label on the data which the data is "ola" in this case. The "var" is a keyword just as "alert and prompt". It recognize that we're creating a new data container. And the container is label the name that follows the "var", which in this case is "yourName". We then set the variable to be equal to a value which in the case is "Ola". Now, every time we refer to "yourName", the computers knows we're referring to the string "ola". So basically, whenever we start with keyword "var", the computer knows is job is to help us create a box which we'll then label with any name that comes after the keyword "var". So after the equal signs lies the string that we place inside the box.
The full meaning of "var" is variable, which means the data place inside it can be alter. For example;
In this case, the computer we simply find the box with label of "yourName" and it simply assign it different string we provided. Note: We don't need to include the keyword "var" again. Var is to be use only when constructing a new box to contain our data. Or when constructing a new variable. So when we decide to use the variable or when we decide to change the variable, we don't need to use the keyword "var" anymore.
This is act of making our code versatile in functioning by combining different keywords.
In this case, "var" will create a variable named "yourName" Then it'll pop-up the value we stored inside which in this case is "Olatunji". More examples:
We simply create a variable named "tutorName" with "Olatunji" as the value, we then create another variable named "yourName" with the value assign as "prompt" which ask the user for the value. The prompt will pop up just as alert. The prompt will ask us for name in this case and the value we provide will be stored inside the "yourName" variable. The the alert will be be display as this => My name is Olatunji, welcome to my course ola! (whatever value we provided).
This will display as "Your latest score is 5"
Take for example, we have rice in bowl a and we have beans in bowl b, think of making bowl b contain rice while bowl a should contain beans instead.
In this instance, to make the two bowl interchange value, we simply introduce a new variable which we called "bowl_c". Then we assign it the value of "bowl_a", then we assign "bowl_a" to hold value of "bowl_c" then finally, we assigned "bowl_b" the value of "bowl_c". We now have rice in bowl_b and beans in bowl_a respectively.
This enable us to keep practice of best standard way of putting down codes
To clear console, we simply hold down command + K on mac. On window is control + K.
This clear the console but the content will still be available. So to clear all the stored data, we'll do a hard clean.
click and hold reload icon. Then choose Empty cache and Hard reload.
This completely wipe off the stored data from the memory,
We can actually name our variable anything that pleases us but it's best to stick with meaningful names.
var yourName = "Olami";
With this, we ensure the name is meaningful and not jargons. This makes retrieving easy.
var myvar = "Olami";
This is valid, js allow us to create a variable that contains keyword.
var my123 = "ola";
This is allowed as it doesn't start with a number
var abc123$_ = "ola";
Variable name contain alphabet, numbers, dollar sign. No other symbols are valid.
var my_name = "ola";
This is valid.
var userScoreFinal = "ola";
This is valid as is widely refers to as "camel casing" First words is not capitalized and every subsequent one is capitalized.
var var = "ola";
This is not valid way to give a variable a name as we provided a keyword that is recognized by "js" to create a var.
var 123 = "ola";
Variable name cannot begin with a number.
var my name = "ola";
Variable name cannot be separated with spaces. Reason is because, js treat the space as if we want to write another different bit of code. The first word that comes after var is treated as the name of our variable, so in our case now, the variable name is "my" and it does not know what to do with the extra name
var my-name = "ola";
This is not valid.
This is done by combining strings together with plus sign.
"d" + " " + "c"; => d c
The above code is simply concatenated into a single string
alert("Hey " + "you");
This simply display Hey you because we add a extra space after the "hey "
alert("Hey" + " " + "you");
Unlike before, we simply add the space more explicitly by making a string around empty space. This gives same outcome.
var message = "Good morning";
var actions = "today";
alert(message + " there, " + actions + "!");
The length feature in "js" allow us to know the number of character in a string. E.g: "word.length" which give us the number of character in a string. Example:
var figure = "one";
figure.length => 3
Here, we'll do tweet calculator that'll limit the number of character we can enter and give us feedback message om the number of character we've written and the characters remaining.
var characterThreshold = 148;
var message = prompt("Enter your character");
var characterAmount = message.length;
var characterLeft = characterAmount - characterThreshold;
alert("You have written " + characterAmount + " characters." + " You have " + characterLeft);
The above code can be chunk down to smaller line but clarity approach is simply the best. The code is set as maximum to 148 characters, then we prompt user to enter message. We then create a container to store the amount of message the user enter(characterAmount). Follow by the characterLeft which is simply a calculation that subtract the "characterAmount and the characterThreshold". We then give the user back details feedback.
We'll be learning about slice feature in this chapter. Slice allow us to slice and dice strings to separate them into individual characters. Example:
var country = "Nigeria";
country.slice(0, 3)
The above code will be reduce to "Nig". The value we provide inside the slice work exactly as range that is; the second digit provided which is 3 in this case will not be involved. Hence "Nig". Program start counting at position 0. So "N" is at position 0. 0 is the lower boundary while the 3 is the upper boundary. We can get the amount of string we'll get back simply by subtracting "upper boundary - lower boundary".
We'll be creating a counter that'll chop off character that exceed limit set and it'll only alert us only the character that is well in the limit set.
var message = prompt("Enter your message here:");
alert(message.slice(1, 5));
With the above code, we've limit the number of message character to enter to a particular limit using slice and in case, we provide a value between range of 1-5. Which means, any character above provided value will not be shown. With the conditioned code above, if we provide for example: "Chill"; The outcome will be "hill". So we always get back "upper boundary - lower boundary" amount of character. So in this case[5-1], we got back 4 character left
Here we'll create a robust counter that'll tell user what they enter and the amount of characters. Which then reduced it to the minimum threshold set telling the use the allowed threshold character.
var message = prompt("Enter your character");
var reducedMessage = message.slice(0, 5);
var characterAmount = message.length;
var characterLeft = characterAmount - characterThreshold;
alert("Here is what you've written " + message + ", which is of size " + characterAmount + " characters " +
". Here is the minimal version allowed " + reducedMessage + " which is of size " + reducedMessage.length);
The above code set does show the overall message enter by user and also tell user the amount of characters enter, it also went further to chunk it and show the user what the message is reduced to and the amount of characters now left as the minimal version allowed.
We can change string text to any case in javascript.
var name = "ola";
name = name.toUpperCase();
name = name.toLowerCase();
This change the string text to capital letter => "OLA". Saving it to the variable "name" makes it callable again without losing the data. The case can also be in lower case which is what we did in the third line of code. => "ola"
Create a prompt asking user to enter name and give them feedback of "Hey + what they entered.". Make first letter a uppercase and the rest in lowercase. Combine "length and slice". Don't use special method. Also, try to prevent a bug that might arise which is when user type in mixture of uppercase and lowercase letters.
var name = prompt("What is your name?").toLowerCase();
nameFirstLetter = name.slice(0, 1);
nameFirstLetter = nameFirstLetter.toUpperCase();
alert("Hello, " + nameFirstLetter + name.slice(1, name.length) + "!");
At first, we ask user for name then we prevent the bug that might arises from user end when he provided mixture of both upper and lower case letters instead. So we mandate all strings to be in lower case. In the line two, we used slice method to isolate the first letter. Then in the third line, we turn it to capital letter. On the fourth line, we then alert the user the feedback. So, if user enter "oLA". It'll give back "Ola" as the popup feedback created by the alert keyword.
In js, we can add, subtract, divide and so on. For examples:
The addition gives back "7", subtractions gives "3", multiplications gives 15 while the modulo gives back the remaining number which in this case is "2". The modulo is the weird one among all of them as it only gives back the remainder of the number we use it on. We use the modulo operator to show whether a number is "even or odd". e.g 45 % 2. If we get back 0, the number is "even", if the modulo end up as not equal to 0 then we have "odd" number.
var value = 5 + 6 * 2
The expression follows the "BODMAS OR PEMDAS" rule. It multiply first then add. The above expression will return "17". This follow a maths rule that says "We must first multiply and divide before we add or subtract." This works exactly the same way in programming. We can get different value we want if we add parentheses to prioritize what should be done first. E.g;
var value = (5 + 6) * 2
This first operate on the numbers inside the bracket before multiplication. Which result to "22".
Note; Despite knowing the order of operations, it's always best to add parentheses around numbers to make it distinctively clear. E.g;
var value = 5 + (6 * 2);
This makes the order be visible and clear enough.
Here, we'll be working with an establish formula of Dog Age To Human Age. Which is;
humanAge = (dogAge - 2) * 4 + 21;
So here, we'll create a prompt asking the user to enter their dog age and then we'll give them an alert telling them their dog age
in equivalent of human age using the above formula.
var dogAge = prompt("What is your dog age?");
var humanAge = ((dogAge - 2) * 4) + 21;
alert("Your dog is " + humanAge + " years old in human years");
This give back the dog age years in human years. If enter "2", we'll get back 21 years old as dog age in human years. We added extra parentheses to make our expression clearer.
We've seen operators of normal maths. Here, we'll be expose with one that exists only in programming. For example;
The above will return back "3" as the value "x"
In programming, there is a better way to make an increment work.
In most programming "x + 1" is same as "x++". The above code result to "3" as the result as well.
The decrement also works in similar way.
"x - 1" is same as "x--". The above code result to "1" as the result as well. So the previous value of "x" which is 2 will be minus by 1. This is the decrement expressions.
"x + 3" is same as "x += 3". The above code result to "5" as the result. Other operator works same way.
"x += y" is same things as "x + 3". That is the value of previous x which is 2 plus the value of "y" which is 3. The above result to "5". This also work with others operators.
Without functions, coding will be a complicated task to do. Functions reduce the workload in coding. For example;
The above codes will have to run for every time we need to perform the specific type of task. Which is boring. Writing every line of the code repeatedly anytime we want to perform such task.
Instead of going the painful way of repeating code, we can simply package the above set of instructions into a single package that we'll attach a name to. Functions allows us to create a series of instructions, package it into a block of code by adding curly braces as the boundary. For example;
We've successfully package the instructions under a single package known as functions which we've given a name. Which the name in this case is "commandButton". We first indicate we're creating a function by first writing the keyword function, follow by the name then a set of parentheses. Then follow by curly bracket and the block of codes that lies between the curly brackets that we want to executed. So next time we want to run the code. We simply call the function. For example;
We simply type the name with the bracket to call the function which save of stress of having to type all the code out again.
We use the var keyword to create a new box which we labelled as myName. Then we put in a value inside the box.
Function work similarly to variable. We used function keyword to indicate that we're creating a function. Then we attached a name to it commandButton a name to recognize the block of codes. Then we put in all the instructions we want to carried out anytime we call the function commandButton
This is where we involved the function keyword, the name commandButton, the bracket (), and curly braces {}. No semi-colon at the end of the curly bracket.
All we have to do when we want to call our function is to just write out the function name with the parentheses. Ending with the semi-colon. Then computer will look through where the functions was created and it'll carry out the instructions inside the curly braces.
Inside chrome, we can simply change the alert keyword to console.log by pressing command + f on mac and control + f on window. Then press the A & B icon then the replace all button to replace all the alert keyword to console.log. Console.log is meant for the developer usage alone while alert depict an information to the user
Practicing with karel robot. We'll be using stanford.edu for our function practices.
Previously on our introduction to the concept of functions, we discussed about the low type of functions which is such a way of packaging set of instructions which we can execute at once by using the name of the function. Functions is classify into three different way. The low level one is the one we already exposed to in the previous lesson. We will be discussing the medium level in this section.
function getBooks(books) {
console.log("leaveHome");
console.log("moveRight");
console.log("moveUp");
console.log("moveRight");
console.log("Buy " + books + " books.");
console.log("moveLeft");
console.log("moveDown");
console.log("moveLeft");
console.log("enterHome");
}
getBooks(2);
We've simply provided an input for our function unlike Previously that we did'nt input anything in the parentheses. In this instance, we've provide an input that will go into this functions which can be use within the series of instructions. We can now pass in data when we call the functions. The console.log can additional output the number of book which in this case will be Buy 2 books.
Creating and Calling in this type of function now look like this;
var booksCost = 2.5;
function getBooks(books) {
var cost = books * booksCost;
}
getBooks(2)
So now, depending on the numbers of books we want the robot to purchase. We can now calculate the total cost. Unlike previous function that we left the function empty, we now give the function the value of 2 which will be bound to the name books we provided when creating the function. So now that we provided 2 as the input, we now have a variable books that's of value 2 and then we can calculate the cost which we set to 2 * 2.5[books * booksCost] which is 5. So the cost is 5 naira. With this, our robot work in more advance way than before. It now knows how many books to get and also the cost it'll spend.
Change the books to money. Then use it to calculates the number of books the robot will buy. For instance, if we gave the robot 6 naira and a book cost 2.5 naira. So the task is to write out the code to calculate how many book the robot will be able to get. So in this case 6 / 2.5 which is 2.4 round the number down to a whole number because the robot will not be able to buy a book for the remaining cent of 0.4 but it can only get 2 books in this case.
var booksCost = 2.5
function getBooks(money) {
console.log("leaveHome");
console.log("moveRight");
console.log("moveUp");
console.log("moveRight");
var numberOfBooks = Math.floor(money / booksCost);
console.log("Buy " + numberOfBooks + " books.");
console.log("moveLeft");
console.log("moveDown");
console.log("moveLeft");
console.log("enterHome");
return money % bookCost + " as the change";
}
getBooks(26);
So the money will provided when we call the function which is 26 will be pass to the money we provided when we created the function getBooks
Then we divided it by the bookCost.
The above will result in 26 / 2.5 which is 10.4 but the Math.floor help us round it down to 10
because we can't get 0.4 naira book. Also at the end, it return an output of
Create function that tells how many days, weeks and months we have left if we live until 90years old. It'll take current age as the input and console.logs a message with our time left in this format. You have x days, y weeks and z months lefts. where x, y and z are replaced with the actual calculated numbers. Assume 365days in a year, 52 weeks in a year and 12 months in a year.
function remainingLifeStats(currentAge) {
var xDays = 365 * (90 - currentAge);
var yWeeks = 52 * (90 - currentAge);
var zMonths = 12 * (90 - currentAge);
console.log("You have " + xDays + " days, " + yWeeks + " weeks, and " + zMonths + " months lefts." )
}
remainingLifeStats(89);
The above code will return You have 365 days, 52 weeks and 12 months lefts. We create a function that takes in our currentAge. We then do maths calculation by taking out the maximum age which is 90 from our current age to get the remainingAge So we utilize the remaining age (90-currentAge) and we multiply days, weeks and months respectively in different line. We get back the remaining days, week and month left.
In the last section, we look at function that are able to take in input and use that input inside the function to do some calculation or to use it as part of the code. In this part, we'll be expose to more complex way of writing function. This type of function are able to give output. So for example, in the previous scenario we took money as an input to the function and then use it to calculate the number of books we can purchase and at the end of the code, we use the keyword return to specify that the function in addition to being able to take inputs, it can also give an output. Hence return money % bookCost + " as the change. This mean we're getting the remainder of how much we've spent to buy the book.
The first gives back 2 because 3 goes in 8 just two times with remainder of 2. With the modulo in use, it'll give back only the remainder. While the second example gives back 3 as the remainder. Because 6 only goes in 9 just one time. So the modulo is only concern about the remainder. Modulo only give back the remainder of division.
This is how we create function in a complex function type. We give in an input which is money when creating our function getBooks. We then make it capable of returning an output by using a return keyword. Which we did some calculation. We will then make use of the output when we call the function.
This is how we call function in a complex function type. We've now gotten hold of the getBooks function we created and we put it inside a variable that we name change. We provided the value of 4 to the function getBooks. The value will replace the money input we provided when creating our function. It'll then be use to do the calculation. That is return 4 % 1.5. So the modulo we now be 1 as the remainder. Which we then store inside variable change. Then we console.log it to give us the output of 1. If we did not have the return 4 % 1.5 line when creating the function getBooks then calling the function getBooks only execute the function without getting an output back.
With this type of function in this section, we're able to use a number of functions inside another functions. For example:
var booksCost = 2.5
function getBooks(money) {
console.log("leaveHome");
console.log("moveRight");
console.log("moveUp");
console.log("moveRight");
var numberOfBooks = Math.floor(money / booksCost);
console.log("Buy " + numberOfBooks + " books.");
console.log("moveLeft");
console.log("moveDown");
console.log("moveLeft");
console.log("enterHome");
return money % bookCost + " as the change";
}
getBooks(26);
function getBooks(money, bookCost) {
console.log("leaveHome");
console.log("moveRight");
console.log("moveUp");
console.log("moveRight");
console.log("Buy " + numberOfBooks(money, bookCost) + " books");
console.log("moveLeft");
console.log("moveDown");
console.log("moveLeft");
console.log("enterHome");
return booksChange(money, bookCost);
}
Creating Separate Functions
function numberOfBooks(givingCash, costPerBook) {
var bookQuantity = Math.floor(givingCash / costPerBook);
return bookQuantity;
}
function booksChange(givingCash, costPerBook) {
var remainingChange = givingCash % costPerBook;
return remainingChange;
}
console.log("Here is your change of " + getBooks(4, 1.5));
We've make the code even more robust by adding in function in function with the implementation of return keyword. We created two separate functions. The first function is reduce the two line of code in our previous codes => var numberOfBooks = Math.floor(money / booksCost); and console.log("Buy " + numberOfBooks + " books."); Instead we create a different function to do the logic which we then return and we then utilize it inside our getBooks function. We must add the exact two values the getBooks have when using the function we created differently inside the getBooks. We are able to use the separate function we created numberOfBooks inside getBooks because of the return keyword we added inside the numberOfBooks. The return keyword make the function return an output. So getBooks will now be the activator of the function.
For the second function, same things as the first. The difference is that, we console.log the first function inside the getBooks while we return the second function which is booksChange inside getBooks. This now makes getBooks to be the activator of the output after we provided the specific amount we want. In this function, we've explicitly add two value to make the code even more cleaner.
getBooks now have two value => money, bookCost. The code run line by line after we called the function getBooks. When it gets to console.log("Buy " + numberOfBooks(money, bookCost) + " books") it'll look for the separate function of numberOfBooks and it'll trigger the block of code in it which will now be 2 in our case because of how we structure the code inside the numberOfBooks which is 4 / 1.5 which result to 2 because of the Math.floor we use on them, it reduce the equation to 2. [it round it down from 2.66 to 2]. The value is fill in as whatever value we provide for the getBooks.
The code keep running till it stumble upon the return booksChange(money, bookCost). It look for where we created the separate function and it trigger it. The getBooks now feeds in the separate function with the value we provided. It'll now be 4 % 1.5 which give us its remainder 1. It is able to feed in the amount we provided for the getBooks because when we give the amount, the first one will be for the first one which is money while the second one will stick with the other one which is bookCost. Which align exactly with what we provided for the two separate function when using them inside getBooks.
We'll be creating a bmi calculator using weight / height^2. The function should be able to take in two input and give us result. For example: var bmi = bmiCalculator(72, 1.8); So 72 / height * height should return 22.222. Round the number up. So final result should be 22 in this instance.
We created bmiCalculator and we give it ability to accept two values when calling it later hence we provided to input which are weight, height. We then create a variable named bmi which we stored our calculation inside. Instead of using the simple approach by just multiplying height * height to give us the height square. We simply use a method which is Math.pow(height, 2). It accept two value, the first will be what we want to work on, in this case height and the second value will be what we want to raise the first to. We then use return keyword so to later use the output when we call the function. We use Math.round() on the variable bmi which we stored our calculation inside. Math.round() simply round up number to the nearest whole number unlike the Math.floor that do round it down. Math.round() approach is mathematically correct for example: Math.round(2.5) we simply be 3. It will round up number in as much the number after the decimal is 5 upwards.. So in our case. The result will be 22
Here, we simply create different function named calcBmi. We then add return keyword at the end of it to make its output usable in our bmiCalculator function. We then use it in our main function which is bmiCalculator adding return keyword to it. Making it useable inside our main function by passing in the output to our main function. So now, when the code get to the line return calcBmi(weight, height) after calling the function bmiCalculator. It'll look for where we created the calBmi walkthrough the calculation in it line by line by passing in the value we provided for the bmiCalculator to the calBmi. Then we get back 22.
In this section, we'll be discussing about Math.random(). Unlike the previous function we've talked about, it does not not take in input. This function generate a random number. And the random number they got generated is a 16 decimal place number. For example; 0.2342985423478235 it can be any number between 0 and 0.9999999999999999 it never reaches one. The random function allows us to generate up to a billion random numbers. The Math.random() function returns a floating-point, pseudo-random number in the range from 0 inclusive up to not including 1. We can scale it to desired range. Check for more about this function on MDN DOCS. The reason why it's refers to as pseudo is because a computer is essentially a whole bunch of switches, just a giant box of many billions os switches, and depending on whether the switches is on or off we essentially got 1 or 0 and it's through these 1 and 0 it does all the computing work. But it's not very good at being random. Although, in nature, it's easy to get randomness but in computer, because of is deterministic process, it's not easy to get true number. So people have come up with various ways which include mathematical formulas to get this nonrandom computer to generate what look like random numbers. This video explain it better Khan Academy
Let's demonstrate random number by building a dice game.
var randomNumber = Math.random(); randomNumber = randomNumber * 6; randomNumber = Math.floor(randomNumber) + 1; console.log(randomNumber);
We stored our random number inside randomNumber. For this example, let's assume that the random number we got was 0.2342985423478235 In the second line, we turned what was store in the randomNumber by repeating it again but this time without var keyword at the beginning. We set in new value. That is randomNumber * 6 which now look like this 0.2342985423478235 * 6 This gives us 1.406. We proceed further by assigning new value for randomNumber. We set used Math.floor to round down the 1.406 and we added 1 to it to make sure we did not get a number that is 0 because we know that a dice number does not include 0 and by adding the 1 also makes sure that the number stay at 6 for maximum. So now, instead of generating 0, 1, 2, 3, 4, 5 it'll make sure it start with 1 and end with 6 that is 1, 2, 3, 4, 5, 6 will now be the random number that'll be generating.
Build a love calculator that accept two prompt of two lovers. Give them back their love score back. Make it between 1 and 100%. The pop-up will appear as this: "Your love score is 58%".
prompt("Enter your name: ");
prompt("Enter your name: ");
var loveCalculator = Math.random();
loveCalculator = loveCalculator * 100;
loveCalculator = Math.floor(loveCalculator) + 1;
alert("Your love score is " + loveCalculator + "%");
We created two prompt that pop-up to ask for the lovers name. We then created a variable loveCalculator setting the value to be of random number using javascript function Math.random(). We then set the current value of our loveCalculator by multiplying the previous value which is the random number stored in it before by 100. We then set the value again by using Math.floor to round down the number then we add 1 to the number to make sure our number started from 1 and ended at 100. Then we use alert keyword to give the users feedback.
In the last section, we created a basic structure of love calculator using randomization. Here, we'll be working on making it more robust by giving the love calculator more custom message based on what they got as there love score. We'll do this by checking what they score and responding differently base on that score using Conditionals. This allow us to use the keyword IF & ELSE to evaluate a statement. The IF gets trigger when code condition is met. If not met, the ELSE keyword gets trigger. This is known as Control Flow. We are controlling the flow of our code depending on the current conditions. Example:
Using conditional statement, our task is to create a set of instructions that will only congratulate us if we have 6 as our number when run. Otherwise, it'll show us what is left to reach the maximum number which is 6.
In the above code, we simply simply created a variable named randomNumber. We set the value to a random number which then multiply by 6. We rounded it down using Math.floor then added with 1. This get rid of decimal number and give us whole number and sets the number from 1-6 We then use Control Flow to control the usage of the outcome of each random number we will be getting. So first condition is to check if we get the exact number which is 6. We will congratulate the user. Anything below 6. We set another condition which is telling the user what is left to get to the lucky number which is 6 and we asked them to try again until they get the lucky number.
Here, we'll be adding more feature to our love calculator to make it more robust. We add custom message to condition the feedback. If the percentage is greater than 70%. We'll give the couples an encouragement feedback. If otherwise, we'll return just the lover scores.
The (greater than)> symbol, lesser than <, and three equal sign symbol === are known in programming as comparatives because they allow us to compare two different values. The === check to see if the left hand side is equal to the right hand side. The !== check whether the left hand side is not equal to the right hand side. The > check if something is greater than something else. < lesser than check whether something is lesser than something else. Also we have <= lesser or equal to and >= greater than or equal to. These comparatives gives our conditionals, like IF & ELSE more flexibility.
On usage, we might come across people using == instead of ===. There is a huge different between the two equals sign and the three equals sign For example:
If we check for the type of data type of each of the variable that is typeof(a) we'll get back number as the data type. The second one typeof(b) is string. Using === to check if a is equals to b will simply give us back the condition inside our else because 1 is not equals to "1". That is number is not equal to strings. They are of two different data types although they are both 1 but === checks for both Equality and Data types. Since the data types are not the same, we'll get back Not true in this case.
If we check for the type of data type of each of the variable that is typeof(a) we'll get back number as the data type. The second one typeof(b) is string. Using == to check if a is equals to b will simply give us back the condition inside our if because 1 is equals to "1". That is number which is 1 is equal to strings. which is "1". Although, They are of two different data types. == checks only for Equality Since they are equal to each other the == triggers "On point". It does not care about data types
In this section, we'll be learning about how we can combine comparatives. We have three basics types of comparatives; Two Ampersands for AND &&. Useful for whether condition one is true and condition two is true. Second one is PIPE || OR. This check for if either condition one is true or condition two is true. Finally, the third one is NOT !. Which is use to denote the opposite of something.
Here, we'll be adding even more flexibility to our app by using combining comparators.
In addition to the previous code. We added more if statement and combining comparators. The first IF checks for whether the love score is above 70. The second one checks for two instances. Whether the score is greater than 30 and also 70 as the maximum. So 70 score and below. The third IF check for score that is 30 and below.
In this section, we'll focus on building a logic to tell if a year is a leap year or not. A normal year has 365 days, leap years has 366 days with an extra day in february. The logic here is: A leap year must be divisible by 4. If not divisible by 4 it already indicate that the particular year is Not a leap year. If the year is cleanly divisible by 4 then, the particular year will be eligible for further test. The next step to further test the year is; After being divisible by 4, it must not be divisible by 100. Then it'll be a leap year. If cleanly divisible by 100 we go to the last option which is The year being divisible by 400. If cleanly divisible by 400 then, it's a leap year, if not divisible by 400, it is Not a leap year. Check leap Years for more information.
We created a function that takes in an input isLeap(year) so when we later call the function, we'll have to provide a year for the input. Firstly, We check if the year is is cleanly divisible by 4. If not, we concluded that the year is not a leap year. Secondly, We check whether the year is cleanly divisible by 100, if not, we concluded that the year is a leap year. If cleanly divisible by 100 then the third step. Thirdly, Inside the previous if, we test again using another if statement to test if the year is cleanly divisible by 400, if true, we say it's a leap year, if not, we concluded it as Not leap year.
In this section, we'll be learning about ways we can simply coding with the help of arrays. Previously, we elongated on usage of variable, but there is some limitation to using variables as it brings about repetitive in our code. Previously, we've been exposed to storing data in variables. But we've only been able to store a single piece of data, e.g; var a = "apple" var b = '123' So we've seen we can store different data type. Now, we'll be expose to how we can store collection of related items into the same container or variable. So Array. For example; let's assume we have a single piece of data, an orange instead of storing a single orange into a variable, we can also store it in an array. Array is a collection of an item that are related, and they can be stored together into the same container or the same variable. Syntax look like this var oranges = ["orange1", "orange2", "orange3"]. So we set our variable oranges to equal bunch of data which we then enclose inside square bracket. Data inside are separated by commas. To retrieve data from this array goes like this; var myOrange = oranges[1]. So we use name of the array setting bracket and providing the position we wanted to retrieve using square bracket. This simply retrieve orange2 because computer start counting at 0. So same goes for programming. We can also get use the length on array. oranges.length; This gives us back 3. It counted the number of items inside the array. Also, we can use the function includes() to find out if an array includes a particular item. For example; oranges.includes("orange2"). This we check if orange2 is in the array, if it's in the array, we get back true. If not, it'll return back false.
Create a prompt that ask for a guess name then check to see if the provided name is on the guest list, if available, show the guest Welcome! If not on the list show the user record not found.
We created a variable name guestList which contain an array of names we invited for the seminars. So on entry, we'll ask each visitor to give out their name, which we store inside the variable guestName. We then use conditional using the condition by checking the guestList against the provided name the visitor provided using the function includes. We feedback Welcome! if the name provided is on the guestList. If not, we give back Record not found.
In this section, we'll be building a game known as fizzbuzz. Counting number from 1, when it get to number that is divisible by 3, it'll replace the 3 with fizz. When we get to number that is divisible by 5, it'll instead replace it with buzz. And finally, getting to number that is divisible by both 3&5 it'll replace the number with fizzbuzz. Final result looks like this [1,2,"fizz",4,"fizz",7,8,9,10,11,12,13,14,"fizzbuzz".....]
To solve this, we'll first figure out a way we can write a code that print out a sequence of numbers starting from 1 and every single time we run the code the next number gets called out.
We can manually include the number in our output variable but we chose to use push to add the number to our output. Our output now looks like this [1,2,3]
A push tend to add item to an array and it tends to do that by adding the item to the end of the array. It does not
A pop basically delete item off array. E.g arrayName.pop which takes the last item in the array and it'll remove it completely from the array.
Instead of writing output.push every single time and adding the next number on in our console, we'll create a function instead in our snippet
We created variable output which we make an empty array, we created another variable which we name count. We set the value as 1 to make sure our counting start from 1. We created function name fizzBuzz within which we added our block of code. We use push to add the count value to our array output. We then make the count an increment that is count++ which simply means count = count + 1. So now, we hit the play button in our snippet then we call the function fizzbuzz() inside our console. For every time we call our fizzbuzz function, it keep adding new number with an increment each time we run the function. Final result looks like this [1,2,3,4,5,6...] command + k to clear console
Now, instead of counting 3, our code should return fizz instead. Instead of 5, we should get back buzz. And finally, when we get to number that is divisible by both 3 & 5, we should get back fizzbuzz.
From the continuation of the previous steps which we created a variable named output which we left it as an empty array simply by setting the value as [ ] empty bracket. We then set the count to 1. We name the function fizzbuzz. Our order of operation matters a lot which is we first check for both number 3&5. We use % modulo operator to make sure we get back the remainder. So for every time we run our function, if the count is divisible by 3 and the remainder is 0 and also we add ampersand && to check for two condition. So if the count is divisible by 5 and also returns back 0. Only when the both condition is met, we will get back fizzbuzz. We follow the first condition with else if. So if count divisible by only 3 and the remainder left is 0, we get fizz. same goes for the other else if. So if the count is divisible by 5 and what is left is 0, we get back buzz. Otherwise, we use else to continue the counting. count++ makes sure the counting keeps increasing. We then console log the output. Then we hit play in our snippet then we call the function fizzBuzz() in our console. So when one condition is met, it'll skip the rest conditions, hence the reason why the other is important.
In this section, we'll create a game that is base on selecting a random name to buy an item like ticket. So we will do this by creating a function and anytime we call the function, it'll select random from an array we provided.
we created a function which we name ticketBuyer, we pass in an input of array named names. the input of array contain the names we want to shuffle to know who we pay anytime we call our function. We create a variable named numberOfNames we set the value as number of person in our arrays using the length on the array names. We created another variable which we named randomPositionOfNames. We set the the value by using Math.floor to round down random number we got from Math.random() * numberOfNames. In our case, because the names in our array of names is 5 hence the length is 5. Using random number with it will limit the range as 0-4 because random number start from 0 and never reaches 1. Instead of 0.99999999 - 4.9999999 we're able to round it down with help of Math.floor. We then return the array of names and then using the randomPositionOfNames the randomPositionOfNames now change anytime we call our function.
We'll be learning on how we can make computer run our code repeatedly by itself. This is know as loop. The simplest of them is the while loops. It is structure as this
We first created variable i which we give the value 1. We now give a true condition which is i < 3 which means 1 < 3 3 greater than 1. So we log the new value of i on each loop and we do that by adding the value i++ explicitly i = i + i till it reach a situation where by the statement i < 3 is no longer true, then it breaks and gives us final result which looks like this; 1, 2. So it won't get to 3 because of the inequality sign which mandate the number to be lesser than 3. If the statement were to be i <= 3 it'll definitely reach 3 because the signs now signify that the number can be either be greater than or equals to 3.
We'll be modifying our fizzbuzz for it to run automatically.
With the above code, all codes works exactly as before but the only difference now is that the code will be executed automatically Without us calling the function repeatedly in our console. Just one call and we'll get the full output with the help of the while loops. Giving it condition that makes it goes from 1-100. So count <= 100 means in as much the count is less or equal to 100. It should keeps giving us output till it is no longer true. So it is when the block of code that is inside while loops is no longer true, only then it'll proceed to give us back our entire full array.
While loops can tends to be a dangerous approach because it'll continue to run infinitely until the statement of code inside it turns false. So if we made a mistake like not including the increment code count++ which means the count stays as 1 and never reach 100 then our loops keeps running till our tab freeze.
We'll replicate a lyrics of song with code. Popularly known as 99 bottles of beer. Visit 99-bottles for full lyrics. Glimpse of how it's being structure is 99 bottles of beer on the wall, 99 bottles of beer.Take one down and pass it around, 98 bottles of beer on the wall.98 bottles of beer on the wall, 98 bottles of beer. Take one down and pass it around, 97 bottles of beer on the wall. Till it run down to 0 bottle. The task is to replicate the whole lyrics, making it automated with code using while loops. And making sure the grammatical context of it is accurate. For example; 2 bottles of beer on the wall, 2 bottles of beer.Take one down and pass it around, 1 bottle of beer on the wall. 1 bottle of beer on the wall, 1 bottle of beer.Take one down and pass it around, no more bottles of beer on the wall.No more bottles of beer on the wall, no more bottles of beer.Go to the store and buy some more, 99 bottles of beer on the wall. Notice that as the bottle get to 1, it turns from bottles to bottles. Thing of a way to make the bottle plural if more than one and make it singular is 1. And when the bottle remain nothing, don't involve 0, instead return no more bottles.. As it is in the lyrics link.
First, we created a variable named bottleTotal. It stored the total value of available bottles of beer which is 99. Since we can either have either more than one bottle remaining or just one bottle, we created a function to
tackle the grammatical error that might occur as a result. So we name it bottleWordGrammar. Which we give it an input named bottleRemaining which gives us the privilege to give our function an input when we call it later. So
this will return singular form of bottle if we have just 1 bottle left, and it'll return plural forms of bottle if we have more than one bottles left. We use ternary operator to implement this in just one line
instead of going more explicit by using if and else explicitly. The question mark ? indicate that if the statement is true, it should return singular forms of bottle. The : indicate else
which returns the plural form of bottle.
We created another function that we named bottleBeerLeft. This helps us return a unique reply when our bottles run than to 0. So we instead return no more as reply for when we have no bottles left. And for the
: which is the else we simply return value of bottleTotal and we use the bottleWordGrammar to implement the usage of grammar. The bottleLeft input makes it the function a capable of taking
in an output when we later call it.
We then proceed to create while loops giving it an expression bottleTotal > 0 which simply means that, so far the bottleTotal is greater than 0, keep running the block of code we'll provide within the loops.
We provide message to display by using our functions and passing in the bottleTotal as an input. Then further message to clarify more updates on what is going on. We then use bottleTotal-- after the first message which reduces number
of bottles after which we provided an updated messages to display after bottle is reduced. So after the loops is no longer true, we provided further messages on what should be done next after which bottle of beer is finished.
For loops works similarly to a while loop, but instead of testing a condition, we're specifying the number of times that we want the loops to run. Here is how the syntax looks like.
We have a keyword for with set of parentheses. Inside the parentheses we first define a starting point var i = 0; So in this instance, we started at 0. We then define the end point i < 5; So the code will keeps running in as much i value is under 5. The last is the change implementation i++. This basically impose an increment on the variable i. This will give output of 0,1,2,3 and 4.
The difference between the two is that, in the var i creation now goes inside for loops indicating starting point. Other notable difference is that
For While loops we have to include the code that change i inside the while loops. But with the for loops, we've integrated it
inside the declaration for the for loops. So at the creation of the for loops, we've define the starting point, the
ending point and how much "i" is going to change.
While loops checks for a state, so it is while something is true. So it repeatedly run an instructions while the program is in a certain state. For the
For loops, we iterate. That is, we run a piece of code many times an we use the for loops to impose the number of times.
So here, we started with variable with value 1.And we'll end while i is less than 5 and we're incrementing by 1 each time. And inside the loop, we simply
log the value of i. The computer first run the code var i = 1 and then create the variable i. It then set the value to 1 as we've provided at
the start.
Next step is it reaches the second part of the for loop where it checks to see whether if the current value of i is less than 2 and 1 is definitely less than 2
So it proceed to run the code inside the for loops. So the code inside the curly braces { }. And in our case, it log the value of i which is currently at 1.
Once getting to end of the for loops which is at the last }. This is the point where the third value in that for loops which is i++ is carried out.
So in our case, i is incremented by 1. So i is now equal to 2. Now the code looks back to run the loop again. And the first thing it now check is to check whether the
condition is true that is i < 2 As we know that 2 is not less than 2. So the condition to keeps running are not met and the code exit the loop.
The code explanation is the same as before, the only changes is the implementation of the for loops. This implementation is more flexible as the condition can even goes in other direction by counting down from 100 to 1. And we can also makes the count increment be of 2.
In this section, we'll be creating a fibonacci sequence generator. The techniques behind the sequence goes like this. We'll add subsequent number together to get the next number. There are lot of version as some start there sequence with 1, 2 and so on, but we'll start our own with 0 and 1 which looks like this; 0, 1, 1, 2, 3, 5, 8, 13, 21.....
We created a function name fibonacciSequence which take in a parameter n to make it dynamic to put in any number when calling the function. We created variable named
output to store the number as an item in a list. Since we want our fibonacci sequence to start at 0 and 1. We set in conditional statement.
So the first one says if the
Argument which will be the value that'll replace the parameter that we pass in to our function. So if the number will pass when calling our function is 1.
We set the output variable now to [0]. We can also use push to add the number to our output.
The second condition was set to if the number pass is 2 then the output is now set to [0, 1].
So thirdly, in rest situation that the argument pass in to our function is higher than both 0 and 1, we provided the output value as the value
of the immediate one which is [0,1] we then iterate using our for loops which we save of stress of having to manually keep giving different output
writing countless if & else statement. So we use for loops to iterate on all the condition that may be provided when calling the function. So we start by setting the value of our
i variable to 2 because we already have 2 items in our output list. So what is require now is to adding subsequent number onward. We then set condition that in as much
n which will be replace by the argument that is the number to be pass when calling the function. So under the condition where i which will be the current number of items in our list
is less than giving argument we then set i++ which means we want i to be increasing till the number enter is greater than i So for example if we call our function like this
fibonacciSequence(3); for loop we make sure the output items must be 3. So this will return [0, 1, 1]. We then set what should be put inside the output
variable. So we derive position of output using output[output.length] this gives us dynamic current position of the last items inside output. We know that position start counts
from 0 unlike length which start from 1. Since we want the item position, we then subtract 2 from the current length of our item, this will give us dynamic position
same as when we subtract 1 So they both will keep transiting depending on number we pass. So if we pass in 3 for example. Since i < n in our loop, it'll be output[2-2]. So item
at position 0 and output[2-1]item at position 1. So we add them together. output[2-2]+output[2-1] which result output[0]+output[1]. Which means to get an output that
will be of length 3 which means 3 items in our output we'll add item at position 0 and 1 which the both items will give us the third item on the list. So we'll get back [0,1,1].
Lastly, we return our output list array after all the conditional. Then we callout our function fibonacciSequence(5) In this case we passed in 5. Since it is greater than both 0 and 1.
It'll bounce straight inside our else So we gave it the output default value to start with, which is 0 and 1. We then use for loops to iterate. In as much i < 5 we will keep
adding subsequent number till the statement is no more true. So what will be put inside our list will now look like this => since i = 2 and i < 5 So in background, for loops work on 3 since
two value has been provide already which is 0,1 it then check again with 4 and it breaks at 4 because the i < 5 condition must be met. So the number must not be up to 5.
What will now be the push to our output list will be structure as this => output[4-2]+output[4-1] which gives output[2]+output[3] it'll now look inside the last items it has already work on, in this
case the recent one is [0,1,1,2] So position 2 + position 3 which the number presently at this position is 1 and 2 respectively. Adding them together gives back 3. So the number to be added
at the end of our list will be 3. Our updated list value now look like this [0, 1, 1, 2, 3]. So five items
In this section we'll now be learning on how we will be able to implement all what we've learn about javascript in a webpage. So inside our vscode we'll create a new folder and give it a name, then we create 3 files
inside. index.html, style.css and index.js.
JavaScript follows the same way as Css when adding the files to our document. We can add js through Inline, internal and external.
Here is how inline Js looks like inside index.html
Now, if you observe the body tag element you'll see a property named onload. This is one of Js property which means when the body of our website is loaded up, then whatever Js we place
inside the quotation mark will be executed. In this case, we use alert keyword and provided what is it we want to popup which in this case is Hey! Notice how we use double quote "" and single quote
'' we simply did this to distinguish string of text from actual Js keyword. Then we concluded it with ;
Just as the Css Inline, also, Js Inline is not modular, and it is tough to debug.
Here is how internal Js looks like inside index.html
In this type, we simply use script tag and everything between it can be a Js. So now, we don't need to contain our keyword inside quotation mark here, just the string. This does exactly the same thing. The browser reads through the web page line by line and once it hit the script tag, it'll execute the Js that is placed inside.
Here is how External Js looks like inside index.html
In this type, we simply add a separate file named index.js inside script tag by using src which means source as attribute to locate the file. The charset="utf-8" tag tells the browser to interpret the characters on the webpage using the UTF-8 encoding.
Here is how the index.js file will look like.
So now, we've created the external file that the script tag inside the index.html will target. We simply give the file the keyword and the string it will display. This does same thing when the web page gets loaded up, we get an alert of Hello
The position inside the html document where we place the script tag matters a lot. With Css tag we place it inside the head element tag so that it get loaded first before any of the content.
of our website which tends to be inside the body tag. This is highly necessary because, if we place the Css Link Tag inside the body tag instead, what happens as a result is that, our website
will behave weirdly because it do read the code line by line from the top, so will have to get to the body tag before it execute our Css code which is not what we want.
With Js, it is quite opposite because if inside our script we tried to change an html element that does not yet exist, then it will fail. So for example, inside our index.js we write a code to change html
element document.querySelector("h1").innerHtml = "Good Bye"; This simply means, we want our code to look inside our document and the look for selector named h1 and when it finds the element, we then change
the innerHtml which is the text that is inside the h1. Currently, it's set to Hello and we want to change it to Good Bye.
Now, if the script we want to change the h1 is below the h1 that is after the h1 has been created, then the code will work as it'll find the innerHtml also known as the text.
and change it as require. But if we move the script into the head tag section, then it'll fail because running from top to bottom will prevent it from seeing the h1 element we wanted to change. So it will fail before
reaching where our h1 is.
So best practice is always to bind the script tag inside the body tag. Added benefit of this is that, it add runtime speed to our website because it require more time to run the script, so placing it at the end
makes our website loaded up fast and by the time it get to the Js zone, Js would be well ready.