JavaScript Crash Course 2023 with new features up to es12
This Javascript crash course 2023 covers a wide range of topics essential for learning JavaScript, including data types, functions, object-oriented programming, and the Document Object Model (DOM). With new features for es8 to 12, this course provides a solid foundation for anyone looking to become proficient in JavaScript and build dynamic web applications.
Here it is my first JavaScript Crash Course of 2023. This article was written by me and my AI-powered assistant. If you find any issue with the code blocks please join my Slack community and let me know.
JavaScript Crash Course | Introduction
JavaScript is a high-level, interpreted programming language that is used to create interactive and dynamic web pages. It is a client-side scripting language, which means that it runs on the user’s web browser rather than on the web server. JavaScript is used to add interactivity to web pages, such as form validation, animations, and dynamic content updates.
There are several reasons why learning JavaScript is important:
- It is a fundamental language for web development: JavaScript is an essential language for web development. It is used to create interactive and dynamic web pages, and it is a key component of modern web development.
- It is widely used: JavaScript is one of the most widely used programming languages in the world. It is used by developers to create web applications, mobile applications, and desktop applications.
- It is easy to learn: JavaScript is a relatively easy language to learn, especially for those who are already familiar with HTML and CSS. It has a simple syntax and is forgiving of errors, making it a great language for beginners.
- It has a large community: JavaScript has a large and active community of developers who contribute to open source projects, create libraries and frameworks, and provide support and resources for other developers.
- It is constantly evolving: JavaScript is constantly evolving, with new features and updates being added regularly. This means that there is always something new to learn and explore in the world of JavaScript.
Table of contents for your JavaScript for beginners crash course:
Table of contents the JavaScript crash course:
- Introduction
- What is JavaScript?
- Why learn JavaScript?
- First Steps
- Setting up your development environment
- Writing your first JavaScript program
- Data Types and Primitives
- Variables and constants
- Data types (strings, numbers, booleans)
- Operators
- Functions
- Defining and calling functions
- Parameters and arguments
- Return values
- Object-Oriented Programming
- Objects and classes
- Properties and methods
- Inheritance and polymorphism
- DOM Manipulation
- Introduction to the DOM
- Selecting and manipulating elements
- Event handling
- what’s new (es7 to 12)
JavaScript Crash Course 2023 | First Steps
Setting up your development environment
- Install a text editor such as Visual Studio Code, Sublime Text, or Atom.
- Install Node.js, which includes the npm package manager.
- Create a new folder for your project.
- Open your text editor and open the project folder.
Writing your first JavaScript program
- Create a new file in your project folder and name it
index.js
. - Open the file in your text editor.
- Type the following code into the file:
console.log("Hello, world!");
- Save the file.
- Open your terminal or command prompt and navigate to your project folder.
- Run the following command to execute your JavaScript program:
node index.js
- You should see the following output in your terminal:
Hello, world!
Congratulations, you have written and executed your first JavaScript program.
Variables and Constants
In JavaScript, variables are used to store data values. You can declare a variable using the var
, let
, or const
keyword.
var x = 5; // variable declaration using var
let y = "Hello"; // variable declaration using let
const z = true; // variable declaration using const
The var
keyword is used to declare a variable that can be reassigned. The let
keyword is used to declare a variable that can be reassigned, but only within its block scope. The const
keyword is used to declare a variable that cannot be reassigned.
JavaScript Crash Course | Data Types
JavaScript has several data types, including strings, numbers, booleans, null, and undefined.
Strings
Strings are used to represent text and are enclosed in single or double quotes.
let name = "John";
let message = 'Hello, world!';
Numbers
Numbers are used to represent numeric values.
let age = 25;
let price = 9.99;
Booleans
Booleans are used to represent true/false values.
let isStudent = true;
let isWorking = false;
Null and Undefined
null
and undefined
are used to represent the absence of a value.
let x = null;
let y = undefined;
Operators
Operators are used to perform operations on variables and values.
Arithmetic Operators
Arithmetic operators are used to perform mathematical operations.
let x = 5;
let y = 2;
console.log(x + y); // addition
console.log(x - y); // subtraction
console.log(x * y); // multiplication
console.log(x / y); // division
console.log(x % y); // modulus
console.log(x ** y); // exponentiation
Comparison Operators
Comparison operators are used to compare values.
let x = 5;
let y = 2;
console.log(x > y); // greater than
console.log(x < y); // less than
console.log(x >= y); // greater than or equal to
console.log(x <= y); // less than or equal to
console.log(x == y); // equal to
console.log(x != y); // not equal to
Logical Operators
Logical operators are used to combine and manipulate boolean values.
let x = true;
let y = false;
console.log(x && y); // logical AND
console.log(x || y); // logical OR
console.log(!x); // logical NOT
JavaScript Crash Course | Control Flow tools
Conditional Statements and Switch Case
Conditional statements are used to execute different actions based on different conditions. In JavaScript, we have two types of conditional statements: if...else
and switch
.
if…else
The if...else
statement is used to execute a block of code if a condition is true, and another block of code if the condition is false.
if (condition) {
// code to be executed if condition is true
} else {
// code to be executed if condition is false
}
switch
The switch
statement is used to perform different actions based on different conditions.
switch (expression) {
case value1:
// code to be executed if expression matches value1
break;
case value2:
// code to be executed if expression matches value2
break;
default:
// code to be executed if expression doesn't match any of the cases
}
Arrays, Sets, and Object Literals
Arrays, sets, and object literals are used to store and manipulate data in JavaScript.
Arrays
An array is a collection of elements, which can be of any data type. In JavaScript, arrays are created using square brackets []
.
const fruits = ['apple', 'banana', 'orange'];
Sets
A set is a collection of unique elements, which can be of any data type. In JavaScript, sets are created using the Set()
constructor.
const numbers = new Set([1, 2, 3, 4, 5]);
Object Literals
An object literal is a collection of key-value pairs, where the keys are strings and the values can be of any data type. In JavaScript, object literals are created using curly braces {}
.
const person = {
name: 'John',
age: 30,
address: {
street: '123 Main St',
city: 'New York',
state: 'NY'
}
};
JavaScript Crash Course | Loops
Loops are used to execute a block of code repeatedly.
for
The for
loop is used to execute a block of code a specified number of times.
for (let i = 0; i < 10; i++) {
// code to be executed
}
forEach
The forEach
method is used to execute a function for each element in an array.
const fruits = ['apple', 'banana', 'orange'];
fruits.forEach(function(fruit) {
// code to be executed for each fruit
});
for…of
The for...of
loop is used to iterate over the values of an iterable object, such as an array.
const fruits = ['apple', 'banana', 'orange'];
for (const fruit of fruits) {
// code to be executed for each fruit
}
for…in
The for...in
loop is used to iterate over the properties of an object.
const person = {
name: 'John',
age: 30,
address: {
street: '123 Main St',
city: 'New York',
state: 'NY'
}
};
for (const property in person) {
// code to be executed for each property
}
while
The while
loop is used to execute a block of code while a condition is true.
while (condition) {
// code to be executed while condition is true
}
Conditional Statements and Switch Case
Conditional statements are used to execute different actions based on different conditions. In JavaScript, we have two types of conditional statements: if...else
and switch
.
if…else
The if...else
statement is used to execute a block of code if a condition is true, and another block of code if the condition is false.
if (condition) {
// code to be executed if condition is true
} else {
// code to be executed if condition is false
}
switch
The switch
statement is used to perform different actions based on different conditions.
switch (expression) {
case value1:
// code to be executed if expression matches value1
break;
case value2:
// code to be executed if expression matches value2
break;
default:
// code to be executed if expression doesn't match any of the cases
}
Arrays, Sets, and Object Literals
Arrays, sets, and object literals are used to store and manipulate data in JavaScript.
Arrays
An array is a collection of elements, which can be of any data type. In JavaScript, arrays are created using square brackets []
.
const fruits = ['apple', 'banana', 'orange'];
Sets
A set is a collection of unique elements, which can be of any data type. In JavaScript, sets are created using the Set()
constructor.
const numbers = new Set([1, 2, 3, 4, 5]);
Object Literals
An object literal is a collection of key-value pairs, where the keys are strings and the values can be of any data type. In JavaScript, object literals are created using curly braces {}
.
const person = {
name: 'John',
age: 30,
address: {
street: '123 Main St',
city: 'New York',
state: 'NY'
}
};
Loops
Loops are used to execute a block of code repeatedly.
for
The for
loop is used to execute a block of code a specified number of times.
for (let i = 0; i < 10; i++) {
// code to be executed
}
forEach
The forEach
method is used to execute a function for each element in an array.
const fruits = ['apple', 'banana', 'orange'];
fruits.forEach(function(fruit) {
// code to be executed for each fruit
});
for…of
The for...of
loop is used to iterate over the values of an iterable object, such as an array.
const fruits = ['apple', 'banana', 'orange'];
for (const fruit of fruits) {
// code to be executed for each fruit
}
for…in
The for...in
loop is used to iterate over the properties of an object.
const person = {
name: 'John',
age: 30,
address: {
street: '123 Main St',
city: 'New York',
state: 'NY'
}
};
for (const property in person) {
// code to be executed for each property
}
while
The while
loop is used to execute a block of code while a condition is true.
while (condition) { // code to be executed while condition is true}
Object-Oriented Programming (OOP) is a programming paradigm that is based on the concept of objects. Objects are instances of classes, which are templates for creating objects. JavaScript is a prototype-based language, which means that it does not have classes in the traditional sense. However, with the introduction of ES6, JavaScript now has classes and supports OOP concepts such as inheritance and polymorphism.
Objects and Classes: In ES6, classes are introduced as a new syntax for creating objects. A class is a blueprint for creating objects with specific properties and methods. To create a class, we use the class
keyword followed by the name of the class. Here is an example:
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
sayHello() {
console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
}
}
let person1 = new Person("John", 30);
person1.sayHello(); // Output: Hello, my name is John and I am 30 years old.
In the example above, we created a Person
class with a constructor that takes in a name
and an age
. We also defined a sayHello
method that logs a message to the console. We then created an instance of the Person
class and called the sayHello
method on it.
Properties and Methods: Properties are variables that are associated with an object, while methods are functions that are associated with an object. In ES6, we can define properties and methods inside a class using the constructor
and class
keywords respectively. Here is an example:
class Rectangle {
constructor(height, width) {
this.height = height;
this.width = width;
}
get area() {
return this.calcArea();
}
calcArea() {
return this.height * this.width;
}
}
let rectangle1 = new Rectangle(10, 20);
console.log(rectangle1.area); // Output: 200
In the example above, we created a Rectangle
class with a constructor that takes in a height
and a width
. We also defined a calcArea
method that calculates the area of the rectangle and a get
accessor that returns the area of the rectangle. We then created an instance of the Rectangle
class and called the area
property on it.
Inheritance and Polymorphism: Inheritance is the process of creating a new class from an existing class. The new class inherits all the properties and methods of the existing class and can also have its own properties and methods. In ES6, we can use the extends
keyword to create a subclass that inherits from a superclass. Here is an example:
class Animal {
constructor(name) {
this.name = name;
}
speak() {
console.log(`${this.name} makes a noise.`);
}
}
class Dog extends Animal {
speak() {
console.log(`${this.name} barks.`);
}
}
let dog1 = new Dog("Rex");
dog1.speak(); // Output: Rex barks.
In the example above, we created an Animal
class with a constructor that takes in a name
and a speak
method that logs a message to the console. We then created a Dog
class that extends the Animal
class and overrides the speak
method to log a different message to the console. We then created an instance of the Dog
class and called the speak
method on it.
Polymorphism is the ability of an object to take on many forms. In JavaScript, polymorphism is achieved through inheritance. In the example above, the Dog
class is a subclass of the Animal
class and can be used wherever an Animal
object is expected. This is because the Dog
class inherits all the properties and methods of the Animal
class.
DOM Manipulation in JavaScript ES6 and beyond
Introduction to the DOM
The Document Object Model (DOM) is a programming interface for web documents. It represents the page so that programs can change the document structure, style, and content. The DOM represents the document as nodes and objects. That way, programming languages can interact with the page.
Selecting and manipulating elements
To select an element in the DOM, you can use the querySelector
method. This method returns the first element that matches a specified CSS selector.
const element = document.querySelector('#myElement');
Once you have selected an element, you can manipulate its properties using JavaScript. For example, you can change the text content of an element using the textContent
property.
element.textContent = 'New text content';
You can also change the HTML content of an element using the innerHTML
property.
element.innerHTML = '<h1>New heading</h1>';
To add a new element to the DOM, you can use the createElement
method to create a new element, and the appendChild
method to add it to an existing element.
const newElement = document.createElement('div');
newElement.textContent = 'New element';
element.appendChild(newElement);
Event handling
Event handling is the process of responding to user actions, such as clicks and key presses. To handle events in JavaScript, you can use the addEventListener
method to attach an event listener to an element.
element.addEventListener('click', () => {
console.log('Element clicked');
});
You can also pass a function as the event listener, which will be called when the event occurs.
function handleClick() {
console.log('Element clicked');
}
element.addEventListener('click', handleClick);
In ES6 and beyond, you can use arrow functions to create concise event listeners.
element.addEventListener('click', () => console.log('Element clicked'));
You can also use event delegation to handle events on multiple elements. Event delegation is the process of attaching a single event listener to a parent element, and then using the event.target
property to determine which child element was clicked.
parentElement.addEventListener('click', event => {
if (event.target.matches('.childElement')) {
console.log('Child element clicked');
}
});
In this example, the event listener is attached to the parentElement
, and then checks if the clicked element matches the .childElement
selector. If it does, the event is handled.
Conclusion
DOM manipulation and event handling are essential skills for web developers. With JavaScript, you can select and manipulate elements in the DOM, and respond to user actions with event listeners. By mastering these skills, you can create dynamic and interactive web pages.
What’s next
ECMAScript (ES) is a scripting language specification that is used to create web applications. ES7, ES8, and ES9 are the seventh, eighth, and ninth versions of the ECMAScript specification, respectively. Each new version of ECMAScript introduces new features and improvements to the language. Here are some of the new features introduced in ES7, ES8, and ES9:
ES7:
- Array.prototype.includes(): This method checks if an array includes a certain element and returns a boolean value.
- Exponentiation operator (**): This operator raises the left operand to the power of the right operand.
ES8:
- Async functions: This feature allows developers to write asynchronous code using the async/await syntax, which makes it easier to read and write asynchronous code.
- Object.values(): This method returns an array of the values of an object’s properties.
- Object.entries(): This method returns an array of an object’s key-value pairs.
ES9:
- Rest/Spread Properties: This feature allows developers to use the spread (…) operator on objects as well as arrays.
- Asynchronous Iteration: This feature allows developers to iterate over asynchronous data sources using the for-await-of loop.
- Promise.prototype.finally(): This method allows developers to run code after a Promise is settled, whether it was fulfilled or rejected.
These are just a few of the new features introduced in ES7, ES8, and ES9. Each new version of ECMAScript brings new features and improvements to the language, making it easier and more efficient for developers to create web applications.
Sure, here’s an example of each:
Array.prototype.includes()
const arr = [1, 2, 3, 4, 5];
console.log(arr.includes(3)); // true
console.log(arr.includes(6)); // false
Exponentiation operator (**)
console.log(2 ** 3); // 8
console.log(10 ** -1); // 0.1
console.log(2 ** 3 ** 2); // 512
In the above example, the first line raises 2 to the power of 3, which is 8. The second line raises 10 to the power of -1, which is 0.1. The third line raises 3 to the power of 2, which is 9, and then raises 2 to the power of 9, which is 512.
ES8 (ECMAScript 2017) is a version of JavaScript that introduced several new features and improvements. Here are some examples of the new features in ES8:
- Async functions:
Async functions are a new way to write asynchronous code in JavaScript. They allow developers to write asynchronous code using the async/await syntax, which makes it easier to read and write asynchronous code. Here is an example of an async function:
async function getData() {
const response = await fetch('https://api.example.com/data');
const data = await response.json();
return data;
}
In this example, the getData
function is declared as async
, which means it returns a promise. The await
keyword is used to wait for the fetch
and json
methods to complete before returning the data.
- Object.values():
The Object.values()
method returns an array of the values of an object’s properties. Here is an example:
const obj = { a: 1, b: 2, c: 3 };
const values = Object.values(obj);
console.log(values); // [1, 2, 3]
In this example, the Object.values()
method is used to get an array of the values of the obj
object.
- Object.entries():
The Object.entries()
method returns an array of an object’s key-value pairs. Here is an example:
const obj = { a: 1, b: 2, c: 3 };
const entries = Object.entries(obj);
console.log(entries); // [['a', 1], ['b', 2], ['c', 3]]
In this example, the Object.entries()
method is used to get an array of the key-value pairs of the obj
object.
These are just a few examples of the new features in ES8. Other features include string padding, shared memory and atomics, and more.
ES8 New Features
ES8, also known as ECMAScript 2017, introduced several new features to the JavaScript language. Some of the notable features are:
String Padding
The padStart()
and padEnd()
methods were introduced to add padding to strings.
const str = 'hello';
console.log(str.padStart(10, '1234')); // "12341hello"
console.log(str.padEnd(10, '1234')); // "hello12341"
Shared Memory and Atomics
ES8 introduced a new SharedArrayBuffer
object that allows multiple JavaScript threads to share the same memory. The Atomics
object provides atomic operations on shared memory.
const buffer = new SharedArrayBuffer(16);
const view = new Int32Array(buffer);
Atomics.store(view, 0, 42);
console.log(Atomics.load(view, 0)); // 42
Object.values() and Object.entries()
The Object.values()
and Object.entries()
methods were introduced to make it easier to work with objects.
const obj = { a: 1, b: 2, c: 3 };
console.log(Object.values(obj)); // [1, 2, 3]
console.log(Object.entries(obj)); // [["a", 1], ["b", 2], ["c", 3]]
ES9, also known as ECMAScript 2018, introduced several new features to the JavaScript language. Here are some examples of the new features:
Rest/Spread Properties
The rest/spread properties feature allows developers to use the spread (…) operator on objects as well as arrays. This makes it easier to copy and merge objects and arrays.
Example:
const obj1 = { a: 1, b: 2 };
const obj2 = { ...obj1, c: 3 };
console.log(obj2); // { a: 1, b: 2, c: 3 }
const arr1 = [1, 2, 3];
const arr2 = [...arr1, 4, 5];
console.log(arr2); // [1, 2, 3, 4, 5]
Asynchronous Iteration
The asynchronous iteration feature allows developers to iterate over asynchronous data sources using the for-await-of loop. This makes it easier to work with asynchronous data sources such as Promises and async generators.
Example:
async function* asyncGenerator() {
yield 1;
yield 2;
yield 3;
}
(async function() {
for await (const num of asyncGenerator()) {
console.log(num);
}
})();
Promise.prototype.finally()
The Promise.prototype.finally() method allows developers to run code after a Promise is settled, whether it was fulfilled or rejected. This makes it easier to perform cleanup tasks after a Promise is complete.
Example:
fetch('https://jsonplaceholder.typicode.com/todos/1')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error))
.finally(() => console.log('Fetch complete'));
Sure, here’s an overview of some of the new features introduced in JavaScript ES10, ES11, and ES12:
ES10
Array.flat() and Array.flatMap()
The Array.flat()
method creates a new array with all sub-array elements concatenated into it recursively up to the specified depth. The Array.flatMap()
method first maps each element using a mapping function, then flattens the result into a new array.
const arr = [1, 2, [3, 4]];
const flattenedArr = arr.flat(); // [1, 2, 3, 4]
const arr2 = [1, 2, 3];
const mappedArr = arr2.flatMap(x => [x * 2]); // [2, 4, 6]
String.trimStart() and String.trimEnd()
The String.trimStart()
method removes whitespace from the beginning of a string, while String.trimEnd()
removes whitespace from the end of a string.
const str = ' hello world ';
const trimmedStr = str.trimStart().trimEnd(); // 'hello world'
Object.fromEntries()
The Object.fromEntries()
method transforms a list of key-value pairs into an object.
const entries = [['a', 1], ['b', 2]];
const obj = Object.fromEntries(entries); // {a: 1, b: 2}
ES11
Optional Chaining
Optional chaining allows you to access nested properties of an object without having to check if each property exists.
const obj = {a: {b: {c: 1}}};
const c = obj?.a?.b?.c; // 1
Nullish Coalescing
The nullish coalescing operator (??
) returns the first operand if it is not null
or undefined
, otherwise it returns the second operand.
const foo = null ?? 'default'; // 'default'
const bar = 0 ?? 'default'; // 0
ES12
BigInt
The BigInt
data type allows you to represent integers larger than Number.MAX_SAFE_INTEGER
.
const bigInt = 9007199254740991n + 1n; // 9007199254740992n
Promise.any()
The Promise.any()
method takes an array of promises and returns a new promise that is fulfilled with the value of the first promise that is fulfilled.
const promises = [
Promise.reject('error 1'),
Promise.resolve('success'),
Promise.reject('error 2')
];
Promise.any(promises)
.then(result => console.log(result)) // 'success'
.catch(error => console.log(error));
Logical Assignment Operators
The logical assignment operators (&&=
, ||=
, and ??=
) combine logical operators with assignment operators.
let x = 1;
x &&= 2; // x is now 2
let y = null;
y ??= 'default'; // y is now 'default'
The logical assignment operators in ES12 are a shorthand way of combining logical operators with assignment operators. They are used to assign a value to a variable based on the result of a logical operation.
For example, let’s say we have a variable x
that we want to assign a value to based on the result of a logical operation. We can use the logical assignment operator &&=
to do this in one line of code.
let x = 5;
let y = 10;
x &&= y;
console.log(x); // Output: 10
In this example, the &&=
operator checks if x
is truthy. Since x
is truthy, it assigns the value of y
to x
. If x
had been falsy, it would have assigned false
to x
.
Another example is using the ||=
operator to assign a default value to a variable if it is falsy.
let x = null;
let y = 10;
x ||= y;
console.log(x); // Output: 10
In this example, x
is falsy, so the ||=
operator assigns the value of y
to x
.
The ??=
operator is used to assign a default value to a variable if it is null
or undefined
.
let x = null;
let y = 10;
x ??= y;
console.log(x); // Output: 10
In this example, x
is null
, so the ??=
operator assigns the value of y
to x
. If x
had been undefined
, it would have also assigned y
to x
.
Conclusions
In conclusion, this JavaScript for beginners crash course has covered a wide range of topics that are essential for anyone looking to learn JavaScript. We started with an introduction to JavaScript, its importance, and why it is worth learning. We then moved on to the first steps of setting up a development environment and writing our first JavaScript program.
We then delved into the different data types and primitives, including variables, constants, strings, numbers, and booleans. We also covered operators and how they can be used to manipulate data.
Functions were also a key topic in this course, and we learned how to define and call functions, as well as how to use parameters and arguments. We also explored return values and how they can be used to pass data between functions.
Object-oriented programming was another important topic, and we learned about objects, classes, properties, and methods. We also covered inheritance and polymorphism, which are key concepts in object-oriented programming.
Finally, we explored the Document Object Model (DOM) and how it can be used to manipulate HTML elements on a web page. We learned how to select and manipulate elements, as well as how to handle events.
Overall, this crash course has provided a solid foundation for anyone looking to learn JavaScript. We have covered a lot of ground, including new features for es8 to 12, and I hope that you have found this course informative and helpful. With practice and continued learning, you can become proficient in JavaScript and use it to build dynamic and interactive web applications.