JavaScript

The console is part of the web browser and allows you to log messages, run JavaScript code, and see errors and warnings. \

JS Basics

Example function used to generate output to the console:

console.log("Hello Humans!");

Enclosed text in quotes:

console.log("I love free cyber training");

Quotes are not needed for numbers:

console.log(1337);

The console.log() function can be used as many times as needed:

console.log("Hello Humans!");
console.log("Take me to your leader");

JavaScript in HTML

You can add JavaScript code in an HTML document using the <script> tag:

<body>
    <script>
      console.log("JavaScript in HTML");
    </script>
</body>

Alert Box display messages with the alert() function

<body>
    <script>
      alert("I think I can learn XSS now");
    </script>
</body>

Comments

Comments are used to describe code and other information A single-line comment starts with //

Multi-line comments start with /* and end with */ making everything in between a comment

//I wonder if I can display two messages in the same script tag

/* The code below
should suffice
for testing */

<body>
    <script>
      console.log("JavaScript in HTML");
      alert("I think I can learn XSS now");
    </script>
</body>

Logic

JavaScript uses the basic programming operators for math such as +. -, /, *, including (, and ), for order of operations.

/* 30 days
1 day = 24 hours
1 hour = 60 minutes
1 minute = 60 seconds */

//Aproximately how many seconds are in a year?
console.log(60*60*24*30);

Increment operator ++ adds 1 to a variable

let count = 0;
count++;
console.log(count);

Decrement operator -- subtracts 1 from a variable

let score = 100;
score--;
score--;
console.log(score);

Combining Arithmetic operators with increment/decrement operators looks like the sample below:

let x = 8;
x++;
x/=3;
console.log(x); //Output should equal 3

Variables

  • variable names must begin with a letter, an underscore _ or a dollar sign $

  • variable names cannot contain spaces

  • variable names can only contain letters, numbers, underscores, or dollar signs.

  • variable names are case-sensitive, which means that, for example, Name and name variables are different

Create a variable (initialize) in JS with let or var:

let name;
name = "Martian";

OR

let name = "Martian";
let number = 1337

Note: the use of let is recommended instead of var when decalring variables

Remembering the definition of variable, remember that they can change on they fly:

let num = 7331;
num = 1337;
//num = 7;
console.log(num);

Constants

Constants must have a value when declared and they cannot change their value.

const cyberpsace = 'green';
console.log(color); color = 'blue'; //confirm this will not work

The typeof operator checks the value to its right and returns, or passes back, a string of the data type.

const unknown1 = 'foo';
console.log(typeof unknown1); // Output: string 

const unknown2 = 10;
console.log(typeof unknown2); // Output: number 

const unknown3 = true; 
console.log(typeof unknown3); // Output: boolean

Conditional (Ternary) operator

Conditional, or ternary, operators assign a value to a variable, based on some condition. This operator is frequently used as an alternative to an if else statement.

This is what the syntax would look like:

variable = (condition) ? value1: value2

It takes three operands: a condition followed by a question mark ?, then an expression to execute if the condition is true followed by a colon :, and finally, the expression to execute if the condition is false.

let lightyears = 42;
let allowedDistance = (lightyears < 5) ? "Too close to Earth": "Welcome to the void";
console.log(allowedDistance);

For this example below, if the total amount is equal to or above 300 it will be discounted by 15%.

let cost = 400;
cost = (cost >= 300) ? cost * 0.85 : cost;
console.log(cost);

Loops

For Loop

The for loop has the following syntax:

for (initializer; condition; final-expression) {
    // code to run
}

The initializer is a variable, which increments the number of times the loop has run.

The condition is used to stop the loop.

The final expression is run each time after the loop's code has run. It is usually used to increment the variable used in the condition. Each run of the loop is called an iteration.

Here is an example of a for loop outputting the number 1 to 10:

for (let i = 1; i <= 10; i++) {
    console.log(i);
}

The loop creates a variable called i and initializes it to 1.

Then, after each iteration, it increments the i variable by 1.

The loop stops when i reaches 11, breaking the condition.

Here is another loop in which each time the player shoots, the number of bullets should be decreased by 1.

for(let i=5; i>=0; i-=1) {
  console.log(`Bullets: ${i}`);
}

While Loop

Last updated