# JavaScript basics: Numbers and Strings

September 26, 2018

Below is your first JavaScript program. If you run the program (click Try It Now! and then Run), you’ll see that it simply produces the output Hello, CommonLounge!.

console.log("Hello, CommonLounge!");

Output:

Hello CommonLounge!

When you say console.log('Something'), JavaScript will “print” the contents you give it to the output (without the quotes).

In the above program, 'Hello, CommonLounge!' is a string. A string is a sequence of characters that can be processed by a computer. The string must always begin and end with the same character. This may be single (') or double (") quotes (there is no difference!) The quotes tell JavaScript that what’s inside of them is a string.

Always remember to put a semicolon ; at the end of every statement. It is not necessary but it is a good practice.

# Operators and Operations

What if we have some math inside console.log, like 2 + 3? Hit the “Try it now” button to find out!

console.log(2 + 3);

Output:

5

Nice! See how the answer popped out? JavaScript knows math. You could try other expressions like:

• 3 + 4 - 5
• 5 * 4 / 2
console.log(3 + 4 - 5);
console.log(5 * 4 / 2);

Output:

2
10

To perform exponential calculation, say 2 raised to the power 3, we type:

console.log(2 ** 3);

Output:

8

Have fun with this for a little while and then get back here :)

There are some more operators in JavaScript, but we won’t go over them right now. At the end of the article, there is a table with a list of all arithmetic operators in JavaScript.

# Expressions

Each of the lines that you typed into the console so far is called an expression. Expressions can be much longer too. For example, try this:

console.log((5 + 2) * (7 - 1) / 3);

Output:

14

Expressions enclosed in parentheses get evaluated first. After all the parenthesized expressions are evaluated, the standard operator precedence is followed.

In JavaScript (and other programming languages as well), all expressions evaluate to a single value.

Here’s a step-by-step breakdown of how the above expression is evaluated.

(5 + 2) * (7 - 1) / 3
=> (7) * (7 - 1) / 3
=> 7 * (7 - 1) / 3
=> 7 * (6) / 3
=> 7 * 6 / 3
=> 42 / 3
=> 14

JavaScript does the above behind the scenes, and tells us what the final result of evaluating the expression is.

# Strings

A sequence of characters is called a string. A string should also be enclosed within open and close inverted commas (" ") or (' '). Both opening and closing quotes should be the same for a string to be valid. For example,

• "teststring" and 'teststring' are strings
• while notastring and 'teststring" are not strings

Strings can be joined together. This is called concatenation of strings:

console.log('Hello ' + 'World!');

Output:

Hello World!

Notice how we had to end the first string ('Hello ') with a space (' '). If we did not, then our result would be 'HelloWorld!', which isn’t what we want.

If you need to put an apostrophe inside your string, you have two ways to do it.

Using double quotes:

console.log("Runnin' down the hill")

Output:

Runnin' down the hill

or escaping the apostrophe with a backslash (\):

console.log('Runnin\' down the hill')

Output:

Runnin' down the hill

Nice, huh? To see your name in uppercase letters, simply type:

console.log('Commonlounge'.toUpperCase())

Output:

COMMONLOUNGE

You just used the toUpperCase() method on your string! A method (like toUpperCase()) is a sequence of instructions that JavaScript has to perform on a given object ("Commonlounge") once you call it.

JavaScript has a number of other built-in functions / methods. You have already seen console.log(). Here’s another one:

console.log('Hello'.repeat(3))

Output:

HelloHelloHello

You can combine concatenation and repetition to form more complex strings

console.log('Hello' + '!'.repeat(3))

Output:

Hello!!!

Wonder why sometimes you call functions with a . at the end of a string (like "Commonlounge".toUpperCase() and '!'.repeat(3)) and sometimes you first call a function and place the string in parentheses (like console.log("Hello World!"))? Well, in some cases, functions belong to objects, like toUpperCase(), which can only be performed on strings. In this case, we call the function a method.

If you want to know the number of characters in a string, you can use the length attribute of a string.

console.log('Hello world!'.length)

Output:

12

Wonder why we don’t need parentheses - () - for .length? That’s because it’s an attribute and not a method. When we use a method, JavaScript needs to do some calculations to calculate the result we asked for. When we use an attribute, the result is already stored somewhere.

In JavaScript, all strings are objects. An object is a collection of attributes and methods. Any attribute or method of an object can be accessed by using dot notation, that is, object.attribute_name or object.method_name().

# Errors

Let’s try finding the number of digits in a number

console.log(215125.length)

Output:

Uncaught SyntaxError: Invalid or unexpected token

We got an error saying Invalid or unexpected token. We got this error because numbers don’t have a length attribute.

So what can we do? Since, we know that we can find length of a string, it makes sense to write our number as a string.

console.log('215125'.length)

Output:

6

# Converting between types

There’s another way to do this. We can use the String() function to convert a number to a string.

console.log(String(215125).length)

Output:

6

Similarly, there’s also a parseInt() function to convert from string to number (Int stands for integer).

console.log(parseInt("1256") + 55)

Output:

1311

What if we give it something that’s not a number? Let’s try:

console.log(parseInt("hello"))

Output:

NaN

NaN stands for Not a Number. It appears when we give a string to parseInt that cannot be converted to a number.

Numbers with a decimal point are called floating point numbers or float for short. Similar to parseInt(), parseFloat() converts the given string to a float.

What happens if you try adding a number to a string?

console.log(1 + " 2 3")

Output:

1 2 3

No error! JavaScript is one of the few languages that will not throw an error for this expression and instead will implicitly convert the 1 to a string.

# Summary

OK, enough of strings. So far you’ve learned about:

• numbers and strings – in JavaScript numbers are used for math and strings for text
• operators – like + and *, combine values to produce a new one
• functions and attributes – like .repeat(), .length
• errors – you now know how to read and understand errors that show up if JavaScript doesn’t understand a statement you’ve given it

These are the basics of every programming language you learn. Ready for something harder? We bet you are!

# Appendix: List of Arithmetic Operations

The following is a list of all arithmetic operations supported by JavaScript.

Operator | Example | Result | Description
---------|---------|--------|------------------------------------------------
+     | 4 + 5   | 9      | addition
-     | 4 - 5   | -1     | subtraction
*     | 4 * 5   | 20     | multiplication
/     | 8 / 3   | 2.666  | division
%     | 14 % 3  | 2      | modulo (remainder left after division)
**    | 5 ** 2  | 25     | exponent 

# Exercise

Play around with the functions that you’ve learned about so far. Try the following and try to explain the output.

• parseInt("199ff")
• parseInt("hahah")
• parseInt(String(199))
• parseFloat(parseInt("351.35"))

You can try these out here:

console.log(parseInt("199ff"))