Arithmetic Operations in JavaScript

preview_player
Показать описание

TRANSCRIPT

In this lesson, I'm gonna show you how to do simple mathematical operations using JavaScript. We're gonna cover addition, subtraction, multiplication, and division. Let me begin by adding in some JavaScript code in here. And I'm gonna start by typing in a comment, messages that you leave in your code for other human beings, or your future self, to read and understand what that code does. It is a good practice to always comment your code to write and to explain what you are doing. To enter comments in JavaScript, you type two forward slashes, and then you can type in anything you want. I'm gonna write in addition. I'm gonna create a variable called a, which will have a value of 1,000. And I want to know the result of the variable a plus 200, and I'm gonna store that in another variable called b. To assign a variable, as we've learned, you will use the equals sign. And if we want to do an addition, we will type in a plus the number. That will give us a result which we can easily show on a message box. As you can see, that gives us the correct result. I don't want to have this shown each time as we move on, so I'm gonna comment this line out. To comment code out, it means to convert a line of code into a comment so that it stays around but it's not executed, it's treated as text. Let's look now into subtraction. Let's create a new variable, and this one will have the value of, let's say, 100 minus 50. And we can easily show that on a message box. Multiplication. Let's call it m, and let's say that this will be c times 10. This one here gave us 50 as a result, and 50 times 10 should give us, let's reload this page, and you can see the 500 in there. Division works in a similar way. All we need to do is use the forward slash sign. Let's divide 500 by two. Let's comment that one out so we don't see it each time. 250, half of the value of that number. Call this one combo, and it'll be, say, 100 plus 50 divided by two times 10. What happens here is that multiplications and divisions executed first, so this part is the first thing that's gonna be executed, and then the rest will be added. Whatever you put inside the brackets gets executed first. In this case, this will be executed first. And now to finish this up, I'm gonna implement a simple calculator that will convert from Celsius degrees to Fahrenheit degrees. And let's end this by showing it on an alert box.
Рекомендации по теме