JavaScript: Quick Start

Mirza Leka
9 min readOct 13, 2024

--

JavaScript is a high-level programming language primarily used to create interactive and dynamic content on the web. It is also used for backend servers, IoT, and on mobile devices. Here is a quick guide to JavaScript.

Photo by revac film’s&photography from Pexels. Edit my own

Origins

It was developed by Brendan Eich in 1995 as a scripting language. Its purpose was to add interactivity to web pages, such as form inputs, buttons, pop-ups, etc.

  • In 2009, when Ryan Dahl created the Node.js, the language hit another milestone with the rise of server-side JS applications.
  • The following year also significantly impacted the language with the release of NPM (Node.js Package Manager), which gave the power to publish and share custom JavaScript tools with anyone worldwide.
    This paved the way for new frameworks such as Angular.js, Backbone, and Express.js.
  • Then, in 2015, a new JavaScript version, ECMAScript6, introduced new and exciting language features that raised JS to modern standards.
  • In recent years, the JavaScript language has set new standards with Progressive-Web and Server-Side Rendered applications and new runtime environments like Deno & Bun.

If you’d like to learn more about the evolution of server-side JavaScript, be sure to check out my blog below 👇

What is JavaScript used for?

Dynamic Content Management

As mentioned, JavaScript is designed to bring interactivity to the web. What happens when you click on that button in the HTML or when you type on that form? Do you call an API, change something on the UI, display a pop-up notification, send a message, change styles, make animations, etc?

There are JavaScript web frameworks that are designed explicitly around managing UIs. The most popular choices are:

  • React.js
  • Angular
  • Vue.js
  • Svelte

JavaScript is also called the language of the internet since it’s been used in over 98.7% of websites worldwide.

Web Browser APIs

Since JavaScript lives in the browser, its primary purpose is to work with different Browser APIs, such as Browser History, Geolocation, Storage, Cookies, WebGL, Audio, Streams, Clipboard, etc.
If you’re making games that run in the browser, you use JavaScript.

Web Servers

JavaScript found its way onto the backend with Real-Time applications, Streams, Restful APIs, and Serverless computing. Big brands like Netflix, LinkedIn, and Paypal have microservices built in Node.js or use server-side rendering through backend JavaScript.

That means you can build full-stack apps using only JavaScript. The popular choices here are:

Server-Side Rendering frameworks:

  • Next.js, Remix (React.js)
  • Nuxt.js (Vue.js)
  • Angular SSR & Analog.js (Angular)
  • Svelte-kit (Svelte)

Fully backend frameworks:

  • Express.js
  • Nest.js
  • Fastify
  • Oak

Cross-Platform Apps

The JavaScript language has expanded to other areas, such as IOT, desktop and mobile apps, progressive web apps, machine learning, and even Linux-based Node.js OS.

“Any application that can be written in JavaScript will eventually be written in JavaScript”.

— Atwood’s Law

Syntax

JavaScript is a lightweight, interpreted, prototype-based, multi-paradigm scripting language that supports object-oriented, imperative, and functional programming styles.

This means you can write JavaScript apps purely using functions.

function sum(a, b) {
return a + b;
}

const result = sum(2, 3);

console.log('result :>> ', result); // 5

Or using Classes:

class Geek {

#name = 'Mirza' // private variable

constructor() {}

get getName() {
return this.#name;
}

set setName(newName) {
this.#name = newName;
}

}

const g = new Geek();

g.setName = 'Mirzly';
const newName = g.getName;

console.log('newName :>> ', newName); // Mirzly

And the two can coexist in the same file.

Data Types

JavaScript is a dynamically typed language that does not have strict types like C# or Java. That means you can create a variable in one type and assign it to a different type:

let geek = 'Mirza'; // string
geek = 47; // number
geek = ['Mirza'] // array

The most commonly used types:

  • Number (applicable for int16, int32, float, double)
  • String (applicable for char and string)
  • Boolean (applicable for booleans)
  • Object (applicable for class instances).

JavaScript also has built-in classes for specific uses:

  • Date — date manipulation
  • Math — mathematical operations
  • Console — printing values in the browser console/terminal
  • RegEx — creating Regular Expressions
  • Error — creating or catching exceptions (using try catch)
  • Promise — managing asynchronous operations

