JavaScript is a special language indeed. Especially for those coming from PHP, C, Java.
Let’s start it with language basics: variables, coding style etc.
Code structure
The code consists of multiple statements.
Semicolon
Statements are separated by a semicolon.
<html> <body> <script> alert('Hello'); alert('World!'); </script> </body> </html>
Spaces and tabs are ignored, so one-lining is possible:
alert('Hello'); alert('World!');
But newlines are not ignored. Instead, a newline may separate statements, just like semicolons do.
These two lines are fully equivalent:
a = 5 a = 5;
Missing semicolon pitfalls
There are few mistakes which beginners tend to make in multiline assignments and calls, because of semicolon issues.
First, this is not going to work:
var a = "long line "
That’s because a parser thinks that the first line is a full statement, like:
var a = "long*!*;*/!* line "*!*;*/!*
And there will be an error about unfinished string (unterminated literal).
Second, these two snippets of code are equivalent:
return result;
… Is, because of a newline, same as
return*!*;*/!* result*!*;*/!*
And that’s of course different from:
return result
Only the last example actually returns result
.
To insert a convenience newline, you can put a backslash before line break, like that:
var a = "long \ line " return \ result
A backslash before a line break forces the interpreter to ignore the newline.
The newline is also ignored if the expression is not finished, particularly for unfinished operators or unclosed brackets:
var a = "long " + " line " var b = 2 + ( 2 + 3 )
JavaScript tries to be even smarter than that. The output in the example below is 8
, the newline is ignored. And don’t ask me why.
var b = 2 * 2 + 4 alert(b)
The rules about the semicolon insertion are complicated and sometimes weird. They are described in the ECMAScript specification.
In short, it is possible to omit ending semicolons in most cases, but doing so gives freedom to the interpreter. The freedom which it could abuse and cause bugs.
There was an argue between programmers: “should I put a semicolon or not?”. Nowadays, most people agree that they should.
In the tutorial, you find lots of code without semicolons. That just my bad habit.
Because I’m in JavaScript for a very long time, I stepped into pitfalls so many times that I know how to get the way out very quickly. Guess, you don’t want to repeat my path here, but rather walk around the pits. Put semicolons between statements.
What’s wrong here?
var a = "Empty spaces - what are we living for? Abandoned places - I guess we know the score.. On and on! Does anybody know what we are looking for?" alert(a)
The multiline string must have backslashes before every line break:
var a = "Empty spaces - what are we living for? \ Abandoned places - I guess we know the score.. \ On and on! \ Does anybody know what we are looking for?" alert(a)
Variables
If you are not familiar with general programming variable concept, there is a great wiki article about it. Shortly, a variable is a named “box”, where you could put a value.
Definition
First, a variable should be defined. That can be done in any place of code using directive var
var x
When a variable is defined, it is possible to operate with it, for example, put a value into it:
var x x = 5
Or you can define multiple variables in single var
statement:
var a, b, c
It is possible to assign a variable in definition:
var name = "John", song = "La-la-la"
In JavaScript you can assign to a variable which you haven’t defined using var
:
noVar = "value"
Technically, it doesn’t cause an error, but don’t go this way. Always define variables with var
. That’s a good style and helps to evade certain errors, like in the code below.
Run this in IE:
<html> <body> <div id="test"></div> <script> test = 5 alert(test) </script> </body> </html>
There will be an error.
IE, Safari/Chrome and Opera create a variable for each element with id
, so variable test
references DIV
in the example above.
But in IE the auto-generated variable is an internal reference that can’t be changed. That’s why assignment to test
causes an error.
The following code works:
<html> <body> <div id="test"></div> <script> *!*var*/!* test = 5 alert(test) </script> </body> </html>
Variable names
A variable name first char must be a letter, $
or _
. The second char and other chars are allowed to be digits.
Strange, but valid names:
var $this, _private, $, _, $1, user15
JavaScript is CaSE-sEnSitiVe!
Apple
and APPLE
are two different names.
Reserved words
There is also a list of reserved words, which can’t be variable names. It includes var, function, return, class, implements
and other words, most of them are used in the language itself.
Some words, like class
are not used in modern JavaScript, but still reserved. There are browsers which allow them, but using them may lead into a pitfall.
The following code works in Firefox which allows 'class'
as variable name. And fails in Safari which gives syntax error on such variable:
var class = 5 alert(class)
Read more about naming principles and how to make good names in the article Variable naming.
Language types
JavaScript defined the following basic types:
- number
- Any number, integer and non-integer:
1
,2
,1.5
etc. - string
- A string, like
'cat'
,'dog'
or'my mommie bought a puppy'
- boolean
- Two possible values:
true
andfalse
. - object
- Objects.. We’ll talk about them later.
- special values
- There are special values which have no type:
null
andundefined
.
Weak typing
Variables in JavaScript are weakly typed. That means two things:
- Every value has a type
- You can put a value of any type into any variable
For example:
var userId = 123; // 123 is a number var name = "John"; // "John" is a string
But you are free to reassign the variable to a value of another type:
var userId = 123; // 123 is a number userId = false; // now userId is boolean
Before a variable is assigned, it has undefined
value. The following statements mean the same:
var x var x = undefined
Generally, undefined
means “no value”.
Comments
Did you note these “//” from the previous example? That were comments.
Comments in JavaScript have two different forms. Single line comment starts with //
and continues to the end of line.
// let's see who is here: var name = "John"; // My most valued visitor
Anything you put after //
is ignored by the interpreter.
Multiline comments
Multiline comment is enclosed with /* ... /
and may span multiple lines.
/* The following variable has a short name. Usually a short name means that the variable is temporary and used only in nearest code. */ var a = "John";
Blocks
The next building element is a block. It consists of multiple statements wrapped in curly braces, like the following:
var i = 5; *!* { i = 6; } */!* var b;
Standalone blocks are never used in JavaScript. But curly braced statements come as a part of more complex syntax constructs like for
, if
, while
, functions, etc.
We’ll get to them in the next sections.
Summary
A few important points to summarize:
- Variables are defined by
var
anywhere in the code. They can be assigned in definition. - A variable can contain a value of any type.
- There are single-line
//
and multiline/...*/
comments. - Statements are divided by semicolons. A newline usually implies a semicolon, so technically it is possible to omit them most time. There are arguments pro and contra omitting semicolons. Choose your way with eyes open.