JavaScript Basics - martindubenet/wed-dev-design GitHub Wiki

JavaScript Basics  ][  JavaScript Tricks  ][  Vue.js & Vuetify  ]

JavaScript Basics

 

Lexicon

  1. CRUD : Create, Read, Update, and Delete

 

#1. JavaScript nomenclature

Query selector

<script>
    const p = document.querySelector('p');
    console.log('p');
</script>

 

#1.1 Variables and Statements

Semi-columns { } are code blocks.

New variables in JavaScript are declared using one of three keywords: let, const, or var. The first two been more modern (part of ES6) and precise are a Best Practices while var, who is NOT obsolete but just not a good practice, was traditionally the only way to declare a variable in JavaScript. A variable declared with the var keyword is available from the function it is declared in.

declaration efficiency editable type level description
const ★★★ Constant Block It allows you to declare variables whose values are never intended to change (within its original scope).
let ★★☆ Variable Block The declared variable is available from the block it is enclosed in.
var ★☆☆ Variable Function It is also the most common declarative keyword because it dates back from the beginnings of JS. It does not have the restrictions that the other two keywords have.

If you declare a variable without assigning any value to it, its type is undefined.

We use these variable statements only the first time we declare a variable. Once it is declare just refer to it by its name without the statement as prefix.

Typographical convention

  1. ★★★ chamelCase
  2. ★★☆ snake_case
  3. ★☆☆ PascalCase
  4. ☆☆☆ kebab-case ❌

Although PascalCase is NOT an error, Good Practice is to start with a lower chamelCase character since Uppercase refers to a class.

Prefixes: a > z

Dolor signs ($) and Underscores (_) are the only NOT alphabetical characters that can be used at the beginning of a variable name BUT you should NOT use them because every time a developer sees these two characters he/she refers to it as:

  1. Dolor signs ($) is used by the very popular jQuery.
  2. Underscores (_) is used by an other popular library called LoDash.

Summary #1

// Function scoped
var functionVariable    = 'Old fashion editable variable';

// Block scoped
const blockVariable1    = true; // default
let blockVariable2      = 'New editable variable';

 

#1.2. Objects

Air quotes or sub-variables contains within an object:

// In file.js
const person = {
  firstName: 'John';
  lastName: 'Tremblay';
  age: 50
};

// In console
person.firstName
//> John

 

#1.3. Types

JavaScript programs manipulate values, and those values all belong to a type.

developer.mozilla

To know what type of a value (in web inspector console) just type typeof. (ex: typeof thisValue)

Common types:

  1. String are sequences of UTF-16 Unicode characters. At it's core a string is an array composed of a simple set of alphanumeric Unicode character values. We can use strings like objects. They have methods that allow you to manipulate the string and access information about them.
  2. Number and it’s BigInt (Big Interger) variant.
  3. Boolean
  4. Symbol (new in ES2015) is a way to do unique identifier in JavaScript.
  5. Object
  6. null
  7. undefined

String type

Backtick «`»

We can compose a multi-line declaration when incapsulated within back-tick characters (instead of single or double quotes).

Interpolation

Interpolation is when you put a variable within a string.

Summary

When within backticks (instead of quotes) a string can print an interpolation.

let quotedString          = 'Martin';
const backtickedString    = `Hello my name is ${quotedString}. I am ${2021 - 1971} years old.`;
const backtickedHtmlBlock = `
  <div>
    <p>${backtickedString}</p>
  </div>