As well as advanced data structures like:

  • Set
  • Map
  • WeakMap

And more confusing ones:

  • null — a value with no concrete value
  • undefined — a value without a previously set value
  • NaN — Not a number value (Fun fact, type of NaN is number)

In JavaScript, arrays and Dates are also objects. You can check the type of any property using the typeof keyword.

typeof null // object

Variable declarations

There are two ways to declare variables in JavaScript.

  • let variables let you reassign values in your program:
let name;
name = 'Mirzly';

console.log(name);
  • const variables do not allow reassigning and must be declared with the value:
const pi = 3.14;
console.log(pi);

There is also the var keyword that preceded let and const, but it is recommended to avoid it

Equality

There are two types of equality in JavaScript.

  • Double equality (==) performs numerical value comparison of the two values after performing a type conversion:
1 == 1 // true
2 == '2' // true
1 == true // true
  • Triple equality (===) doesn’t perform any type conversion when comparing values. Triple equality compares values as well as their types:
1 === 1
2 === '2' // false
1 === 'true' // false

Logical Operators

JavaScript supports a wide range of logical operators that you’ll find in other languages:

  • ??, &&, ||, +=, &&=, ||=, ??=

Learn more about JavaScriot operators 👇

Conditions

JavaScript features everyday conditions:

  • if, else, else if
  • switch case
  • ternary operator

Loops

JavaScript language also features a wide array of loops:

  • for, forEach, for of, for in, while, do while.

String methods

JavaScript lets you easily manipulate strings:

const username = 'John Wick';

const upper = username.toUpperCase();
// 'JOHN WICK'

const lower = username.toLowerCase();
// 'john wick'

const characters = username.split('');
// [ 'J', 'o', 'h', 'n', ' ', 'W', 'i', 'c', 'k' ]

const numberOfCharacters = username.length;
// 9

const firstCharacter = username.at(0);
// 'J'

const lastCharacter = username.at(username.length - 1);
// 'k'

const firstWord = username.split(' ')[0];
// 'J'

const partialWords = username.substring(0, 6);
// ' John W'

Array methods

It also features a long list of array utility methods that help you easily manipulate data. This includes:

  • Projection, filtering, sorting, aggregation, quantifiers, etc.
const users = [
{
age: 30,
name: 'Mirza',
hobby: 'JS'
},
{
age: 31,
name: 'Armin',
hobby: 'SQL'
},
{
age: 17,
name: 'Faruk',
hobby: 'CSS'
},
]

// data manipulation
const names = users
.filter(user => user.age > 18)
.map(p => p.name)
.sort()

console.log('names :>> ', names); // [ 'Armin', 'Mirza' ]

Object methods

You can easily read the properties and values of an object:

const user = {
age: 100,
hobby: 'butcher',
name: 'Sead'
}

const keys = Object.keys(user);
const values = Object.values(user);
const entries = Object.entries(user);

// keys :>> [ 'age', 'hobby', 'name' ]
// values :>> [ 100, 'butcher', 'Sead' ]
// entries :>> [ [ 'age', 100 ], [ 'hobby', 'butcher' ], [ 'name', 'Sead' ] ]

Modules

In Javascript, the module is just another JavaScript file, that exports items that can be imported into other JS files.

Here is a quick example:

I created a math.js file that does some math calculations.

// math.js (module)
function sum (a, b) {
return a+b;
}

// export a function sum so that is available out of this file
export sum;

I can import this file to other files whenever I need to do some calculations in my app:

// app.js

// import a function sum by providing file path
import { sum } = from './math';

// using a function from math.js
console.log('Sum is: ', sum(2, 3)); // 5

The modules can share data, and you can have as many modules in your application as you desire.

More on JS modules 👇

Asynchronous JavaScript

JavaScript is a synchronous, single-threaded language by default, meaning it executes code line by line. However, adding Async ingredients into the mix behaves quite differently. Let’s see an example of that:

console.log('Frodo')

setTimeout(() => console.log('Sam'), 1000)

setTimeout(() => console.log('Pippin'), 0)

console.log('Merry')

These timeouts create delays. Looking at the snippet above, you may think that execution will go like this:

  • Print “Frodo”
  • Wait for 1000ms (1 second) and print “Sam”
  • Print “Pippin” and finally
  • Print “Merry”

