JavaScript Training Workshop

Hosted by Ravin, Martin & Paschal

๐Ÿ‘‹ Introduction to JavaScript

JavaScript is a core web technology that enables interactive and dynamic websites. In this 3-hour session, we'll cover the basics using PHPStorm + Live Server and Bootstrap for a practical, hands-on experience.

Note: Find the project folder in your training materials. This website will be available until August 2025.

Let's begin with a short video introduction of the history of JavaScript

JavaScript in 100 Seconds - Fireship JavaScript for Haters - Fireship

๐Ÿง  Basic Syntax

JavaScript code can be written inline within a <script> tag in an HTML file or in an external .js file referenced using the src attribute. Always place scripts at the bottom of the <body> element.

<!DOCTYPE html>
<html lang="en">
  <head>
    ...
  </head>
  <body>
    ...
    <script>
      // Inline script
    </script>
    <script src="externalScript.js"></script>
  </body>
</html>

Note: Use let or const instead of var. Use === for strict equality checks. Avoid using ==, as it can lead to unexpected results due to type coercion.


var price = 2; // Var is used on older browsers and not anymore 
const price1 = 5; // We use const to hard code the variable
const price2 = 6;
let total = price1 + price2; //While here we can cahnge the value of total later
                  

Note

The var keyword was used in all JavaScript code from 1995 to 2015.
The let and const keywords were added to JavaScript in 2015.
The var keyword should only be used in code written for older browsers.

๐Ÿ“š Variables and Data Types

Use const for unchanging values and let for values that change. Variable names should use camelCase and are case-sensitive. JavaScript is weakly typed, so types donโ€™t need to be declared and can change.

Data Types:

Data Type Example typeof Returns
number 5, 3.14, 34e-2, 2_500 number
string "string 1", 'string 2', `string 3` string
boolean true, false boolean
array ['red', 'green', 'blue'] object
object {firstName: 'John', lastName: 'Doe'} object
null null object
undefined undefined undefined

Remark: Arrays and null are objects, not primitive types. Every statement ends with a semicolon (;). Avoid using var due to its issues (learn more).

const nr = 17;
const str = "John Doe";
const bool = true;
const arr = ["red", "green", "blue"];
const obj = { firstName: "John", lastName: "Doe" };
const noValue = null;
const undef = undefined;

console.log("typeof nr:", typeof nr); // number
console.log("typeof str:", typeof str); // string
console.log("typeof bool:", typeof bool); // boolean
console.log("typeof arr:", typeof arr); // object
console.log("typeof obj:", typeof obj); // object
console.log("typeof noValue:", typeof noValue); // object
console.log("typeof undef:", typeof undef); // undefined

Note

The statement console.log() is used to print values to the console of your browser. Think of it as the print() function in Python. The log() method writes logs to the console which is really useful for debugging and testing purposes. To open a console in most browsers, use F12.

๐Ÿ’ฌ Comments

Use // for single-line comments or /* */ for multi-line comments. In PhpStorm, use Ctrl + / for single-line and Ctrl + Shift + / for multi-line comments.

// This is a single line comment

/* This comment section
   spans several
   lines */

๐Ÿ“œ Console Log

Use console.log() to output to the browserโ€™s console for debugging. Label outputs clearly. Use console.error() for errors (red) or console.warn() for warnings (yellow).

const name = "John";
const age = 35;
// without template literals
console.log("name", name, "age", age); // Good
// with template literals
console.log(`My name is ${name} and I am ${age} years old`);

Debugging Tip: Use browser debuggers instead of excessive console.log() statements. Learn more: Chrome Debugger, Firefox Debugger.

โž• Arithmetic Operators

Operator Description Example Result
+ Addition x + y Sum of x and y
- Subtraction x - y Difference of x and y
* Multiplication x * y Product of x and y
/ Division x / y Quotient of x and y
% Modulus x % y Remainder of x divided by y
** Power x ** y x to the power y
++ Post/Pre Increment x++, ++x Increment x
-- Post/Pre Decrement x--, --x Decrement x

Remark: The + operator also concatenates strings (e.g., "John" + " " + "Doe" yields "John Doe").

let x = 10;
let y = 3;
console.log(`x + y = ${x + y}`); // 13
console.log(`x - y = ${x - y}`); // 7
console.log(`x * y = ${x * y}`); // 30
console.log(`x / y = ${x / y}`); // 3.333...
console.log(`x % y = ${x % y}`); // 1
console.log(`x ** y = ${x ** y}`); // 1000
console.log(`x++ = ${x++}, x = ${x}`); // 10, 11
console.log(`++y = ${++y}, y = ${y}`); // 4, 4

