Quick Start
Identifiers
Must begin with:
- A letter
A-Z a-z
- A dollar sign
$
- An underscore
_
JavaScript identifiers are case sensitive, lastName
and lastname
are two different variables.
Usually, variables in JavaScript are named using Lower Camel Case:
firstName, lastName, masterCard, interCity
JavaScript uses the Unicode character set.
Comments
Single Line Comments:
// comment
Multi-line Comments:
/* comment comment */
Variables
JavaScript variables can be declared in 4 ways:
- Automatically
- Using
var
- Using
let
- Using
const
The
var
keyword should only be used in code written for older browsers.
var
, let
, or const
When to use - Use
const
if :- the value should not be changed
- the type should not be changed (Arrays and Objects)
- Use
let
if you can’t useconst
- Use
var
if you must support old browsers
Scope | Redeclare | Reassign | Hoisted | Binds this | |
---|---|---|---|---|---|
var | No | Yes | Yes | Yes | Yes |
let | Yes | No | Yes | No | No |
const | Yes | No | No | No | No |
let
Variables declared with let
:
- have Block Scope
- must be Declared before use
- cannot be Redeclared in the same scope
const
Variables declared with const
:
- cannot be Redeclared
- cannot be Reassigned
- have Block Scope
const
does not define a constant value, it defines a constant reference to a value.
You cannot reassign a constant value, but you can change the elements/properties of constant Array/Object.
const
when to use Always declare a variable with const
when you know that the value should not be changed.
Use const
when declaring:
- A new Array
- A new Object
- A new Function
- A new RegExp
Operators
Arithmetic Operators
Operator | Description |
---|---|
+ | Addition |
- | Subtraction |
* | Multiplication |
** | Exponentiation (ES2016) |
/ | Division |
% | Modulus (Remainder) |
++ | Increment |
-- | Decrement |
Comparison Operators
Operator | Description |
---|---|
== | equal to |
=== | equal value and equal type |
!= | not equal |
!== | not equal value or not equal type |
> | greater than |
< | less than |
>= | greater than or equal to |
<= | less than or equal to |
? | ternary operator |
Logical Operators
Operator | Description |
---|---|
&& | logical and |
|| | logical or |
! | logical not |
Type Operators
Operator | Description |
---|---|
typeof | Returns the type of a variable |
instanceof | Returns true if an object is an instance of an object type |
typeof "" // string
typeof "Alice" // string
typeof 1 // number
typeof 1.001 // number
Bitwise Operators
Operator | Description | Example | Same as | Result | Decimal |
---|---|---|---|---|---|
& | AND | 5 & 1 | 0101 & 0001 | 0001 | 1 |
| | OR | 5 | 1 | 0101 | 0001 | 0101 | 5 |
~ | NOT | ~ 5 | ~0101 | 1010 | 10 |
^ | XOR | 5 ^ 1 | 0101 ^ 0001 | 0100 | 4 |
<< | left shift | 5 << 1 | 0101 << 1 | 1010 | 10 |
>> | right shift | 5 >> 1 | 0101 >> 1 | 0010 | 2 |
>>> | unsigned right shift | 5 >>> 1 | 0101 >>> 1 | 0010 | 2 |
Data Types
JavaScript has 8 Datatypes:
- String
- Number
- Bigint
- Boolean
- Undefined
- Null
- Symbol
- Object
Dynamic Types
JavaScript types are dynamic. This means that the same variable can be used to hold different data types:
let x; // undefined
x = 5; // number
x = "Alice"; // string
String
A string is a series of characters. Strings are written with quotes, you can use single or double quotes:
let name1 = "Alice"; // double quotes
let name2 = 'Foo' // single quotes
// Use quotes inside a string
let str1 = "It's OK";
let str2 = "She is 'Alice'";
let str3 = 'She is "Alice"';
String length
let text = "123";
console.log(text.length); // 3
Escape character
Code | Result |
---|---|
\b | Backspace |
\f | Form Feed |
\n | New Line |
\r | Carriage Return |
\t | Horizontal Tabulator |
\v | Vertical Tabulator |
String Object
let x = new String("Alice");
Do not create String objects.
The
new
keyword complicates the code and slows down execution speed.
String objects can produce unexpected results:
let x = "Alice";
let y = new String("Alice");
let z = new String("Alice");
console.log(x == y); // true
console.log(x === y); // false
console.log("");
console.log(y == z); // false
console.log(y === z); // false
Comparing two JavaScript objects always returns false.
String methods
Extracting string parts
slice(start, end)
substring(start, end)
let str = "Alice";
// slice
console.log(str.slice(1, 3)); // li
console.log(str.slice(2)); // ice
// if the parameter is negative, the position is counted from the end of the string
console.log(str.slice(-3, -1)); // ic
console.log(str.slice(-3)); // ice
// substring
// if parameter is negative, it will be treated as 0
console.log(str.substring(1, 3)); // li
console.log(str.substring(-1, 3)); // Ali
Replacing string content
replace()
Thereplace()
method replaces a specified value with another value in string.replace(old_string, new_string) // regexp are written without quotes replace(regexp, new_string)
replaceAll()
let str = "My name is Alice Alice Alice";
// By default, replace() will only replace the first match
console.log(str.replace("Alice", "A")); // My name is A Alice Alice
// Use regexp
console.log(str.replace(/ALICE/ig, "A")); // My name is A A A
Converting to Upper and Lower Case
let str2 = "My name is Alice Alice Alice";
console.log(str2.toUpperCase());
console.log(str2.toLowerCase());
Concatenate
let x = "A";
let y = "B";
let z = "D";
console.log(x.concat(y, z)); // ABD
Trim
trim()
trimStart()
trimeEnd()
// trim() removes whitespace from both sides
let text1 = " A ";
console.log('"'+text1.trim()+'"'); // "A"
// trimStart() removes whitespace only from the start of string
console.log('"'+text1.trimStart()+'"') // "A "
// trimStart() removes whitespace only from the end of string
console.log('"'+text1.trimEnd()+'"') // " A"
Padding
padStart()
padEnd()
let str = "5";
console.log(str.padStart(2, "0")); // 05
console.log(str.padStart(3, "0")); // 005
console.log(str.padEnd(2, "0")); // 50
console.log(str.padEnd(3, "0")); // 500
Extracting string characters
charAt(position)
charCodeAt(position)
: returns a UTF-16 code- Property access
[]
let str = "abcd";
console.log(str.charAt(2)); // c
console.log(str.charCodeAt())// 99
console.log(str[2]); // c
Converting a string to an Array
split()
let str = "a,b,c,d";
str.split(","); // ['a', 'b', 'c', 'd']
Number
JavaScript numbers are always one type: 64-bit floating point.
let x1 = 2.00; // with decimals
let x2 = 34; // without decimals
// exponential notation
let y = 1e3; // 1000
let z = 1e-3; // 0.001
NaN - Not a Number
NaN
is a JavaScript reserved word indicating that a number is not a legal number.
let x = 10 / "a"; // NaN
isNaN(x); // true
typeof NaN; // number
BigInt
BigInt
is used to store integer values that are too big to be represented by a normal JavaScript Number.
let x = BigInt("123456789012345678901234567890");
Boolean
Booleans can only have two values: true
or false
.
let x = 5;
let y = 5;
let z = 6;
(x == y) // true
(x == z) // false
Array
JavaScript arrays are written with square brackets.
Syntax:
const arry_name = [item1, item2, ...];
const names = ["Alice", "Foo", "Bar"];
Object
const person = {
name: "Alice",
age: 16
};
Undefined
A variable without a value, has the value undefined
. The type is also undefined
.
let car; // undefined
typeof car; // undefined
Functions
function name(param_list) {
// code
}
Functions used as variable values
let x = add;
console.log(x(1,2)) // 3
function add(a, b) {
return a+b
}
Object
const person = {
name: "Alice",
age: 16
};
// Access properties
console.log(person.name) // Alice
console.log(person.["age"]) // 16
Object methods
const person2 = {
name: "Alice",
age: 16,
info: function() {
return this.name + ", " + this.age;
}
};
console.log(person2.info()); // Alice, 16
if-else
if (conditin) {
// code
} else if {
// code
} else {
// code
}
switch
switch (expression) {
case x:
// code
break;
case y:
// code
break;
default:
// code
}
Loop
JavaScript supports different kinds of loops:
for
- loops through a block of code a number of timesfor/in
- loops through the properties of an objectfor/of
- loops through the values of an iterable objectwhile
- loops through a block of code while a specified condition is truedo/while
- also loops through a block of code while a specified condition is true
for
for exp1; conditoin; exp2 {
// code
}
for-in
Do not use for in over an Array if the index order is important.
The index order is implementation-dependent, and array values may not be accessed in the order you expect.
It is better to use a for loop, a for of loop, or Array.forEach() when the order is important.
for (key in obejet) {
// code
}
const person = {
name: "Alice",
age: 16
};
for (let key in person) {
console.log(person[key]);
}
for-of
for (variable of iterable) {
// code
}
const arr = [1, 2, 3];
for (let n of arr) {
console.log(n);
}
while, do-while
while (condition) {
// code
}
do {
// code
} while (condition)
Set
A JavaScript Set is a collection of unique values. Each value can only occur once in a Set.
Method | Description |
---|---|
new Set() | Creates a new Set |
add() | Adds a new element to the Set |
delete() | Removes an element from a Set |
has() | Returns true if a value exists in the Set |
forEach() | Invokes a callback for each element in the Set |
values() | Returns an iterator with all the values in a Set |
Property | Description |
---|---|
size | Returns the number of elements in a Set |
// create set
const letters = new Set(["a", "b", "c"]);
// add element
letters.add("d");
// forEach()
letters.forEach(function(ele) {
console.log(ele);
});
Map
A Map holds key-value pairs where the keys can be any datatype.
A Map remembers the original insertion order of the keys.
Method | Description |
---|---|
new Map() | Creates a new Map |
set() | Sets the value for a key in a Map |
get() | Gets the value for a key in a Map |
delete() | Removes a Map element specified by the key |
has() | Returns true if a key exists in a Map |
forEach() | Calls a function for each key/value pair in a Map |
entries() | Returns an iterator with the [key, value] pairs in a Map |
Property | Description |
---|---|
size | Returns the number of elements in a Map |
// create map
const m = new Map([
["a", 1],
["b", 2],
["c", 3]
]);
// set
m.set("d", 4);
// get
console.log(m.get("b")); // 2
Map and Object
Object | Map | |
---|---|---|
Iterable | Not directly iterable | Directly iterable |
Size | Do not have a size property | Have a size property |
Key Types | Keys must be Strings (or Symbols) | Keys can be any datatype |
Key Order | Keys are not well ordered | Keys are ordered by insertion |
Defaults | Have default keys | Do not have default keys |
Error
The try
statement defines a code block to run (to try).
The catch
statement defines a code block to handle any error.
The finally
statement defines a code block to run regardless of the result.
The throw
statement defines a custom error.
try {
Block of code to try
}
catch(err) {
Block of code to handle errors
}
finally {
Block of code to be executed regardless of the try / catch result
}
Strict mode
"use strict";
Defines that JavaScript code should be executed in "strict mode".
Arrow function
Arrow functions allow us to write shorter function syntax:
hello = function() {
return "hello";
}
hello = () => {
return "hello";
}
hello = () => "hello";
Class
Use the keyword class
to create a class.
Always add a method named constructor()
:
class ClassName {
constructor() {
//...
}
method1() {...}
method2() {...}
method3() {...}
...
}
class Car {
constructor(name, year) {
this.name = name;
this.year = year;
}
}
const car1 = new Car("Ford", 2014);
const car2 = nwe Car("Audi", 2019);
Module
JavaScript modules allow you to break up your code into separate files.
Named exports
export const name = "Alice";
export const age = 16;
const name = "Alice";
const age = 16;
export {name, age};
Default exports
export default message = () => {
const name = "Alice";
const age = 16;
return name + " " + age;
}
Import
// import named exports
import {name, age} from "xxx.js";
// import default exports
import message from "xxx.js";
Async
Promise object
"Producing code" is code that can take some time
"Consuming code" is code that must wait for the result
A Promise is a JavaScript object that links producing code and consuming code
A JavaScript Promise object contains both the producing code and calls to the consuming code:
let myPromise = new Promise(function(myResolve, myReject) {
// "Producing Code" (May take some time)
myResolve(); // when successful
myReject(); // when error
});
// "Consuming Code" (Must wait for a fulfilled Promise)
myPromise.then(
function(value) { /* code if successful */ },
function(error) { /* code if some error */ }
);
When the producing code obtains the result, it should call one of the two callbacks:
Result | Call |
---|---|
Success | myResolve(result value) |
Error | myReject(error object) |
Properties
A JavaScript Promise object can be:
- Pending
- Fulfilled
- Rejected
The Promise object supports two properties: state and result.
While a Promise object is "pending" (working), the result is undefined.
When a Promise object is "fulfilled", the result is a value.
When a Promise object is "rejected", the result is an error object.
myPromise.state | myPromise.result |
---|---|
"pending" | undefined |
"fulfilled" | a result value |
"rejected" | an error object |
You cannot access the Promise properties state and result.
You must use a Promise method to handle promises.
Use promise
Promise.then() takes two arguments, a callback for success and another for failure.
Both are optional, so you can add a callback for success or failure only.
myPromise.then(
function(value) { /* code if successful */ },
function(error) { /* code if some error */ }
);
function myDisplayer(some) {
document.getElementById("demo").innerHTML = some;
}
let myPromise = new Promise(function(myResolve, myReject) {
let x = 0;
// The producing code (this may take some time)
if (x == 0) {
myResolve("OK");
} else {
myReject("Error");
}
});
myPromise.then(
function(value) {myDisplayer(value);},
function(error) {myDisplayer(error);}
);
async
async makes a function return a Promise
await makes a function wait for a Promise
async function myFunction() {
return "Hello";
}
// same as
function myFunction() {
return Promise.resolve("Hello");
}
The await
keyword can only be used inside an async
function.
The await
keyword makes the function pause the execution and wait for a resolved promise before it continues:
let value = await promise;
example
async function myDisplay() {
let myPromise = new Promise(function(resolve) {
resolve("I love You !!");
});
document.getElementById("demo").innerHTML = await myPromise;
}
myDisplay();
async function myDisplay() {
let myPromise = new Promise(function(resolve) {
setTimeout(function() {resolve("I love You !!");}, 3000);
});
document.getElementById("demo").innerHTML = await myPromise;
}
myDisplay();
async function getFile() {
let myPromise = new Promise(function(resolve) {
let req = new XMLHttpRequest();
req.open('GET', "mycar.html");
req.onload = function() {
if (req.status == 200) {
resolve(req.response);
} else {
resolve("File not Found");
}
};
req.send();
});
document.getElementById("demo").innerHTML = await myPromise;
}
getFile();