But what will happen is this:

[LOG]: "Frodo"
[LOG]: "Merry"
[LOG]: "Pippin"
[LOG]: "Sam" // after waited for whole second

JavaScript has a set of built-in APIs that don’t execute on the main thread (single thread) and thus do not block the execution. Instead, they run in the background process. These include:

  • Network calls (REST API)
  • Timeouts
  • Events
  • Various browser APIs
  • Streams
  • I/O operations (reading/writing into files/databases), etc.

When working with JavaScript, one should leverage the async capabilities as much as possible.

Example of HTTP Request in JavaScript using Fetch API:

fetch("https://jsonplaceholder.typicode.com/todos/1")
.then((res) => {
console.log('res.status :>> ', res.status); // 200
// Process response as JSON
return res.json();
})
.then((jsonData) => {
console.log('jsonData :>> ', jsonData); // {...}
})
.catch(function (err) {
console.log("Unable to fetch: ", err);
});

More on Async JS 👇

JSON

JavaScript Object Notation (JSON) is a lightweight data-interchange format (usually between servers or between the server and the client). It is easy for humans to read and write.

Sample JSON (from JSONplaceholder).

[
{
"userId": 1,
"id": 1,
"title": "delectus aut autem",
"completed": false
},
{
"userId": 1,
"id": 2,
"title": "quis ut nam facilis et officia qui",
"completed": false
},
{
"userId": 1,
"id": 3,
"title": "fugiat veniam minus",
"completed": false
}
]

The JSON is based on a subset of the JavaScript Programming Language.
JavaScript lets you parse and serialize the JSON:

  • JSON to concrete class (JSON.parse(data))
  • Concrete class to JSON (JSON.stringify(data))

JavaScript on the Backend

JavaScript is a scripting language designed to run in the browser and make use of:

  • Browser APIs
  • DOM structure
  • Client Events (clicks, hover, and user input)

However, on the server, it is an entirely different story. Here you can:

  • Host Web servers
  • Perform DNS Lookups
  • Create and Listen to Server events
  • Read and Write files
  • Interact with the database
  • Create streams
  • Execute CLI scripts
  • Inspect Operating System

Three popular JavaScript runtimes are used to build server-side JS applications:

  • Node.js
  • Deno
  • Bun

If you’re serious about learning server-side JS, this is the place to start 👇

Node.js Starter

8 stories

NPM

Node Package Manager (NPM) is the largest repository of third-party packages. The NPM lets you add any third-party utilities, libraries and frameworks to your JavaScript project simply by running the install command:

  • Using npm:
> npm i react
  • Using yarn:
> yarn add react

Then, use the package by importing it to your project:

import react from 'react'

// ...

TypeScript

TypeScript is a superset of JavaScript. It’s an entirely new language created by Microsoft that adds strict types to JavaScript, such as:

  • Interfaces, enums, custom types, tuples, etc.

Once the variable is declared as a specific type, it cannot be reassigned to a different one:

let geek: string = 'Mirza';
geek = 47; // Error

It’s also very popular nowadays as it helps you spot errors quicker. It comes out of the box in frameworks like Angular and runtimes like Deno and Bun.

Get started with JavaScript

So far, we have learned that JavaScript powers websites. This means it can be added to any website using the HTML script tag or executed in the browser's dev tools console (the latter should be avoided).

Here is a basic website that has a clickable HTML button element. What happens when you click that element in between the script tags:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" type="text/css" href="./styles.css" />
<title>Document</title>
</head>
<body>
<button id="submit">Submit</button>
</body>


<!-- JavaScript 👇 -->
<script>
const submitBtn = document.getElementById('submit');

submitBtn.addEventListener('click', (event) => {
console.log('Clicked!');
});
</script>
</html>

If you’re a passionate reader, I wrote several blogs on JavaScript that will help you get started and sharpen your skills:

JavaScript Starter

6 stories

Also, be sure to explore the JS Ecosystem 👇

Bye for now 👋

--

--

Mirza Leka

Web Developer. DevOps Enthusiast. I share my experience with the rest of the world. Follow me on https://twitter.com/mirzaleka for news & updates #FreePalestine