Getting Started with JavaScript
Last updated:
What is JavaScript?
High-level, interpreted programming language.
Versatile - can be used for a wide range of tasks such as creating web applications, developing mobile apps, building games, and even controlling robots. JavaScript is popular among web developers due to its simplicity, flexibility, and the vast number of libraries and frameworks available for it. Most significant advantage: used for both front-end and back-end programming.
Loosely typed language - variables do not need to be declared with a specific data type. This makes it easier to write and read code, but it can also lead to errors if not used carefully. TypeScript was created for this reason - is a superset of JavaScript that adds static typing to the language.
Constantly evolving - new updates and features are added regularly and have made JavaScript more powerful and efficient, making it easier for developers to write clean and readable code. See ECMAScript version history.
Tools
Environment
To check what version of Node we are running, type the following in a terminal:
node --version
v18.20.3
Editor
Any text editor can be used to write code. I’m using Visual Studio Code (aka VS Code), by far the most popular editor used by the JavaScript community.
VS Code themes and extensions:
- JavaScript Debugger (Nightly) - an extension for debugging Node.js programs and Chrome
- Babel JavaScript – VS Code syntax highlighting for today’s JavaScript
- Code Runner - Run code snippet or code file for multiple languages, including JavaScript
- GitHub Theme - GitHub theme for VS Code
In the Browser
HTML header
Using a script
tag inside the header
:
<html>
<head>
<title>Webpage</title>
<script type="text/javascript">
console.log("here");
</script>
</head>
<body></body>
</html>
HTML body
Using a script
tag inside the body
:
<html>
<head>
<title>Webpage</title>
</head>
<body>
<script type="text/javascript">
console.log("here");
</script>
</body>
</html>
External File
Given a file named app.js
, to include it in an HTML file named index.html
, located beside it:
<html>
<head>
<title>Webpage</title>
<script src="app.js"></script>
</head>
<body></body>
</html>
ES6 - import & export
In the example below, we’ll use 2 JavaScript files:
// first.js
export function House() {
this.width = 100;
this.length = 200;
}
// second.js
function paint() {
...
}
function clean() {
...
}
export { paint, clean }
To include them both in an HTML file:
<!-- index.html -->
<html>
<head>
<title>Webpage</title>
<script type="module">
import { House } from "./first.js";
import { paint, clean } from "./second.js";
let house = new House();
</script>
</head>
<body></body>
</html>
ES10 - dynamic import
// my-script.js
export const helloEvent = () => {
console.log('Hello World');
};
<!-- index.html -->
<html>
<head>
<title>Webpage</title>
<script type="text/javascript">
window.onload = function() {
document.getElementById('helloButton').addEventListener("click", async() => {
const module = await import('./myscript.js');
module.helloEvent();
});
}
</script>
</head>
<body></body>
</html>
Browser Console
Here are a couple of tricks you can use in your browser console.
Output to console
This is probably the most used debug technique:
console.log("test");
test
Output multiple values
let year = 2020;
let age = 99;
console.log(age, year);
99, 2020
For a message that will also include the variable names:
let year = 2020;
let age = 99;
console.log({age, year});
Object { age: 99, year: 2020 }
Output with formatting
Specifiers can be used to achieve string interpolation:
let year = 2020;
let age = 99;
console.log('It is %i and I am %i years old.', year, age);
It is 2020 and I am 99 years old.
Available Specifiers
Specifier | Output |
---|---|
%s | String |
%i or %d | Integer |
%f | Float |
%o | Optimal formating for collections |
%O | Expandable data |
%c | CSS style |
Output with style
Here is how to use the %c
specifier mentioned above:
console.log('%c Seeing red', 'color: red');
Seeing red.
Output an object
We can output objects directly via:
console.dir({a:1,b:2});
▾ Object { a: 1, b: 2 } a: 1 b: 2 ...
… but we can also show a JSON-ifyed version:
console.log(JSON.stringify({a:1,b:2}));
{"a":1,"b":2}
Output an object using table
console.table({a:1,b:2});
--------------------- | (index) | Value | --------------------- | a | 1 | | b | 2 | ---------------------
Output an array of objects using table
const redTeam = { name: 'Red', score: 14 };
const blueTeam = { name: 'Blue', score: 9 };
console.table([redTeam, blueTeam]);
------------------------------- | (index) | name | score | ------------------------------- | a | Red | 14 | | b | Blue | 9 | -------------------------------
Output a variable using template literals ES6
let width = 100;
console.log(`width is: ${width}`);
width is: 100
Log errors & warnings
console.error("Computer says no");
⛔️ ▾ Computer says no
console.warn("Computer says maybe");
⚠️ ▾ Computer says maybe
Grouping
To make it easier to read and organize, you can use console.group()
and console.groupEnd()
to group related data together:
console.group("Fruits");
console.log("Apple");
console.log("Banana");
console.log("Orange");
console.groupEnd();
▸ Fruits Apple Banana Orange
Groups can be nested:
console.group("Fruits");
console.log("Apple");
console.log("Banana");
console.group("Citrus");
console.log("Orange");
console.log("Lemon");
console.groupEnd();
console.groupEnd();
▸ Fruits Apple Banana ▸ Citrus Orange Lemon
Clear console
console.clear;
Execution time
Measure how long some code execution took:
console.time('id1');
...
console.timeEnd('id1');
default: 6202.5400390625ms
Node.js
Another of running JavaScript is via node.js.
Node.js Console
With node.js
installed, open a terminal and type node
. You will get a prompt allowing the input of JavaScript:
node
Welcome to Node.js v18.20.3.
Type ".help" for more information.
> ▊
Each JavaScript expression will be evaluated as is entered:
const theAnswer = 42
undefined
theAnswer
42
theAnswer = 43
Uncaught TypeError: Assignment to constant variable.
JS File
With a file named app.js
:
// app.js
console.log("Hello World");
node app.js
Hello World