Learning JavaScript
JavaScript Fundamentals
Welcome to the JavaScript fundamentals section! This comprehensive guide will take you from basic concepts to advanced topics.
What You’ll Learn
This section covers core JavaScript concepts that work in any environment (browser, Node.js, or other runtimes):
- Basics: Variables, operators, data types
- Data Structures: Arrays, objects, Map, Set
- Functions: Regular functions, arrow functions, closures
- Modern JavaScript: Classes, modules, spread/rest operators, destructuring
- Async Programming: Callbacks, promises, async/await
- Error Handling: Try/catch, throwing errors
- Advanced Topics: Generators, regular expressions, functional programming
Learning Path
Start with lesson 01 and progress sequentially. Each lesson builds on previous concepts.
Prerequisites: Basic understanding of programming concepts is helpful but not required.
There is a lot to learn in modern javaScript Development but that shouldn’t scare you because also there are great things you can do with knowing only a little bit of it and then while you are using it you continue to learn as you go. The modern javaScript eco-system is really great and mature now and allows you to get down to doing Development without worrying a whole lot about whether all browsers support it.
What is the difference between NodeJS and regular frontend javaScript? what I will be covering in this article Which should you choose to focus on and why? Which am i going to focus on and why? What is NodeJS and how does it differ from regular javaScript? Regular javaScript or javaScript that people normally refer to when they speak of it is javaScript that runs in the client’s web browser. We write some code and include it inside the html of the document (inside script tags) or we use script tags (normally) to download a separate javaScript file that will start executing as soon as its finished downloading.
What do you need to get started with javaScript and follow along with my articles? A computer, this doesn’t have to be anything fast, super modern or specific. Just about anything that can run a modern web browser will do.
A text editor of some sort.
List of many editors many I have used An excellent popular code editor of vscode a new quick addition is to try the new vscode online editor at https://vscode.
Conditionals allow your code to make decisions and execute different code based on different conditions. They’re fundamental to creating programs that respond to user input, validate data, and control program flow.
What are Conditionals? Conditionals check whether a condition is true or false, then execute code accordingly:
const age = 18; if (age >= 18) { console.log('You can vote!'); } // Output: You can vote! Think of conditionals like choosing a path:
Comparison operators let you compare values and return true or false. They’re essential for making decisions in your code with conditionals and loops.
What are Comparison Operators? Operators that compare two values and return a boolean (true or false):
5 > 3 // true 10 === 10 // true 'hello' !== 'world' // true These results are used in if statements, while loops, and anywhere you need to check conditions.
Logical operators allow you to combine multiple conditions and create more complex decision-making logic. They’re essential for writing realistic programs that check multiple criteria.
What are Logical Operators? Operators that work with boolean values (true and false) to produce a new boolean result:
const age = 25; const hasLicense = true; // Can drive if both conditions are true if (age >= 18 && hasLicense) { console.log('You can drive'); } There are three main logical operators:
Loops allow you to repeat code multiple times without writing the same code over and over. They’re fundamental for processing lists, repeating tasks, and building efficient programs.
What are Loops? A loop executes a block of code repeatedly until a condition is met:
// Without loop (repetitive) console.log(1); console.log(2); console.log(3); console.log(4); console.log(5); // With loop (efficient) for (let i = 1; i <= 5; i++) { console.log(i); } // Output: 1 2 3 4 5 JavaScript has several types of loops:
Variables are containers for storing data values. Understanding how to declare and use variables correctly is fundamental to writing good JavaScript code.
What are Variables? Variables let you store and reuse values throughout your program:
let message = 'Hello, World!'; console.log(message); // Hello, World! message = 'Welcome!'; console.log(message); // Welcome! Think of variables as labeled boxes where you can:
Store a value Read the value later Update the value (for some variable types) Three Ways to Declare Variables JavaScript has three keywords for declaring variables:
Template literals (also called template strings) provide an easy way to create strings that include variables and expressions. They’re cleaner and more readable than traditional string concatenation.
What are Template Literals? Template literals use backticks ` instead of quotes and allow embedded expressions with ${}:
// Old way - concatenation const name = 'Alice'; const greeting = 'Hello, ' + name + '!'; console.log(greeting); // Hello, Alice! // Modern way - template literal const name = 'Alice'; const greeting = `Hello, ${name}!
Numerical operators perform mathematical calculations on numbers. Understanding these operators and how they work together is essential for any programming task involving math.
Arithmetic Operators JavaScript provides standard arithmetic operators for mathematical operations:
Operator Name Example Result + Addition 5 + 3 8 - Subtraction 5 - 3 2 * Multiplication 5 * 3 15 / Division 15 / 3 5 % Modulus (remainder) 10 % 3 1 ** Exponentiation 2 ** 3 8 Addition (+) const a = 10; const b = 5; const sum = a + b; console.
String operators allow you to combine, compare, and manipulate text. While there’s only one string operator (+), understanding how strings work with operators is crucial.
String Concatenation (+) The + operator joins (concatenates) strings together:
const firstName = 'Alice'; const lastName = 'Smith'; const fullName = firstName + ' ' + lastName; console.log(fullName); // Alice Smith Basic Concatenation const greeting = 'Hello' + ' ' + 'World'; console.log(greeting); // Hello World const message = 'I am ' + '25' + ' years old'; console.
JavaScript has a single number type (all numbers are 64-bit floating point). The Math object provides mathematical functions and constants for advanced calculations.
Number Type Basics All numbers in JavaScript are floating point (decimals):
const integer = 42; const decimal = 3.14159; const negative = -10; const scientific = 2.5e6; // 2.5 × 10^6 = 2,500,000 console.log(typeof 42); // "number" console.log(typeof 3.14); // "number" console.log(typeof -10); // "number" Special Number Values // Infinity console.
Type coercion is JavaScript’s automatic conversion of values from one type to another. Understanding coercion helps you avoid bugs and write predictable code.
What is Type Coercion? Implicit coercion = JavaScript converts types automatically
Explicit coercion = You manually convert types
// Implicit - JavaScript converts automatically console.log('5' - 3); // 2 (string '5' → number 5) console.log('5' + 3); // '53' (number 3 → string '3') // Explicit - you convert manually console.
The following string methods do not mutate the existing string. str.endsWith(searchString) – returns (boolean), determines if a string ends with a searchString.
str.startsWith(searchString) – returns (boolean), determines if a string starts with a searchString.
str.includes(searchString) – returns (boolean), returns true if string includes searchString anywhere within it.
str.indexOf(searchString) – returns the first occurrence of the searchString or -1 if none found.
str.lastIndexOf – returns the last occurrence of the searchString or -1 if none found.
Arrays are an integral part of JavaScript that I use everyday and might be one of the most important things in the language. Since at the core of most data crunching or coding is the idea of repetition over a series of some sort and with javaScript you will find arrays to be your best friend.
An array is an unordered collection of stuff, that stuff can be strings, numerals, or objects.
The array methods that I find most useful are methods that do not mutate the array, meaning that instead of changing the array I pass to it return a subset or changed array as a new array. A full list of array methods can be found on the Mozzila JavaScript reference site.
find( function ) – returns the first element in an array that passes the test. If no results then undefined is returned.
Objects are also an integral part of JavaScript that you will probably find yourself using everyday. They are very useful for storing keyed pices of data or organizing data in a more structured way then an array would allow by itself.
An object is a collection of keyed data and that data can include arrays or other objects as well. In JavaScript it is designated by the use of curly brackets ( { } ).
Following is a list of the object methods that I find most useful daily. For a complete list you can go to the Mozzila JavaScript documentation for objects.
Object.assign(target, ...sources ) – target is a target object and sources are source objects. Mainly used to shallow clone an object. (easiest way to deep clone is by using JSON.parse with JSON.stringify).
example
let obj = { somekey: 100 }; let cloneOfObject = Object.
iterating over Object with for in loop let myObj = { "one" : 1, "two" : 2, "three" : 3 }; let newArray = []; for (let int in myObj){ newArray.push( int * 5); } // newArray now contains: [5, 10, 15] iterating over Objects with array methods let myObj = { "one" : 1, "two" : 2, "three" : 3 }; let newArray = Object.keys(myObj).map( key => 5 * myObj[key] ); // newArray: [5, 10, 15]; cloning an object (shallow clone) const clone = {.
Functions in JavaScript Functions are one of the fundamental building blocks in JavaScript. A function is a reusable block of code that performs a specific task. You define it once and can call it multiple times throughout your program.
Why Use Functions? Reusability: Write code once, use it many times Organization: Break complex problems into smaller, manageable pieces Maintainability: Update code in one place rather than many Abstraction: Hide complex logic behind simple function names Function Declaration The most common way to create a function is with a function declaration:
Arrow Functions (ES6) Arrow functions are a shorter syntax for writing functions introduced in ES6 (ECMAScript 2015). They’ve become extremely popular in modern JavaScript development, especially in React and other frameworks.
Basic Syntax Traditional function:
function add(a, b) { return a + b; } Arrow function:
const add = (a, b) => { return a + b; }; Even shorter (implicit return):
const add = (a, b) => a + b; Syntax Variations Multiple parameters:
Closures Closures are one of JavaScript’s most powerful features, yet they can be tricky to understand at first. A closure gives you access to an outer function’s scope from an inner function, even after the outer function has finished executing.
The Simple Explanation A closure is created when:
A function is defined inside another function The inner function uses variables from the outer function The inner function is returned or passed elsewhere The inner function “closes over” (remembers) the outer function’s variables.
Spread and Rest Operators (…) The three dots ... operator in JavaScript serves two purposes: spread and rest. Despite looking identical, they do opposite things depending on where they’re used.
The Spread Operator The spread operator expands an array or object into individual elements.
Spreading Arrays Copying arrays:
const original = [1, 2, 3]; const copy = [...original]; copy.push(4); console.log(original); // [1, 2, 3] - unchanged console.log(copy); // [1, 2, 3, 4] Combining arrays:
Destructuring Destructuring is a convenient way to extract values from arrays or properties from objects into distinct variables. It makes your code cleaner and more readable.
Array Destructuring Basic syntax:
const numbers = [1, 2, 3]; // Old way const first = numbers[0]; const second = numbers[1]; // Destructuring const [first, second, third] = numbers; console.log(first); // 1 console.log(second); // 2 console.log(third); // 3 Skipping elements:
const colors = ["red", "green", "blue", "yellow"]; const [primary, , tertiary] = colors; // Skip green console.
This keyword Oh, this! It’s one of the trickiest concepts for beginners, but absolutely vital. The value of this inside a function depends on how the function is called, not where it’s defined (unless it’s an arrow function!).
Global Context: this refers to the global object (window in browsers, undefined in strict mode modules).
Method Call: this refers to the object the method is called on.
Constructor Call: this refers to the new instance being created.
Class Let’s talk about something that’s been making waves in the JavaScript ocean for a while now: Classes. They’re not just a fancy new keyword; they’re a paradigm shift that brings a whole lot of power and organization to your code.
JavaScript Classes: More Than Just Syntactic Sugar For a long time, JavaScript developers used constructor functions and prototypes to achieve object-oriented patterns. And while that worked, let’s be honest, it wasn’t always the prettiest or most intuitive way to express object relationships.
A module is just a javascript file really, one that can be called by anouther javascript program.
Modules can load each other and use special directives export and import to interchange functionality, call functions of one module from another one.
export keyword labels variables and functions that should be accessible from outside the current module. import allows the import of functionality from other modules. For instance, if we have a file sayHello.
Error Handling in JavaScript Errors are inevitable in programming. Good error handling makes your applications more robust, user-friendly, and easier to debug.
The Basics: try…catch The try...catch statement lets you handle errors gracefully:
try { // Code that might throw an error const result = riskyOperation(); console.log(result); } catch (error) { // Code to handle the error console.log("Something went wrong:", error.message); } Without try…catch:
JSON.parse("invalid json"); // Uncaught SyntaxError - app crashes!
Regular Expressions are a concise method of describing text patterns. In JavaScript a Regular Expression are also special objects that can be used with some methods to help find or transform text.
Defining a Regular Expression:`` let r = /ab+c/ constructing with slashes. let r = new RegExp('ab+c') constructing with the constructor function ‘RegExp’. Special Characters Regular Expression use a bunch of special characters to express pattern matches.
Character meaning example ^ Matches beginning of input $ Matches end of input * Matches preceding expression 0 or more times + Matches preceding expression 1 or more times ?
Regular Expression Methods exec (regex method) - executes a search for a match in a string, returning an array or null if not found.
test (regex method) - search for a match and return boolen of true or false.
match (string method) - search for a match in the string and returns array or null if not found.
search (string method) - tests for a match in a string and returns the index of the match or -1 if not found.
While always has been good to know how to deal with asynchronous code it is becoming more and more important as programs become more complex. Without asynchronous code our program would only be able to do one thing at a time and would have to wait for the previous instruction to finish before moving on. This works surprisingly well in a lot of instances but whenever we have something that will take awhile to run or return to us is when we should certainly look into using asynchronously.
example of simple callback useage function cbFunc() { console.log("this is the callback function that is run after 'cbExample' is done with its main code block); } function cbExample(something, cb) { let somethingElse = something + 2 cb(); } cbExample(5, cbFunc); example with anomalous arrow funcs function cbExample(something, cb) { let somethingElse = something + 2 cb(); } cbExample(5, () => { console.log("this is the callback); }); callbacks and async useage many filesystem utilities in nodeJS take a callback as an option, that function you give it in the callback is then executed after the filesystem utility completes its function.
Promises are always kept, as they should be. They are guaranteed to return at some time. Many utilites will return a promise now, enabling you to then use that returned promise to watch for when it resolves. I always look for this feature when choosing 3rd party libraries, like axios (for http client)
Promises were introduced with ES6 before that a library like bluebird was needed to take advantage of them.
Okay you have delt with callbacks, and seen how messy and complex that can get quickly, you have dealt with promises and the power they bring to the table and maybe also experienced some frustration with how once you start with something in a promise it sometimes seems like everything is promises after that. async and the await function might be just what you were waiting for. Its definitely not a catch all or replacement for plain promises but it can help clean up code a lot sometimes.
Define a generator: function* nameGenfunc() { //generator function code yield 1 } use a generator instance has to be created before use const genObj = nameGenfunc()
statements yield next – nameGenfunc.next() – runs until it encounters a yield statment returning that yield value return — exits out of generator Next Article: The Map data structure
Map data structures what I will be covering in this article What is the map data structure. How to use the map data structure. When to use the map data structure. What is the map data structure Map allows keys of any type unlike an Object which is very like a Map.
Methods and properties are: new Map() – creates a new map. map.set(key, value) – sets the value by the key returns the set.
set data structures what I will be covering in this article What is the set data structure. How to use the set data structure. When to use the set data structure. What is the set data structure A Set is a special type collection – “set of values” (without keys), where each value may occur only once.
Methods new Set(iterable) – creates the set, and if an iterable object is provided (usually an array), copies values from it into the set.
Set, Map, Arrays, Objects what I will be covering in this article What is the difference. When to use what. What is the difference What to use when Next Article: This Keyword
Functional Programming in JavaScript Functional programming (FP) is a programming paradigm that treats computation as the evaluation of mathematical functions. While JavaScript is multi-paradigm, it has excellent support for functional programming concepts that lead to more predictable, testable, and maintainable code.
Core Principles The three pillars of functional programming:
Pure Functions - Functions with no side effects Immutability - Data that never changes Function Composition - Building complex functions from simple ones Pure Functions A pure function always returns the same output for the same input and has no side effects.