2. Data Types
Numbers: A number. Numbers don’t have quotes around them.
// Using a variable to store a number
var price = 5;
var quantity = 14;
var total = price * quantity;
Above, three variables are created and values assigned to them.
price holds the price of an individual item.
quantity holds the number of items a customer wants.
total holds the total cost of the items.
Strings: A sequence of text known as a string. To signify that the variable is a string, you should enclose it in quote marks.
// Using a variable to store a string
var name = "Martin";
var message = "Hello World";
Above, two variables are declared (name and message), and they are used to hold strings.
Booleans: A Boolean variable can only have a value of true or false, but this data is very helpful.
// Using a variable to store a boolean
var inStock = true;
var shipping = false;
Variables are containers that you can store values in. You start by declaring a variable with the var keyword, followed by any name you want to call it:
var city = "Barcelona";
They can store all of the values we have seen
var name = "Marlon"; //String
var favNumber = 23; //Number
var isFunny = true; //Boolean
Recall the stored value by calling the variable name
var name = "Marlon";
"Hello there " + name //"Hello there Marlon"
var num = 37;
num + 3 + 10 //50
We can also update existing variables
var name = "Marlon";
name = "Marlon Martins";
4. Useful Built-In Methods
The alert() method displays an alert box with a specified message and an OK button.
An alert box is often used if you want to make sure information comes through to the user.
prompt() displays a dialog with an optional message prompting the user to input some text.
console.log() Outputs a message to the Web Console.
You should write comments to explain what your code does, they help make your code easier to read and understand. This can help you and others who read your code.
Single line comments start with //.
var x = 5; // Declare x, give it the value of 5
var y = x + 2; // Declare y, give it the value of x + 2
Multi-line comments start with /* and end with */.
The code below will change
the heading with id = "myH"
and the paragraph with id = "myP"
in my web page:
document.getElementById("myH").innerHTML = "My First Page";
document.getElementById("myP").innerHTML = "My first paragraph.";