Today we're going to review and talk about some of the nitty gritty of JavaScript syntax.
Let's do this in the JavaScript console. In Chrome for Mac:
Or Windows:
Syntax basics
The following is a simple statement that declares and initializes a variable.
var sentence = "Hello world";
Each part of our statement should be separated by one space.
In JavaScript, extra white space is ignored.
var sentence = "Hello world.";
Extra white spaces are not ignore if they are part of a string value.
var sentence = "Hello world.";
Assignment operator
The =
sign is for assigning values.
Unlike in math, it does not mean that two values are the same. It simply asks the program to store a value somewhere in the memory the computer and give that piece of memory a nickname.
When I say "gets" I mean the =
assignment operator.
So this is what that statement would sound like:
A variable called sentence gets the value "Hello world."
Variables
In Javascript, variables are declared using var
regardless of what type of information they hold.
Type sentence
in the console again and it will return the value, "Hello world."
Declaration and Assignment
Creating a variable requires two steps: declaration and assignment.
// declaration
var a;
// undefined
// assignment
a = 10;
// 10
A variables can be initialized by declaring and assigning in one statement:
// initialize
var a = 10;
Numbers and Strings
JavaScript has several basic data types, including Numbers and Strings.
Numbers can represent any numerical value:
10;
10.5;
0.1 + 0.2;
1 / 0 // Infinity
Because variables can be set to different types, you can check in a value is a Number. If not, you will get the error type NaN
or "Not a Number".
var a = "ten";
Number(a); // NaN
typeof a; // "string"
Strings are "strings" of characters. They usually store messages, names or other text that needs to be rendered in a program. They can also store data.
var s = "Hello"
var name = "Jerry";
s + " " + name;
Once a variables is declared, the value can be assigned or changed using an operator.
var a = 0;
a = 10;
a = 10 + 20;
a = "ten plus twenty";
Operators
Add and subtract
var x = 10;
var y = 20;
x + y;
x - 5;
x - y + 5;
// use parentheses for order of operations
x - (y + 5);
Multiply and divide
2 * 2;
2 / 3;
Concatenation
var h = "hello";
var w = "world";
x + w;
"hello" + "world";
"hello " + "world";
Increment, decrement
var x = 0;
x++;
x += 10;
x--;
x -= 5;
Addition vs. concatenation
var x = 1;
var y = "7";
x + y;
typeof x + y;
y + x;
x + +y;
x + Number(y);