ResourcesJavascriptGuides

Guide to declarations in Javascript

Introduction

This guide covers various ways of declaration in Javascript, from basic variable declarations to more advanced topics like declaring classes and modules. We included Typescript declarations too.

Also, take in mind declaration is not the same thing as assignment.


Declarations

Variable declarations

  • var declaration
var x = 5;
  • let, const declaration
let y = 10;
const z = 15;

There is the difference about scope and what you can do with variables declared with var, let, const.

If you want to get in-depth knowledge about the differences here is the article: Difference between var, let and const

Array Declaration

let arr = [1, 2, 3];

Function Declaration

Default function declaration:

function greet() {
  return "Hello, world!";
}

Arrow function declaration:

const greet = () => "Hello, world!";

I personally love arrow functions and use them all the time!

Class Declaration

class Person {
  constructor(name) {
    this.name = name;
  }
 
  greet() {
    return `Hello, my name is ${this.name}`;
  }
}

Advanced Declarations

Async functions (normal)

async function fetchData() {
  let response = await fetch('https://api.example.com/data');
  let data = await response.json();
  return data;
}

Async functions (arrow)

const fetchData = async () => {
  let response = await fetch('https://api.example.com/data');
  let data = await response.json();
  return data;
}

Global variable declaration

window.globalVar = "I'm global";

Module declaration

window.globalVar = "I'm global";

Declarations in Typescript

Variables

let isDone: boolean = false;
let decimal: number = 6;
let color: string = "blue";

Global Types

declare global {
  interface Window {
    myCustomProperty: string;
  }
}

Resources

MDN Web docs

On this page