Working with Numbers

The most common kind of values in computer programs are numbers. Not like other strong-type programming language who have to know the right data type for the right number, in Javascript we can just write it. They all just considered number.

var a;
a = 5;
a = 1000000;
a = 123.654;
a = -500;
alert(a);

As you can see, we can change the value of 'a' easily because Javascript treat them only as numbers. What you will printing is the last value you write into 'a'. So in this case 'a' have value of -500.

var b = 123;   //data type of int
var c = '123'; //data type of string

Remember, when you write number inside the quotation sign, it will become a string. So be careful.

Using Characters and Strings

When you put word inside quotation, it called string literal. We can create variable with string literal as value. After that, you can alert the variable. Do not put variable inside quotation, because it will make it to string.

var message = "Hello, world";
alert(message);  //print "Hello, world"

var message = "Hello, world";
alert("message");  //print "message"

When we creating string, you can use double quote (" ") or single quote (' ') to surround the word. But you can't mix those two. You cannot open open with double quote and end with single quote.

var message = "Hello"; //right
var message = 'Hello'; //right
var message = "Hello'; //wrong

One of the reason you might change between the two format is if you need to have quotes inside quotes. In that case, you can use single quote inside double quote and not the other way.

var message = "I 'love' your face"; //right
var message = 'I "love" your face'; //wrong

Also, never write like this :

var message = 'I 'love' your face';

It's wrong because there are single quote inside that quote, causing program not knowing the right end quote. If you want to word like that using single quote, use escape character(\).

var message = 'I \'love\' your face';

Escape character is not part of the words, you just mark the quote signs inside so program know the right opening and ending quote sign.

results matching ""

    No results matching ""