`;
document.body.innerHTML = backtickedHtmlBlock;

Number type

We can do maths right from within the web inspector console using Math.…. (ex: Math.PI * myVarTypeNumber)

Mathematical terms translation

type english french
+ Operator Addition Addition
++ Increment Incrémentation
- Operator Subtraction Soustraction
-- Decrement Décrémentation
* Operator Multiplication Multiplication
/ Operator Division Division
% Operator Modulo Reste
** Operator Exponent Exposant
+= Assignmentation Addition Addition
-= Assignmentation Subtraction Soustraction
*= Assignmentation Multiplication Multiplication
/= Assignmentation Division Division
**= Assignmentation Exponent Exposant
=== Comparaison Strict equality Égalité stricte
!== Comparaison Strict-non-equality Non-égalité stricte
< Comparaison Less than Inférieur à
> Comparaison Greater then Supérieur à
<= Comparaison Less than or equal to Inférieur ou égal à
>= Comparaison Greater than or equal to Supérieur ou égal à
! Logical NOT ET
|| Logical OR OU
&& Logical AND ET
||= Logical assignment OR Affectation après le OU logique
&&= Logical assignment AND Affectation après le ET logique
??= Logical assignment Nullish Affectation après la coalescence des nuls

Round

Rounds decimals to a specific number of digits. See Stackoverflow about this

let myNumber = 99.5599
Math.round(myNumber * 100) / 100
//> 99.56

Floor -VS- Ceil

Math.floor(20.9999)
//> 20
Math.ceil(20.9999)
//> 21

Modulo operator %

In mathematics modulo is the left over of a division

// 10 cyclists for 3 tandem bikes. How many won't ride?
10 % 3
//> 1

Not a number

NaN : «Not a Number» is a (type) number!

Equals in Boolean type

  1. === : Checks that both value AND type are the sames.
  2. == : Checks ONLY the value.

Integer VS strings

Toggle it toString or parseInt

let $string = '99';
let $digit  = parseInt($string);
let $string = $digit.toString();

 

#1.4 States

boolean state true empty null undefined false
Truthy (1)
Falsy (0)

Falsy -VS- Truthy boolean statements

All (declared) values are truthy unless they are defined as falsy.

  • A falsy (sometimes written “falsey”) value is a value that is considered false when encountered in a Boolean context.
  • A truthy value is a value that is considered true when encountered also in a Boolean context.

Null -VS- Undefined -VS- Empty statements

  • An undefined statement is declared, it exist in the code, but no value as been assigned to it.
  • A null statement is both declared and defined but the assigned value is null.
  • An empty statement is used to provide no statement, although the JavaScript syntax would expect one.
let undefinedVar;
let nullVar = null;
let emptyVar = '';

In JavaScript null is a primitive value that represents the intentional absence of any object value.

Conditional (ternary) operator

This operator is frequently used as a shortcut for the if statement.

myVar ? positiveState : negativeSate;
myString ? '👍' : '👎';

 

#1.5. Properties

Properties are the values associated with a JavaScript object.
A JavaScript object is a collection of unordered properties.
Properties can usually be changed, added, and deleted, but some are read only.

w3schools

Access nested objects using either dot or brackets:

  • myObj.cars.car2;
  • myObj.cars["car2"];
  • myObj["cars"]["car2"];

 

#1.6. Methods

Methods are functions stored as object properties.

w3schools

In a function this is a reserve keyword that refer to the owner of that function.

Object Methods

const objectName = {
    staticProperty: 'This is a string stored as an object property',
    dynamicProperty: {
        return 'This is a function stored as an object property';
    }
}

To access an object method : objectName.dynamicProperty()

  • name = objectName.dynamicProperty(); : Access the method (to execute the function),
  • name = objectName.dynamicProperty; : Returns the function definition.

 

#2. Functions

« What hapens in a function stays in a function »

A particularity of JavaScript is the ability to pass functions within functions which is not a common feature in programming languages.

#2.1 Parameters and Arguments

  1. Parameters are variables listed as a part of the function definition.
  2. Arguments are values passed to the function when it is invoked.

A parameter is a named variable passed into a function. Parameter variables are used to import arguments into functions.

An argument can be a parameter OR an object

In this case it is implicitly passed just like the this parameter. It is a local variable accessible within all functions and contains an entry for each argument passed to that function. The arguments object is an array-like construct which can be used to access arguments passed to the function even if a matching parameter isn’t explicitly defined.
(source)

function nameOfFunction(parameter) {
  console.log(parameter); // Output = foo
}

const argument = 'foo';

nameOfFunction(argument);

By default Function's variables are NOT accessible outside of the body of that function. To have access to the function results you have to:

  1. Define a function,
  2. Name the function,
  3. Return it from within the function body (Implecit return),
  4. Call (or Run) it from outside the function body,
  5. Capture the returned function as a new global variable.

In a function anything declared AFTER the return line will get ignore because the return declares the end of the processing.

// Definition of the function
function nameOfFunction() {
    // Body of the function (or Block)
    const functionVariable = 100 * 1.13;

    return nameOfFunction;
}

// Capture the called function as a global variable
const globalVariable = nameOfFunction();

Arguments

function nameOfFunction(functionArgument) {
    return `The function argument is ${functionArgument}`;
}

#2.2 Expressions and Operators

Expressions VS Statements

Any unit of code that can be evaluated to a value is an expression. Since expressions produce values, they can appear anywhere in a program where JavaScript expects a value such as the arguments of a function invocation.

A statement is an instruction to perform a specific action. Such actions include creating a variable or a function, looping through an array of elements, evaluating code based on a specific condition etc. JavaScript programs are actually a sequence of statements.

Hoisting

«Functions are first class citizen, they are happy when privileged!»

Anonymous function is NOT valid in JavaScript …

function(anonymousFunction) {
    return `This ${anonymousFunction} is NOT valid!`;
}

… But an anonymous function contained within a variable IS VALID even if it gives you errors …

const containedFunctionVariable = function(anonymousFunction) {
    return `This contained ${anonymousFunction} is VALID but gives errors.`;
}

… But if you declare it in a regular declaration format it turns out VALID without errors

function declaringFunction(anonymousFunction) {
    return `This declared ${anonymousFunction} is VALID without errors!`;
}

… This is because functions are hoisted and variables are NOT.

Hoisting is JavaScript’s default behavior of moving declarations to the top.

Arrow functions

The fat arrow =>, a function inception symbol

In programming => is called a fat arrow -VS- -> are skinny arrow.

No brackets shorthand method

Some arrow functions use parentheses () while others use braces (curly brackets) {} . This key difference is that parentheses will implicitly return the last statement while braces require an explicit return statement.

This method of declaring functions in JavaScript dates from ES6 (2015). Arrow functions introduced a new way of writing concise functions. It’s like a one line method of declaring functions contained within variables.

// 1. Original function
function inchToCm(inches) {
    const cm = inches * 2.54;
    return cm;
}

// 2. Slightly optimised function
function inchToCm(inches) {
    return inches * 2.54;
}

// 3. Make this a variable contained function
const inchToCm = function(inches) {
    return inches * 2.54;
}

// 4. A more concise (explicit return) method
const inchToCm = (inches) => {
    return inches * 2.54;
}

// 5. Implecit return method (one line without curly brackets)
const inchToCm = (inches) => inches * 2.54;

// 6. When only one argument it does NOT requires parentheses
const inchToCm = inches => inches * 2.54;

Immediately Invoked Function Expression (IIFE)

In JavaScript parenthesis () are prioritised for the rendering order.

The following function is NOT valid because it is NOT run first…

function() {
   return 'NOT Valid function generates an ERROR';
}

… Wrap the same undefined function within parenthesis () will make it run first…

(function() {
   return 'OK function';
});

… Add an other set of parenthesis () at the end and VOILÀ!

(function() {
   return 'VALID function!';
})();

Closures

JavaScript is able to create functions within a function and can still reach outside to the parent function scope even when this parent is done running. It's values are still in memory, so accessible at a later time. Useful for complex context where a same function deserve a larger needs.

 

#3. Debugging tools

Console log options

console.log('Any string of text');
console.error('This displayes a RED flag');
console.warning('This displays a YELLOW flag');
console.table([{th1:'td1', th2:'td2', th3:3}]);
console.dir(document);

console.clear();

console.group('Any group identifier');
console.log('First item');
console.log('Second item');
console.groupEnd('Any group identifier');

console.time('Counter');
for(var i = 0; i < 2000; i++){
  console.log(i);
}
console.timeEnd('Counter');

Browser web inspectors

 

#4. Object Oriented Programming (OOP)

Object oriented method

 

 

⚠️ **GitHub.com Fallback** ⚠️