Variables in JavaScript

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

TRANSCRIPT

Variables are used to store and retrieve values from the memory of your computer. And in this lesson, you will learn how to create variables in JavaScript. I'm gonna start by declaring a new variable. To declare a variable in JavaScript, you use the keyword var. And then you need to give your variable a name, that name can be any word or just a single letter, it cannot contain spaces in between. So I'm gonna call a variable a. In JavaScript when you end a statement, you need to enter a semicolon. So what I've done here is declare a new variable and call it a. We also need to assign a value to that variable. You can assign a variable, a value to a variable upon declaration. So I'm gonna create another variable called b and be using an equal sign, you can give it a value, so b will be equal to 10. You can also assign a value to an existing variable, in which case you don't have to use the var keyword anymore because that's only for the declaration part. We'll give this one a value of 100. Let's show these variables on our web page. So I'm gonna type in alert, which allows me to show a message box and the name of the variable. This case will be a and I'm gonna close this with a semicolon. When the page loads, it shows the value of 100, which is the value of the variable called a. You can also enter text in a variable. So let's call this variable, let's call it text. And I'm gonna enter some text in here. So to enter text you need to use either single or double quotes. And we can show this on a message box using alert. So let me reload the page. And we'll see that it first, firstly it shows me 100, and then I click okay, and then it shows me your name here, the value of this one. Variable names are case sensitive, so a variable called lower case a, is not the same as a variable called upper case A. A common way to name variables is when you need to call them with more than one word, for example, person name, is something that's called camel case. So you type in different words, in this case personName, and the second word starts and the follow up words start with an upper case or with a capital letter. So this is called a camel case notation. It's just a convention. That's just how people normally call their variables. Another thing for you to know is that the name of the variables, it's only made for us humans to understand. So the computer doesn't care if you call your variable name, if you call it sky, if you call it letter x, that's just for humans to have a sense of what's going on in our code. Variables can be used for multiple things, they can be used to perform mathematical calculations, to manipulate text, to store different types of data. And JavaScript supports multiple types of variables, not just numbers and text, as we'll see further in the course.
Рекомендации по теме