๐Ÿ“ Assignment Operators

Operator Description Example Result
= Assign x = y
+= Add and assign x += y x = x + y
-= Subtract and assign x -= y x = x - y
*= Multiply and assign x *= y x = x * y
/= Divide and assign x /= y x = x / y
%= Modulus and assign x %= y x = x % y
let x = 10;
const y = 2;
const z = 3;
x += y; // x = 12
x -= z; // x = 9
x *= z; // x = 27
x /= z; // x = 9
x %= y; // x = 1
console.log(`x = ${x}`);

โš–๏ธ Comparison Operators

Operator Description Example Result
== Equal x == y true if equal
=== Identical x === y true if equal and same type
!= Not equal x != y true if not equal
!== Not identical x !== y true if not equal or different type
< Less than x < y true if x < y
<= Less than or equal x <= y true if x <= y
> Greater than x > y true if x > y
>= Greater than or equal x >= y true if x >= y
const x1 = 10;
const x2 = "10";
const y = 5;
console.log(`x1 == x2: ${x1 == x2}`); // true
console.log(`x1 === x2: ${x1 === x2}`); // false
console.log(`x1 !== y: ${x1 !== y}`); // true
console.log(`x1 < y: ${x1 < y}`); // false
console.log(`x1 > y: ${x1 > y}`); // true

๐Ÿ”— Logical Operators

Operator Example Result
&& x && y true if both x and y are true
|| x || y true if x or y is true
! !x true if x is false
const x = 6;
const y = 4;
console.log(`x < 8 && y > 3: ${x < 8 && y > 3}`); // true
console.log(`x < 8 && y > 6: ${x < 8 && y > 6}`); // false
console.log(`x < 8 || y > 3: ${x < 8 || y > 3}`); // true
console.log(`!(x < 8 || y > 6): ${!(x < 8 || y > 6)}`); // false

๐Ÿ”€ Selection

if:

if (condition) {
  // code if condition is true
}

if - else:

if (condition) {
  // code if condition is true
} else {
  // code if condition is false
}

if - else if - else:

let score = 88;
if (score >= 90) {
  console.log("A");
} else if (score >= 80) {
  console.log("B");
} else {
  console.log("Try again");
}

switch:

switch (expression) {
  case x:
    // code
    break;
  case y:
    // code
    break;
  default:
    // code
}

Warning: Always include break in switch cases to prevent fall-through.

โน๏ธ Break and Continue

Break: The break statement is used to exit a loop or switch statement prematurely when a specific condition is met.


for (let i = 0; i < 10; i++) {
  if (i === 5) {
    break; // Exit the loop when i equals 5
  }
   console.log(i);
}
// Output: 0, 1, 2, 3, 4

Continue: The continue statement skips the current iteration of a loop and moves to the next iteration.


for (let i = 0; i < 10; i++) {
  if (i % 2 === 0) {
    continue; // Skip even numbers
  }
  console.log(i);
  }
// Output: 1, 3, 5, 7, 9

Note: Use break to stop a loop entirely, and continue to skip specific iterations without stopping the loop.

๐Ÿ” Iteration

for:

const end = 10;
for (let i = 0; i <= end; i++) {
  console.log(i);
}

while:

let i = 0;
const end = 10;
while (i <= end) {
  console.log(i);
  i++;
}

do while:

let i = 0;
const end = 10;
do {
  console.log(i);
  i++;
} while (i <= end);

Remark: do while loops run at least once.

forEach (Arrays):

const array = ['red', 'green', 'blue'];
array.forEach((element, index) => {
  console.log(`Element ${index}: ${element}`);
});

๐Ÿงต String Object

Strings represent sequences of characters, written with single quotes, double quotes, or backticks (template literals).

const string1 = "A string primitive";
console.log("typeof string1:", typeof string1); // string
const string2 = new String("A String object");
console.log("typeof string2:", typeof string2); // object

Template Literals:

const a = 5;
const b = 7;
console.log(`${a} + ${b} = ${a + b}`); // 5 + 7 = 12

Common Properties/Methods:

Property/Method Description
length The length of a string
charAt(n) Returns character at position n
indexOf(str) Position of first occurrence of str (-1 if not found)
lastIndexOf(str) Position of last occurrence of str (-1 if not found)
startsWith(str) True if string begins with str
endsWith(str) True if string ends with str
includes(str) True if string contains str
concat(str1, [str2]) Concatenates strings
replace(pattern, str) Replaces matches with str
toLowerCase() Converts to lowercase
toUpperCase() Converts to uppercase
trim() Removes whitespace from both ends
match(regex) Returns array of regex matches or null
split(pattern) Splits string into array based on pattern
substring(n1, [n2]) Portion of string from n1 to n2

