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:
Enclosed text in quotes:
Quotes are not needed for numbers:
The console.log() function can be used as many times as needed:
JavaScript in HTML
You can add JavaScript code in an HTML document using the <script> tag:
Alert Box display messages with the alert() function
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
Logic
JavaScript uses the basic programming operators for math such as +
. -
, /
, *
, including (
, and )
, for order of operations.
Increment operator ++
adds 1 to a variable
Decrement operator --
subtracts 1 from a variable
Combining Arithmetic operators with increment/decrement operators looks like the sample below:
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
:
OR
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:
Constants
Constants must have a value when declared and they cannot change their value.
The typeof
operator checks the value to its right and returns, or passes back, a string of the data type.
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:
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.
For this example below, if the total amount is equal to or above 300 it will be discounted by 15%.
Loops
For Loop
The for
loop has the following syntax:
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:
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.
While Loop
Last updated