The JavaScript Programming Language
Syntax
Statement
Statement ends with semicolon.
var x = y >= 0 ? y : -y;
Expression
Expressions are collections of statements mostly inside blocks.
var x;
if (y >= 0) {
x = y;
} else {
x = -y;
}
Block
Block is a collection of statements inside curly braces.
if (x<=y) {
x += 3;
y = 23;
}
Semicolons
Semicolons terminate statements.
var x = 23;
var fja = function ( x ) { ... }; //only case where block ends with semicolon
AUTOMATIC SEMICOLON INSERTION
JS parser insert semicolon automatically:
- newline if (x < 0) x = 0
- inside curly brace function add(x,y) { return z }
Sometimes generate error:
return
{
name: 'John'
};return ; //automatic insertion generate error
{
name: 'John'
};
Comments
// single line
/*
multi line
comment
*/
Variables and assignement
Variables are defined by var keyword.
var identifier = value;
var x = 5;
x = 8; //overwrite variable
console.log(x); //8
VARIABLE IDENTIFIER
Identifier is a variable name. It can contain any unicode characters for example čćž.
var čćž = 15; //croatian characters
console.log(čćž);
example: 001syntax_unicode.js
"café" === "caf\u00e9" //true
Identifier must start with character, _ or $. Can't start with number.
var 3x ; //this will generate error
Also don't use reserved words for identifier.