๐Ÿ”ข Number Object

Common Methods:

Method Description
toFixed(digits) Formats number as string with fixed decimals
Number.isInteger(value) True if value is an integer
parseInt(str) Converts string to integer
parseFloat(str) Converts string to floating-point number

Tip: Use + before a string (e.g., +'5.5') as an alternative to parseFloat.

console.log(Number.parseInt("42")); // 42
console.log(+"5.5"); // 5.5

๐Ÿ“ Math Object

The Math object provides mathematical constants and methods.

Common Property: Math.PI (~3.14159)

Common Methods:

Method Description
Math.ceil(x) Rounds x up
Math.floor(x) Rounds x down
Math.round(x) Rounds x to nearest integer
Math.random() Random number between 0 and 1
Math.abs(x) Absolute value of x
console.log(Math.PI); // 3.14159...
console.log(Math.round(4.7)); // 5

๐Ÿ“… Date Object

Create dates with new Date(). Results depend on browser timezone.

Constructors:

  • new Date(): Current date/time
  • new Date(year, month, day, hours, minutes, seconds, ms)
  • new Date(ms): Milliseconds since Jan 1, 1970
  • new Date(dateString)

Common Methods:

Method Description
getDay() Day of week (0-6)
getDate()/setDate() Day of month (1-31)
getMonth()/setMonth() Month (0-11)
getFullYear()/setFullYear() Year
toLocaleString() Browser default format
toISOString() ISO format
const d = new Date(2020, 0, 31);
console.log(d.toLocaleString());

Tip: Use libraries like Day.js for advanced date handling.

โš™๏ธ Functions

Functions start with function, followed by parameters and code in {}. Parameters can have default values.

function writePersonalMessage(name = "Mr./Mrs.") {
  console.log(`Dear ${name}, we hope you like this JavaScript course!`);
}
writePersonalMessage("John"); // Dear John, ...
writePersonalMessage(); // Dear Mr./Mrs., ...

Declaration vs. Expression:

function sum1(a, b) { // Declaration
  return a + b;
}
const sum2 = function(a, b) { // Expression
  return a + b;
};
console.log(sum1(5, 8)); // 13
console.log(sum2(5, 8)); // 13

Remark: Declarations are hoisted; expressions are not.

Arrow Functions:

const sum = (a, b) => a + b; // Shorthand
console.log(sum(5, 8)); // 13

Timing Functions:

let timer = setInterval(() => console.log("Tick"), 1000);
setTimeout(() => clearInterval(timer), 5000);

๐ŸŽฎ Live Code Playground

Use the floating button { } at the bottom right to open the interactive code playground in split-screen mode.

๐Ÿ† JavaScript Challenges

Select Challenge:

Completed

Expected output:

Hint:

Output:


                      
Correct! Your solution matches the expected output.

Sample Solution


                      

Explanation:

๐ŸŽ‰ Congratulations!

You've completed all JavaScript challenges! Great job mastering these concepts.

๐Ÿงช Practice Challenges

  • Create a function that returns the sum of two numbers.
  • Loop from 10 to 1 and print each number.
  • Check if a string is a palindrome.
  • Find the largest number in an array.
  • Use a switch statement to return grades based on scores.

๐Ÿง  JavaScript Quiz

๐ŸŽฏ Kahoot Quiz

Wrap up with a fun Kahoot quiz to test your skills!

Extra

Complete all challenges to unlock this section automatically, or click the button to access it now.

Note: This is not part of the course but it is something really fun we found and wanted to share with you, we will only cover this part if we have time left.

Extra

Do you know that it is possible to run the same file with the same code in 2 different lanugages. This is called Polyglot and it is a fun thing I foun and played around with. This works with a lot of languages, and to see more about them we found this video

this code runs in both JS and Python. - Evan Zhou GitHub link


eval(["console.log('Hello, js!')", "print('Hello, py!')"][(-1 % 2 + 1) >> 1])

                        

To install the npm module to make this possible


npm i polycompiler
                          

To run the code create a file with the extention .js.py and paste this code

To run the code in Python: python {filename}.js.py
To run the code in JavaScript: node {filename}.js.py

๐ŸŽฎ Live Code Playground

Output: