This section I will cover Javascript fundamentals, again this is more of a cheatsheet guideand I won't be going into to get detail on the basic commands as they are very similar to other programming languages. I will be covering four areas, syntax, data types, flow-control and function.
Javascript syntax is very simular to other programming languages, so if you another language you should have no issues learning Javascript. Javascript is case-sensitive so a variable or test and Test are different. Javascript also uses the semi-colon (;) to terminate the end of a statement, however this is not enforced but good practice. A identifier is the name of a variable and have a number of rules
Variable syntax | let var1 = 5; let doSomething = 10; let _underscore = 15; |
You can use comments in Javascript
Comments | // single line comment /* multi-line comment some more information */ |
A Javascript statements block uses curly braces
Statement Block | if (test) { // do some stuff } |
Javascript has a number of keywords which you are not allowed to use as variable/function/etc names
Keywords | |||
break | do | in | typeof |
case | else | instanceof | var |
catch | export | new | void |
class | extends | return | while |
const | finally | super | with |
continue | for | switch | yield |
debugger | function | this | enum (future) |
default | if | throw | await (future) |
delete | import | try |
Lets take a look at variables, in Javascript they are loosely typed unlike Java for instance, this means a variable can hold any type of data, you can declare three types of variables
var example | var message = "hi"; // Global variable message = 100; // legal, but not recommended function test() { var message = "hi"; // local variable } function foo() { console.log(age); var age = 26; // Javascript will hoist this variable up to the top of the function, regardless } foo(); // this will work for (var i = 0; i < 5; ++i) { // using var in loops means it will affect any global variables, use let // do loop things } console.log(i); // 5 |
let example | let message = "hi"; var message = "hi"; let message = "hi"; // you cannot do this as message has already been declared if (true) { let age = 26; // this variable is only available inside the block console.log(age); // let age = 26; // You cannot do hoisting with let } console.log(age); // ReferenceError: age is not defined for (let i = 0; i < 5; ++i) { // let is ideal for for loops // do loop things } console.log(i); |
const example | const age = 26; age = 36; // you cannot overwrite a constant const name = 'Matt'; // constants are blocked scoped if (true) { const name = 'Nicholas'; // this constant only refers to the block } console.log(name); // Matt const person = {}; person.name = 'Matt'; // ok because the underlying data type is modifiable |
There are a number of different data types in Javascript
Here are some examples
undefined | let message; console.log(message == undefined); // true console.log(typeof message); // "undefined" if (message) { // undefined is False // This block will not execute } |
null | let message = null; console.log(typeof message); // null is a empty pointer Object if (message) { // null is False // This block will not execute } |
boolean | let found = true; let lost = false; Note: - 1 is not equal to true and 0 is not equal to false - non-empty string is true, string of "" is false - any non zero number is true, 0 and NaN is false - any objct is true, null is false - undefined is false |
string | # You can use single-quotes, double-quotes or backticks (you cannot mix and match), Strings are 16-bit Unicode characters # JavaScript use character literials like \n, \t, \b, \\, \", etc let firstName = "Paul"; let lastName = 'Valle'; let longWord = `supercalifragilisticexpialidocious` let text = "This is the letter sigma: \u03a3."; // using unicode console.log(text.length); // obtain the length of a string let age = 11; let ageAsString = age.toString(); // the string "11" // convert number into a string (there is also a String() Function) let value = 5; let exponent = 'second'; // Old and New way to perform interpolation let interpolatedString = var1 + ' is equal to ' + var2; let interpolatedTemplateLiteral = `${ var1 } is equal to ${ var2 }`; // notice the backticks |
number | // Use the Number.MIN_VALUE (5e–324) and Number.MAX_VALUE (1.7976931348623157e+308) on most browsers // NaN (Not a Number) is a special value which is used to indicate if a returned results is a number // There are three functions to convert numbers Number(), parseInt(), parseFloat() let intNum = 55; // integer let octalNum1 = 070; // octal for 56 let hexNum1 = 0xA; // hexadecimal for 10 let floatNum1 = 1.1; let floatNum2 = 0.1; let floatNum3 = .1; // valid, but not recommended let floatNum = 3.125e7; // equal to 31250000 console.log(isNaN(NaN)); // true console.log(isNaN(10)); // false - 10 is a number console.log(isNaN("10")); // false - can be converted to number 10 console.log(isNaN("blue")); // true - cannot be converted to a number console.log(isNaN(true)); // false - can be converted to number 1 let num1 = Number("Hello world!"); // NaN let num2 = Number(""); // 0 let num3 = Number("000011"); // 11 let num4 = Number(true); // 1 let num1 = parseInt("1234blue"); // 1234 let num2 = parseInt(""); // NaN let num3 = parseInt("0xA"); // 10 - hexadecimal let num4 = parseInt(22.5); // 22 let num1 = parseFloat("1234blue"); // 1234 - integer let num2 = parseFloat("0xA"); // 0 let num3 = parseFloat("22.5"); // 22.5 let num4 = parseFloat("22.34.5"); // 22.34 |
object | # You create a empty Object and then add properties/methods to it, each object has a number of built-in properties and methods # constructor, toString(), valueOf(), isPrototypeof(object), hasOwnProperty(propertyName), # propertyIsEnumerable(propertyName) and toLocaleString() let o = new Object(); Note: I will have whole section on Objects and OOP |
function | see functions below |
symbol | # Symbols are primitive values, and symbol instances are unique and immutable. let sym = Symbol(); console.log(typeof sym); // symbol let genericSymbol = Symbol(); let otherGenericSymbol = Symbol(); let fooSymbol = Symbol('foo'); console.log(fooSymbol); // using a symbol as a key, results in Symbol(foo) let fooGlobalSymbol = Symbol.for('foo'); console.log(typeof fooGlobalSymbol); // using global symbols, results in "object" Note: I will be covering Objects in another section but symbols can used for Objects keys There are a number of well known symbols for example Symbol.iterator, Symbol.hasInstance, Symbol.replace, etc |
Operators are used to manipulate data values, there are matematical, bitwise, relational and equality operators.
Unary Operators | |
increment/decrement | ++age; // prefix, same as age = age + 1; --age; // prefix age++; // postfix --age; // postfix let num3 = num1-- + num2; // you can use complex algorithms (but try not too be too clever) |
plus/minus | let num = 25; num = +num; // number is already positive console.log(num); // 25 let num = 25; num = -num; console.log(num); // -25 |
Bitwise Operators | |
NOT | let num1 = 25; // binary 00000000000000000000000000011001 let num2 = ~num1; // binary 11111111111111111111111111100110 console.log(num2); // -26 |
AND/OR | let result = 25 & 3; console.log(result); // 1 let result = 25 | 3; console.log(result); // 27 |
XOR | let result = 25 ^ 3; console.log(result); // 26 |
left shift | let oldValue = 2; // equal to binary 10 let newValue = oldValue << 5; // equal to binary 1000000 which is decimal 64 |
signed/unsigned right shift | let oldValue = 64; // equal to binary 1000000 let newValue = oldValue >> 5; // equal to binary 10 which is decimal 2 let oldValue = 64; // equal to binary 1000000 let newValue = oldValue >>> 5; // equal to binary 10 which is decimal 2 |
Boolean Operators | |
logical NOT | console.log(!false); // true console.log(!"blue"); // false console.log(!0); // true console.log(!NaN); // true console.log(!""); // true console.log(!12345); // false |
logical AND/OR | let var1 = false; let var2 = true let result1 = (var1 && var2); let result1 = (var1 || var2); |
Multiplicative Operators | |
add/subtract | let result = 1 + 2; let result = 2 - 1; |
multiply/divide | let result = 34 * 56; let result = 66 / 11; Note: if you divide by zero you get a NaN |
modulas | let result = 26 % 5; // equal to 1 |
Exponentiation Operators | |
exponentiation | console.log(Math.pow(3, 2); // 9 console.log(3 ** 2); // 9 console.log(Math.pow(16, 0.5); // 4 console.log(16** 0.5); // 4 |
Relational Operators | |
relational | let result1 = 5 > 3; // true let result2 = 5 < 3; // false let result = "Brick" < "alphabet"; // true, you can even use strings |
Equality Operators | |
equal | let result1 = ("55" == 55); // true - equal because of conversion let result2 = ("55" === 55); // false - not equal because different data types Note: three equal signs (===) is the identical equal operator |
NOT equal | let result1 = ("55" != 55); // false - equal because of conversion let result2 = ("55" !== 55); // true - not equal because different data types |
Conditional and Assignment Operators | |
conditional | variable = boolean_expression ? true_value : false_value; Note: Also known as the ternary operator |
assignment | let num = 10; num = num + 10; let num = 10; num += 10; Note: other assigment operators are *=, /=, %=, +=, -=, <<=, >>= and >>>= |
Comma Operators | |
comma | let num1 = 1, num2 = 2, num3 = 3; let num = (5, 1, 4, 8, 0); // num becomes 0 as its the last number |
Javascript provides the standard set of flow-contrl statements, if, while, for, switch and a few that is specific to to the language
if statement | if (i > 25) { console.log("Greater than 25."); } else if (i < 0) { console.log("Less than 0."); } else { console.log("Between 0 and 25, inclusive."); } |
do-while statement | let i = 0; do { // the loop will always execute at least once i += 2; } while (i < 10); |
while statement | let i = 0; while (i < 10) { i += 2; } |
for statement | let count = 10; for (let i = 0; i < count; i++) { console.log(i); } |
for-in statement | for (const propName in window) { document.write(propName); } |
for-of statement | for (const el in [2,4,6,8) { // is a good idea to use a const document.write(el); } |
Labeled statements | start: for (let i = 0; i < count; i++) { console.log(i); } Note: also see break and continue below as they can use labelled statements |
break and continue statements | let num = 0; for (let i = 1; i < 10; i++) { if (i % 5 == 0) { break; // the for loop will be broken out when i reaches 5 } num++; } console.log(num); // the result will be 4 ------------------------------------------------------------------------------------------ let num = 0; for (let i = 1; i < 10; i++) { if (i % 5 == 0) { continue; // when the loop reaches 5 it will jump back to the for loop and num will not be increased } num++; } console.log(num); // the result will be 8 ------------------------------------------------------------------------------------------ let num = 0; outermost: for (let i = 0; i < 10; i++) { for (let j = 0; j < 10; j++) { if (i == 5 && j == 5) { break outermost; // when code reaches here it will jump outside the for loop } num++; } } console.log(num); // 55 ------------------------------------------------------------------------------------------ let num = 0; outermost: for (let i = 0; i < 10; i++) { for (let j = 0; j < 10; j++) { if (i == 5 && j == 5) { continue outermost; // When thcode reaches it will jump to the outer loop and continue } num++; } } console.log(num); // 95 |
with statement | with(location) { // loop over location let qs = search.substring(1); // search.substring(1) will be location.search.substring(1) let hostName = hostname; // hostname will be lcoation.hostname let url = href; // href will be location.href } |
switch statement | switch (expression) { case value1: statement break; // use break statements otherwise code will fall through case value2: statement break; case value3: statement break; case value4: statement break; default: statement } |
Functions are blocks of code that perform an action, you can pass data into the function which are called arguments, data can also be returned.
basic function with arguments | function sayHi(name, message) { console.log("Hello " + name + ", " + message); } |
function that returns data | function sum(num1, num2) { return num1 + num2; } |
function with multiple returns | function diff(num1, num2) { if (num1 < num2) { return num2 - num1; // you can have multiple return statements } else { return num1 - num2; // you can have multiple return statements } } |